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

Julia, lesson 5

Loops

Loops run a block of code again and again. Julia has two: for and while. Both end with end, like every other block.

for loops

A for loop takes each value of a collection in turn. The most common collection is a range: 1:5 means 1, 2, 3, 4, 5, and 10:-2:0 means 10, 8, 6, 4, 2, 0 (start, step, stop).

You can loop over anything that holds several values, including the lines from readlines():

A range like 1:0 is simply empty, so a loop over 1:n correctly runs zero times when n is 0.

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Guess the number

Press Ctrl Enter or Check to test your code.

while loops

A while loop repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need:

Make sure the body moves the condition towards false, or the loop never ends.

break and continue

  • break leaves the loop at once.
  • continue skips the rest of this round and goes on with the next one.

Updating a variable from a loop: the scope rule

There is one Julia rule you must know when you write loops at the top level of a script. A loop body has its own scope. If the loop assigns to a variable that already exists outside it, Julia cannot tell whether you mean the outside variable or a new one inside the loop. In a script it warns about the ambiguity and treats it as a new local variable, so code like this fails with an UndefVarError:

Say what you mean with the global keyword:

This applies to top-level for and while loops in a file. Inside a function (next lesson) the problem disappears, and that is the usual Julia style: put your program's work in functions.

Counting and accumulating

Most loops follow one of a few patterns: count how often something happens, keep a running total, or remember the best value so far. Start the variable before the loop, update it inside, use it after.

Further reading

  • Julia manual: Control flow, repeated evaluation
  • Julia manual: Scope of variables

Read a whole number n and print the first 10 lines of its times table, in the form n x i = product.

Sample input:

Sample output:

The first input line is the secret number. Every following line is a guess. For each guess, print higher if the secret is bigger, lower if it is smaller, and stop at the first correct guess, printing correct, guesses used: N (counting the correct one). If the guesses run out without a correct one, print out of guesses.

Sample input:

Sample output:

for i in 1:3
    println("Lap $i")
end
for line in readlines()
    println("> ", line)
end
n = 1
while n < 100
    n *= 2
end
for n in 1:10
    n % 2 == 0 && continue   # skip even numbers
    n > 7 && break           # stop after 7
    print(n, " ")
end
println()                    # prints: 1 3 5 7
total = 0
for x in 1:3
    total += x     # error in a script: which `total`?
end
total = 0
for x in 1:3
    global total += x
end
println(total)     # 6
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
42
50
25
42
10
lower
higher
correct, guesses used: 3