Julia Community 🟣

Vinod V
Vinod V

Posted on • Updated on

Control Flow in Julia

Control Flow

In the programs we have seen till now, there has always been a series of statements faithfully executed by Julia in exact top-down order. What if you wanted to change the flow of how it works? For example, you want the program to take some decisions and do different things depending on different situations, such as printing "Good Morning" or "Good Evening" depending on the time of the day?

As you might have guessed, this is achieved using control flow statements. There are three control flow statements in Julia - if, for and while.

The if statement

The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional.

Example (save as if.jl):

number = 23
println("Enter an integer : ")
text = readline()
guess = parse(Int,text)

if guess == number
    # New block starts here
    println("Congratulations, you guessed it.")
    println("(but you do not win any prizes!)")
    # New block ends here
elseif guess < number
    # Another block
    println("No, it is a little higher than that")
    # You can do whatever you want in a block ...
else
    println("No, it is a little lower than that")
    # you must have guessed > number to reach here
end

println("Done")
# This last statement is always executed,
# after the if statement is executed.
Enter fullscreen mode Exit fullscreen mode

Output:

Enter an integer :                     
6                                      
No, it is a little higher than that   
Done
Enter fullscreen mode Exit fullscreen mode

How It Works
In this program, we take guesses from the user and check if it is the number that we have. We set the variable number to any integer we want, say 23. Then, we take the user's guess using the readline() function. Functions are just reusable pieces of programs. We'll read more about them in the next chapter.

We supply a string to the built-in readline function which prints it to the screen and waits for input from the user. Once we enter something and press 'enter' key, the readline() function returns what we entered, as a string. We then convert this string to an integer using parse and then store it in the variable guess. Actually, the Int is a data type but all you need to know right now is that you can use it to convert a string to an integer (assuming the string contains a valid integer in the text).

Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message. Notice that we use indentation levels to tell Julia which statements belong to which block.

Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little higher than that. What we have used here is the elseif clause which actually combines two related if else-if else statements into one combined if-elseif-else statement. This makes the program easier and reduces the amount of indentation required.

The elseif and else statements must also have a colon at the end of the logical line followed by their corresponding block of statements (with proper indentation, of course)

You can have another if statement inside the if-block of an if statement and so on - this is called a nested if statement.

Remember that the elseif and else parts are optional. A minimal valid if statement is:

if true
    print("Yes, it is true")
end
Enter fullscreen mode Exit fullscreen mode

After Julia has finished executing the complete if statement along with the associated elseif and else clauses, it moves on to the next statement in the block containing the if statement. In this case, it is the main block (where execution of the program starts), and the next statement is the print('Done') statement. After this, Julia sees the ends of the program and simply finishes up.

Even though this is a very simple program, I have been pointing out a lot of things that you should notice. All these are pretty straightforward (and surprisingly simple for those of you from C/C++ backgrounds). You will need to become aware of all these things initially, but after some practice you will become comfortable with them, and it will all feel 'natural' to you.

Note for C/C++ Programmers

There is no switch statement in Julia. You can use an if..elseif..else statement to do the same thing (and in some cases, use a Dict to do it quickly). Dict{K,V}() constructs a hash table with keys of type K and values of type V which will be discussed later.

The while Statement

The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause.

Example (save as while.jl):

number = 23
running = true

while running == true
    text1 = readline()
    guess = parse(Int,text1)

    if guess == number
        print("Congratulations, you guessed it.")
        # this causes the while loop to stop
        running = false
    elseif guess < number
        print("No, it is a little higher than that.")
    else
        print("No, it is a little lower than that.")
    end

end
Enter fullscreen mode Exit fullscreen mode

Output:

23
Congratulations, you guessed it.
Enter fullscreen mode Exit fullscreen mode

How It Works

In this program, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly - there is no need to repeatedly run the program for each guess, as we have done in the previous section. This aptly demonstrates the use of the while statement.

We move the input and if statements to inside the while loop and set the variable running to true before the while loop. First, we check if the variable running is true and then proceed to execute the corresponding while-block. After this block is executed, the condition is again checked which in this case is the running variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement.

The else block is executed when the while loop condition becomes false - this may even be the first time that the condition is checked. If there is an else clause for a while loop, it is always executed unless you break out of the loop with a break statement.

The true and false are called Boolean types and you can consider them to be equivalent to the value 1 and 0 respectively.

Note for C/C++/Python Programmers

