Learn/Crystal/5. Loops
Lesson 5 of 8
Sign in

Crystal, lesson 5

Loops

Computers are great at doing the same thing many times. Crystal has a classic while loop, but most of its repetition is done by methods that take a block, which reads almost like English.

while

while repeats its body as long as the condition is true. It checks the condition before every pass:

Make sure something in the body moves the condition towards false, or the loop never ends. until is the mirror image: until balance >= 200 means the same as the loop above.

Counting with blocks

A block is a chunk of code between do ... end (or { ... } on one line) that a method runs for you. The value it is given appears between bars, like |i|.

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Savings goal

Press Ctrl Enter or Check to test your code.

1..5 is a range that includes both ends; 1...5 (three dots) stops before 5. The block's variable, i here, only exists inside the block.

Looping over input

STDIN.each_line runs a block once for every remaining line of input, without the line break, and stops by itself when the input runs out:

Leaving early: break and next

  • break leaves the loop immediately.
  • next skips the rest of this pass and moves on to the next one (other languages call it continue).

Methods ending in ?, like odd? and even?, return true or false. A common pattern is a loop over the input that breaks as soon as it has what it needs, leaving the rest unread.

Further reading

  • Crystal reference: while
  • Crystal reference: break and next
  • Crystal reference: Blocks and procs
  • API: Int#times, Int#upto

Read a whole number n and print its times table from 1 to 10, one line each, in this form:

Input: one line with n (it may be 0 or negative). Output: exactly ten lines.

You are saving up for a bike. Read your savings goal, then a list of deposits. Count how many deposits it takes for the total to reach the goal (equal counts as reached). Stop reading deposits as soon as you get there.

Input: the first line is the goal (at least 1). Each following line is one deposit (a whole number of 0 or more). There may be no deposits at all.

Output: if the goal is reached, print Goal reached! Deposits used: K. Otherwise print Short by X. where X is how much is still missing.

prints Goal reached! Deposits used: 3

balance = 100
years = 0
while balance < 200
  balance += balance // 10
  years += 1
end
puts "Doubled after #{years} years"
3.times do |i|
  puts "Lap #{i}"          # Lap 0, Lap 1, Lap 2
end

(1..5).each do |i|
  puts i                   # 1 to 5
end

1.upto(3) { |i| puts i }   # 1, 2, 3
5.downto(1) { |i| puts i } # 5, 4, 3, 2, 1
STDIN.each_line do |line|
  puts "You typed: #{line}"
end
(1..100).each do |n|
  next if n.odd?      # skip odd numbers
  break if n > 10     # stop completely after 10
  puts n              # 2, 4, 6, 8, 10
end
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
100
30
50
40
10