A for loop executes some code a fixed number of times and has a variable (called an index) that updates. The next few examples are not practical, but are designed to illustrate the syntax and what is possible. The following is a simple for loop that prints out the numbers 1 to 10
If you want to skip numbers or count backwards, a range in the form
start:
skip:
stop is used. The following starts at 1 and skips by 2 up to 21:
and the following starts at 10, counting down to 1:
for i=10:-1:0
@show i
end
We can use the
for var in list form to go through elements in a list or array (or tuple). The following adds all numbers in the list (array)
[1,5,7,11,20]:
let
local sum=0
for i in [1,5,7,11,20]
sum += i
end
sum
end
Recall that in
Section 4.6 we used this in the formation to find the mean:
function theMean(x::Number...)
local s = 0
for val in x
s += val
end
s/length(x)
end
Subsection 5.5.1 While Loops Versus For Loops
No this, isn’t a smackdown between while and for loops. A big question often is when I have a problem that I want to solve and I know a loop is needed, when should I use a
while loop and when should I use a
for loop. The general rule of thumb is:
-
If you know that you need to run code for a fixed number of times, use a for loop
-
If you don’t use a while loop. Generally, the
doing something in the loop will affect how many times the loop is run.
Notice in the examples above, the bisection method used a
while loop because it is unclear when you start how many times you want to go through the loop. Instead we stopped in while the interval was small enough.
In the summing of the terms for the mean, a for loop was used because of the fixed number of values in the tuple
x.
Subsection 5.5.2 Adapting While loops as For Loops
As just mentioned above, generally if we don’t know how many times we go through a loop that a while loop should be used. Let’s say we have a game that we roll a die. If we roll the die 10 times without rolling a 1, we win and if a 1 appears fewer than 10 times, we lose. Here’s a function that we can use to play this game.
function playDieGame()
local roll = rand(1:6)
@show roll
local n = 1
local win = roll != 1
while roll != 1 && n <=10
roll = rand(1:6)
@show roll
win = false
n += 1
end
win
end
This starts with a roll of the die with
rand(1:6). We also have the variable
n that will store the number of rolls and
win is whether or not we win the game. At this point
win is assumed
true unless
roll == 1. The condition on the while loop is that the roll is not 1 and that the number of rolls is less than or equal to 10. A possible output is
roll = 6
roll = 5
roll = 1
false
We will discuss random numbers in detail in
Chapter 18 and if you run this function, you will get different results, but should see rolls until a 1 is reached. If it 1, the result is
false that you win and
true if not. Try running this function a number of times.
If this seems complicated, it is more complicated than it needs to be. If we take the premise that since we don’t know how many times this is run, we need to use a
while then that complicates things then we need to have conditions on both the roll and the number of rolls (this is how the game is determined) and these both need to be set before the while loop.
Instead, we will use a
for loop and break out (or actually just
return) during the winning and losing conditions. Here’s an update of the code:
function playDieGame()
for n=1:10
local roll = rand(1:6)
@show roll
roll == 1 && return false
n == 10 && return true
end
end
Try running this code and you should see that it behaves the same way as above.
Notice that first we didn’t need to define
roll before the loop and
n is now the index of the for loop. Also, we didn’t define a
win variable. Instead, notice that if
roll == 1 we just
return false and if
n == 10 we
return true.
If also, we don’t care about seeing the rolls, we can simplify this further with
function playDieGame()
for n = 1:10
rand(1:6) == 1 && return false
n == 10 && return true
end
end
We simplify further in that there is no reason to check that
n == 10 each time through the loop. If we make it through the loop, then we have gone 10 times and thus we win. Here’s an even shorter version of the game:
function playDieGame()
for n = 1:10
rand(1:6) == 1 && return false
end
true
end
And if you compare this to the original function above, it’s much shorter. There is only one other feature to note. The variable
n is never used, it is simply there as the index of the for loop. If this is true, in Julia style, we replace the variable with the _ character (which is technically a variable name) so our final version is
function playDieGame()
for _ = 1:10
rand(1:6) == 1 && return false
end
true
end
Subsection 5.5.3 Using break and continue with for loops
Although we introduced both
break and
continue statements in while loops above, they can also be used in for loops. Although these are not very practical examples, nevertheless this shows how they are used.
In this example, we will defined a loop from 1 to 10 and then break out of it after going through 5 times.
for n=1:10
@show n
n == 5 && break
end
And in this example, we will print out only odd numbers
for n=1:10
n % 2 == 0 && continue
@show n
end