question archive Write and test Ruby scripts for the two exercises that follow, debug (if necessary)
Subject:Computer SciencePrice:2.87 Bought3
Write and test Ruby scripts for the two exercises that follow, debug (if necessary).
Write a Ruby program that takes keyboard input of three names, each from its own line. Then output the names in alphabetical order. For this assignment do not use arrays.
Write a Ruby program that takes keyboard input of six numbers, each from its own line. Then output the largest, smallest, average, total of the inputs.
Answer:
Since in first question we are advised not to use array , so for sorting i have to use multiple if-else statement:
Code:
name1 = gets.chomp
name2 = gets.chomp
name3 = gets.chomp
if name1 < name2 && name1 < name3
if name2 < name3
puts name1 + " " + name2 + " " + name3
else
puts name1 + " " + name3 + " " + name2
end
elsif name2< name1 && name2 < name3
if name1 < name3
puts name2 + " " + name1 + " " + name3
else
puts name2 + " " + name3 + " " + name1
end
else
if name1 < name2
puts name3 + " " + name1 + " " + name2
else
puts name3 + " " + name2 + " " + name1
end
end
Output:
Code:
#nitialize an array with size of 6
numbers = Array.new(6)
#take 6 numbers from user
for i in 0..5
numbers[i] = gets.chomp.to_i
end
#find the biggest number, smallest number, total
biggest_num = numbers[0]
smallest_num = numbers[0]
total = numbers[0]
for i in 1..5
#for biggest_num
if biggest_num < numbers[i]
biggest_num = numbers[i]
end
#for smallest_num
if smallest_num > numbers[i]
smallest_num = numbers[i]
end
#total
total = total + numbers[i]
end
#print all
puts "Biggest: " + biggest_num.to_s
puts "Smallest: " + smallest_num.to_s
puts "Average: "+ (total/6).to_s
puts "Total: " + total.to_s
Screenshots and outputs:
PFA