Road to Julia 3: Loops and Conditionals

Loops

Loops are used in programming for evaluating the same expressions repeatedly. Julia supports two types of loopswhile and for.

while loops

In general, while loops are used to continually execute a section of code until a condition is met. The conditions can be anything that can be evaluated to a boolean value (true or false). In Julia they are syntactically denoted by

while condition
...
end

Once the condition is evaluated to false, the loop ends and the code execution continues after the loop. An example while loop may be given by

counter = 0

while counter <= 10
    println(counter)
    global counter += 1
end

NOTE: The required addition of the global keyword inside the loop is a known concern which will likely be resolved in future – it is beyond the scope for this level in any case.

for loops

The second type of loop in Julia is for loops, which use a variable to count the number of times that it has been iterated, and stopping when that reaches a limit. They are delimited by

for iterable
...
end

The iterable is a temporary variable which sequentially takes the values of a range or set, executing the sequence for each value. A simple example is counting to 5:

julia> for i = 1:5
           println(i)
       end
1
2
3
4
5

Conditionals

Often while programming, one may wish to check whether a condition has been met – to achieve this Julia uses if conditionals. These are written

if condition
...
end

Should the condition evaluate to true then the inner code is executed, otherwise the main code continues. Unlike in many other languages, the condition must be of boolean type (strictly true/false), for example the following code would not run whereas its equivalent in other languages would

if 1
...
end

Multiple conditions may be checked simultaneously by combining them into a single condition using the || (or) and && (and) operators which are evaluated as a single condition, e.g.

julia> x = 1
1

julia> y = 2
2

julia> if x == 1 || y == 1
       println("yay!")
       end
yay!

julia> if x == 1 && y == 1
       println("yay!")
       end

Additional conditions may be checked separately by having elseif conditions, written as

if condition1
...
elseif condition2
...
end

There can be as many elseifs as necessary and as before, conditions may be strung together into single conditions.

Leave a Reply

Your email address will not be published.