Reputation: 471
I am trying to understand nested loops by getting this program to work. I'd like to use the "each do" way of looping, if possible. Right now the loop executes all of the 1st loop, then 2nd...etc...I'd like to do, execute 1st loop 1 time, then fall down to 2nd loop one time...etc. Here is my code (pasted below)
Desired output would be something like this:
index 3.0 3.0
+-------------------------------------------------------+
0 -23.4 -23.4
1 -2226.74 -2226.74
2 -1.93464e+07 -1.93464e+07
class LogisticsFunction
puts "Enter two numbers, both between 0 and 1 (example: .25 .55)."
puts "After entering the two numbers tell us how many times you"
puts "want the program to iterate the values (example: 1)."
puts "Please enter the first number: "
num1 = gets.chomp
puts "Enter your second number: "
num2 = gets.chomp
puts "Enter the number of times you want the program to iterate: "
iter = gets.chomp
print "index".rjust(1)
print num1.rjust(20)
puts num2.rjust(30)
puts "+-------------------------------------------------------+"
(1..iter.to_i).each do |i|
print i
end
(1..iter.to_i).each do |i|
num1 = (3.9) * num1.to_f * (1-num1.to_f)
print num1
end
(1..iter.to_i).each do |i|
num2 = (3.9) * num2.to_f * (1-num2.to_f)
print num2
end
end
Upvotes: 3
Views: 12747
Reputation: 27747
Your loops aren't actually nested. They are in fact one after the other. This is why they are running one after the other. To nest them - you have to put them inside of each other. eg:
Not nested
(1..iter.to_i).each do |i|
# stuff for loop 1 is done here
end # this closes the first loop - the entire first loop will run now
(1..iter.to_i).each do |j|
# stuff for loop 2 is done here
end # this closes the second loop - the entire second loop will run now
Nested:
(1..iter.to_i).each do |i|
# stuff for loop 1 is done here
(1..iter.to_i).each do |j|
# stuff for loop 2 is done here
end # this closes the second loop - the second loop will run again now
# it will run each time the first loop is run
end # this closes the first loop - it will run i times
Upvotes: 4
Reputation: 7288
I think you don't have to run with three loop, following will give the desire output
(1..iter.to_i).each do |i|
print i
num1 = (3.9) * num1.to_f * (1-num1.to_f)
print num1.to_s.rjust(20)
num2 = (3.9) * num2.to_f * (1-num2.to_f)
print num2.to_s.rjust(30)
end
Upvotes: 4
Reputation: 646
Wouldnt something like this solve your problem?
(1..iter.to_i).each do |i|
num1 = (3.9) * num1.to_f * (1-num1.to_f)
print num1
num2 = (3.9) * num2.to_f * (1-num2.to_f)
print num2
end
From what I can see you dont even use the i
variable. So in theory you could just do
iter.to_i.times do
# stuff
end
Upvotes: 1