Looping Flashcards
How do you make a loop method using the loop construct?
loop do #your code here end
How many times will the following code run?
loop do #your code here end
An infinite amount of times.
How many times will the following code run?
loop do #your code here break end
Once
How many times will the following code run?
counter = 0
loop do
counter = counter + 1
puts “Iteration #{counter} of the loop”
if counter >= 10
break
end
end
10 times
How can we rewrite the following code using += instead?
counter = counter + 1
counter += 1
What does the following code do to the variable age?
age = 20
age += 1
Reassigns the variable age to the value of 21
How do you make a loop method using the times construct?
5.times do
puts “Penguins like to jump off icebergs!”
end
How many times will the following code run?
7.times do
puts “I am doing the dishes left by my former friends.”
end
7 times.
What will the value of jewels_in_bag be after the code has run?
jewels_in_bag = 100
3.times do
puts “Hiding 10 stolen jewels.”
jewels_in_bag = jewels_in_bag - 10
end
70
How can we rewrite the following code using -= instead?
jewels_in_bag = jewels_in_bag - 10
jewels_in_bag -= 10
How many times will the following code run?
x=0
while x < 10 do
puts “so many loops”
end
An infinite amount of times.
True or False: The line in the following loop puts “Hi” will never run.
10.times do
break
puts “Hi”
end
True
The break stops the loop from reaching the line puts “Hi”
How would you read this code in sentences?
counter = 0 while counter < 20 puts "The current number is less than 20." counter += 1 end
Variable counter is 0.
While counter is less than 20, output “The current number is less than 20.”, then increment counter by 1.
How would you read this code in sentences?
counter = 0 until counter == 20 puts "The current number is less than 20." counter += 1 end
Variable counter is 0.
Until counter is equal to 20, output “The current number is less than 20.”, then increment counter by 1.
How is the until loop different from the while loop?
Until is simply the inverse of a while loop. An until keyword will keep executing a block until a specific condition is true. In other words, the block of code following until will execute while the condition is false. One helpful way to think about it is to read until as “if not”.