101 -loops Flashcards

1
Q

What is another way to write this loop condition?

say_hello = true
counter = 0
while say_hello
  puts 'Hello!'
  counter += 1
  say_hello = false if counter == 5   
end
A
say_hello = true
counter = 0
while say_hello
  puts 'Hello!'
  counter += 1
  if counter == 5
    say_hello = false
  end
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Using a while loop, print 5 random numbers between 0 and 99.

numbers = []
while
# …
end

A

numbers = [ ]

while numbers.size

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Modify the code so that it counts from 1 to 10 instead.

count = 10

until count == 0
puts count
count -= 1
end

A

count = 1

until count > 10
puts count
count += 1
end

puts count

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Given the array of several numbers below, use an until loop to print each number.

numbers = [7, 9, 13, 25, 18]

A
numbers = [7, 9, 13, 25, 18]
count = 0
until count == 5 (or)
until count == numbers.size
   numbers[count]
   count += 1
end
   puts numbers
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

use a for loop to greet each friend individually.

friends = [‘Sarah’, ‘John’, ‘Hannah’, ‘Dave’]

A

friends = [‘Sarah’, ‘John’, ‘Hannah’, ‘Dave’]

for friend in friends
puts “ Hello #{friend}”
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a loop that prints numbers 0-5 and whether the number is even or odd.

count = 1

loop do
count += 1
end

A

count = 1

loop do
    if count.odd?
       puts "number #{count} is odd" 
    else
      puts "number #{count} is even"
    end

break if count == 5
count += 1
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly