Breaks and Continues
Sometimes while you are executing a loop, you might like to skip something, at those times you can use a key word called continue
. Let’s say that I don’t want 6 getting printed when I write a program to print 1 to 10, I can write a program like this:
i = 0
while i < 10
i += 1
if i == 6
continue
end
println(i)
end
Output:
1
2
3
4
5
7
8
9
10
Look at these lines of code in the above example:
if i == 6
continue
end
It tells Julia to continue to next iteration if i
equals 6
, so the statement that comes after it, that is in this case println(i)
won’t get executes when i
is 6
, and it will go to the next iteration and i
will become 7
and the loop will go on normally. So seeing this why can’t you write a program that prints only even numbers or odd numbers below a given value in the number line?
continue
tells Julia to skip operation and go on to next iteration, break
tells it to break out of the loop entirely. Type the program below in your notebook and execute it:
i = 1
while i <= 10
println(i)
if i == 6
break
end
i += 1
end
Output:
1
2
3
4
5
6
Here when i
is 6
, in these lines:
if i == 6
break
end
when i==6
becomes true, and break
will get executed, and the program breaks out of the loop. Hence only 1 to 6 gets printed and the loop breaks.
A very similar implementation of the above programs is given below using for
loop for continue
:
for i in 1:10
if i == 6
continue
end
println(i)
end
Output:
1
2
3
4
5
7
8
9
10
and this one is for break
:
for i in 1:10
println(i)
if i == 6
break
end
end
Output:
1
2
3
4
5
6
The notebook for this blog can be found here https://gitlab.com/data-science-with-julia/code/-/blob/master/breaks_and_continues.ipynb.