Find largest element in array without using max function in Ruby



Write a program to find largest element in array without using max function in Ruby

class LargestElement
  def findLargestElement
    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 
    max = array.first
    print "Input array is: #{array}"
    array.each do |n|
      max = n if max < n
    end
    print "\nLargest element of array is: #{max}"
  end
end

p = LargestElement.new 
p.findLargestElement

Output:


Enter the size of array 5
Enter the elements of array 44
 66
 22
 99
 77
Input array is: [44, 66, 22, 99, 77]
Largest element of array is: 99


No comments:

Post a Comment