Control Flow#

Learning Objectives#

  • Understand and use conditional statements (if, else, elseif) in Julia

  • Implement for and while loops to execute repetitive tasks

  • Recognise how control flow structures manage the execution of code based on conditions

  • Write programs that use loops and conditional statements to solve problems

  • Gain awareness of some utility functions for iteration

Control flow statements allow your program to make decisions (with conditionals) and repeat actions (with loops). Julia’s control flow syntax will look familiar if you’ve used languages like Python, C or others, but there are some syntax differences to note; for example, Julia uses end to close blocks.

Conditional Statements (Branching)#

Julia uses if, elseif (note the single word, not else if), and else to execute code based on conditions. The general structure is:

if <condition1>
    # code to run if condition1 is true
elseif <condition2>
    # code to run if condition1 was false, but condition2 is true
else
    # code to run if all above conditions are false
end

The elseif and else parts are optional (use them as needed). You can have multiple elseif branches if there are several conditions to check in sequence.

A simple example of the branching logic would be to determine if a number x is positive, negative, or zero:

# Check whether a number is positive, zero or negative
x = 0
if x < 0
    println("x is negative")
elseif x == 0
    println("x is zero")
else
    println("x is positive")
end
x is zero

A few things to note about conditional statements:

  • You must end the if block with an end.

  • Each condition in the if / ifelse statements can be written without parentheses (though you may wish to use parentheses for complex expressions).

  • In Julia, the conditions must be boolean (Bool) objects. Python, by contrast, allows you to write if some_list: to enter the if branch if some_list is non-empty. In Julia, if some_array will throw an error - in this case you should explicitly check the length e.g. if length(some_array) > 0.

  • Similarly, you cannot use nothing in place of a condition: if nothing will throw an error. Again, this is different to the analogous statement if None: in Python.

Loops#

Loops are used to repeat a block of code multiple times. Julia provides for loops and while loops for iterations.

For Loops#

A for loop is used to iterate over a sequence (like a range of numbers or elements of an array). The syntax is:

for var in sequence
    # loop body using var
end

For example, to print numbers 1 through 5:

# Print numbers 1 to 5
for i in 1:5
    println(i)
end
1
2
3
4
5

Here, 1:5 is a range representing the sequence 1,2,3,4,5 (note that the last number in the range is included!). The loop variable i takes each of those values in turn.

Instead of using the in keyword you can use =, like so:

for i = 1:5
    println(i)
end

You can loop over any iterable object using the same for ... in ... notation:

# Loop over elements of an array
for letter in ["c", "a", "t"]
    print(letter)
end
cat

For array-like objects, if you need to loop through the indices then one convenient approach is to use the built-in function eachindex. For example, to print each element with its index, we could write:

# Loop through the indices of an array
arr = ["apple", "banana", "cherry"]
for idx in eachindex(arr)
    println("Element ", idx, " is ", arr[idx])
end
Element 1 is apple
Element 2 is banana
Element 3 is cherry

Observe that Julia arrays are 1-indexed!

Exercise: For loops and conditionals#

Write code to iterate over the numbers 1 to 20 and println the number, but if the number is divisible by 7 then additionally print the word “Boom!” on the same line. Hint: You might want to use the modulus operator!

# Answer here

While Loops#

A while loop repeats as long as a given condition remains true. It’s useful when you don’t know in advance how many times to loop, but you have a condition to check each time. The syntax for a while loop is:

while <condition>
    # code to run repeatedly
end

The loop will check the condition before each iteration and stop when the condition becomes false. For example:

# Count down to blastoff
x = 5
while x > 0
    println(x)
    x -= 1  # decrease x by 1 each time (x -= 1 is shorthand for x = x - 1)
end
println("Blastoff!")
5
4
3
2
1
Blastoff!

A key thing to remember when using while loops is to avoid infinite loops by making sure that something in the loop eventually makes the condition false.

Note: just like with if blocks, loops in Julia must be closed with an end and the loop conditions must be booleans.

Exercise: While Loops#

Write a while loop that starts with a number n = 1 and repeatedly doubles it (i.e., n*= 2) until n exceeds 1,000,000. What is the final value of n when the loop stops?

# Answer here

Breaking and Continuing Loops#

Within loop bodies, you can use break to immediately exit the loop (stop looping entirely) and continue to skip the rest of the current iteration and move to the next iteration of the loop. For example:

# Print only the odd numbers from 1 to 10
for i in 1:10
    if i % 2 == 0
        continue  # skip even numbers
    end
    println(i)    # this runs only if i was not even
end
1
3
5
7
9

If instead of skipping even numbers you want to stop the loop entirely when you see the first even, you would use break in place of continue.

Ternary Operator#

Julia’s ternary operator lets you write simple if–else expressions on one line:

# If `condition` is true, the return `true_expr`, otherwise return `false_expr`
condition ? true_expr : false_expr

For example, to capture whether a number is positive or negative:

# Determine the sign of a number
x = -5
sign = x >= 0 ? "positive" : "negative"
println(sign)
negative

Exercise: a pair of close random numbers#

The function rand can be used to generate a random floating point number between 0 and 1. Write code that continually generates a pair of random numbers x1, x2 until they are only 0.05 apart, printing the resulting pair (we have started the code for you below).

Hint:

  • You will need to compute the absolute value of the difference between x1 and x2. Consider using the ternary operator.

# Generate a pair of random numbers
x1 = rand();
x2 = rand();

# Answer here

Iteration Utilities#

Julia provides a number of handy iterator helpers in the Base.Iterators module. Two of the most common are zip and enumerate, but there are many more. See the Iteration utilities section of the manual for details.

  • zip: Iterate in lockstep over two or more collections, yielding tuples of corresponding elements.

  • enumerate: Iterate over a single collecton while keeping track of the index, yielding (index, element) pairs.

# Example `zip` usage 
names = ["Alice", "Bob", "Carol"]
scores = [85, 92, 78]

for (name, score) in zip(names, scores)
  println("$name scored $score")
end

# Example `enumerate` usage 
fruits = ["apple", "banana", "cherry"]
for (i, fruit) in enumerate(fruits)
    println("Fruit $i is $fruit")
end
Alice scored 85
Bob scored 92
Carol scored 78
Fruit 1 is apple
Fruit 2 is banana
Fruit 3 is cherry

End of Section Quiz#

What keyword does Julia use to close a conditional or loop block?

Which of the following correctly describes the syntax of a for loop in Julia?