Find second largest number from an array in Ruby



Find second largest number from an array in Ruby

class SecondLargestElement
  def findSecondLargestElement
    print "Enter the size of array"
    size = gets.chomp.to_i
    print "Enter the elements of array"
    count = 0
    array = []
    while count < size do 
      array.push(gets.chomp.to_i)
      count = count + 1
    end 
    print "Input array is: #{array}"
    second_largest = array.sort[-2]
    print "\nSecond largest element of array is: #{second_largest}"
  end
end

p = SecondLargestElement.new 
p.findSecondLargestElement

Output:


Enter the size of array 5
Enter the elements of array 77
 44
 66
 88
 99
Input array is: [77, 44, 66, 88, 99]
Second largest element of array is: 88


No comments:

Post a Comment