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

Groovy, lesson 5

Loops

Loops let you repeat work: count down, add up prices, read input until it ends. Groovy supports Java's classic loops and adds a few shortcuts of its own.

for over a range

A range is written start..end and includes both ends. start..<end stops just before the end. A for ... in loop visits each value:

Ranges can count down too: 5..1 gives 5, 4, 3, 2, 1. Careful, though: because a range always goes from its first to its last value, 0..1 and 1..0 are both two-element ranges. If the end might be past the start, guard the loop or use a classic for.

The classic for loop

2 exercises to try what you just read.

Exercise 1

Countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Total until zero

Press Ctrl Enter or Check to test your code.

Groovy also accepts Java's three-part loop: a start, a condition checked before each round, and an update after each round:

If the condition is false at the start, the body never runs, which makes it a safe choice when the number of rounds may be zero.

Loop shortcuts

Numbers and ranges have methods that take a closure, a block of code in braces. Inside a one-parameter closure, the current value is called it:

These read nicely for simple repetition. You'll learn more about closures in the next lesson.

while loops

A while loop repeats as long as its condition is true. It is the natural choice when you don't know in advance how many rounds you need, such as reading input until it runs out:

Make sure something inside the loop eventually makes the condition false, or the loop never ends.

Early exit: break and continue

break leaves the loop immediately. continue skips the rest of the current round and moves on to the next one:

break and continue work in for and while loops, but not inside closures such as each: a closure is a separate block of code, not part of the loop syntax. When you need to stop early, use a real loop.

Further reading

  • Semantics: looping structures
  • Groovy development kit: ranges and numbers

Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, then print Liftoff!.

Sample input:

Sample output:

Watch the edge case n = 0: only Liftoff! should be printed.

A cashier types prices, one per line, and types 0 when the order is complete. Read the prices and print the total of everything before the first 0. Anything after the 0 belongs to the next customer and must be ignored. There is always a 0 in the input.

Sample input:

Sample output:

for (lap in 1..3) {
    println "Lap ${lap}"
}
for (int i = 10; i > 0; i -= 3) {
    println i            // 10, 7, 4, 1
}
3.times { println "Hip hip hooray!" }     // runs 3 times
(1..3).each { println "Item ${it}" }
10.downto(8) { println it }              // 10, 9, 8
1.step(10, 3) { println it }             // 1, 4, 7
def reader = System.in.newReader()
def line
while ((line = reader.readLine()) != null) {
    println "Got: ${line}"
}
for (n in 1..10) {
    if (n % 2 == 0) continue     // skip even numbers
    if (n > 7) break             // stop completely after 7
    println n                    // 1, 3, 5, 7
}
3
3
2
1
Liftoff!
12
5
8
0
25