Find smallest element in array without using min function in Ruby



Write a program to find smallest element in array without using min function in Ruby

class SmallestElement
  def findSmallestElement
    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 
    min = array.first
    print "Input array is: #{array}"
    array.each do |n|
      min = n if min > n
    end
    print "\nSmallest element of array is: #{min}"
  end
end

p = SmallestElement.new 
p.findSmallestElement

Output:


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


No comments:

Post a Comment