Remember that you can have an else clause for the while loop.

The for loop

The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. We will see more about sequences in detail in later chapters. What you need to know right now is that a sequence is just an ordered collection of items.

Example (save as for.jl):

for i in 1:4:
    println(i)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
Enter fullscreen mode Exit fullscreen mode

How It Works

In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in : operator.

m:n returns a sequence of numbers starting from the first number and up to the second number. For example, 1:4 gives the sequence [1, 2, 3, 4]. By default, : takes a step count of 1. If we supply a third number to :, then that becomes the step count. For example, 1:2:7 gives [1,3,5,7]. Remember that the range extends to the second number i.e. it does include the second number.

Note that : generates only one number at a time, if you want the full list of numbers, call collect() on the :, for example, collect(1:4) will result in [1, 2, 3, 4].

The for loop then iterates over this range - for i in 1:4 is equivalent to for i = [1, 2, 3, 4] which is like assigning each number (or object) in the sequence to i, one at a time, and then executing the block of statements for each value of i. In this case, we just print the value in the block of statements.

Remember that the for..in loop works for any sequence. Here, we have a list of numbers generated by the built-in : operator, but in general we can use any kind of sequence of any kind of objects! We will explore this idea in detail in later chapters.

Note for C/C++ Programmers

In C/C++, if you want to write for (int i = 0; i < 5; i++), then in Julia you write just for i in 0:4. As you can see, the for loop is simpler, more expressive and less error prone in Julia.

The foreach statement

The foreach statement is an inbuilt function in Julia that is used to call a specified set of instructions on each element of a specified iterable. The syntax for the foreach statement is foreach(f, c...), where f is the specified set of instructions and c is the specified iterable. The function f is called element-wise, and iteration stops when any iterator is finished. The foreach statement should be used instead of map when the results of f are not needed. Below are some code examples of the foreach statement in Julia:

julia> foreach(println,[1,2,3])        
1                                      
2                                      
3                                      
  julia> tri = 1:3:7; res = Int[];

  julia> foreach(x -> push!(res, x^2), tri)

  julia> res
  3-element Vector{Int64}:
    1
   16
   49
julia> foreach((x, y) -> println(x, " with ", y), 1:3:7, 'a':'c')
Enter fullscreen mode Exit fullscreen mode

The break Statement

The break statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become false or the sequence of items has not been completely iterated over.

Example (save as break.jl):

while true
    println("Enter something : ")

    s = readline()    

    if s == "quit"
        break
    end
    println("Length of the string is ", length(s))

end
Enter fullscreen mode Exit fullscreen mode

Output:

Enter something : 
quit
Enter fullscreen mode Exit fullscreen mode

How It Works

In this program, we repeatedly take the user's input and print the length of each input each time. We are providing a special condition to stop the program by checking if the user input is "quit". We stop the program by breaking out of the loop and reach the end of the program.

The length of the input string can be found out using the built-in length function.

Remember that the break statement can be used with the for loop as well.

The continue Statement

The continue statement is used to tell Julia to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.

Example (save as continue.jl):

while true
    println("Enter something : ")
    s = readline()
    if s == "quit"
        break
    end
    if length(s) < 3
        println("Too small")
        continue
    end
    println("Input is of sufficient length")    
end
Enter fullscreen mode Exit fullscreen mode

Output:

Enter something :                    
2                                    
Too small
Enter something :           
quit
Enter fullscreen mode Exit fullscreen mode
                             **How It Works**
Enter fullscreen mode Exit fullscreen mode

In this program, we accept input from the user, but we process the input string only if it is at least 3 characters long. So, we use the built-in length function to get the length and if the length is less than 3, we skip the rest of the statements in the block by using the continue statement. Otherwise, the rest of the statements in the loop are executed, doing any kind of processing we want to do here.

Note that the continue statement works with the for loop as well.

Summary

We have seen how to use the three control flow statements - if, while and for along with their associated break and continue statements. These are some of the most commonly used parts of Julia and hence, becoming comfortable with them is essential.

Adapted from control_flow

Top comments (2)

Collapse
 
ohanian profile image
Steven Siew

TYPO

In C/C++, if you want to write for (int i = 0; i < 5; i++), then in Julia you write just for i in 1:4

should be

In C/C++, if you want to write for (int i = 0; i < 5; i++), then in Julia you write just for i in 0:4

Collapse
 
vinodv profile image
Vinod V

Corrected