# Julia - Flow Control

As we know that each line of a program in Julia is evaluated in turn hence it provides many of the control statements (familiar to other programming languages) to control and modify the flow of evaluation.

Following are different ways to control the flow in Julia programming language −

• Ternary and compound expressions

• Boolean switching expressions

• If elseif else end (conditional evaluation)

• For end (iterative evaluation)

• While end (iterative conditional evaluation)

• Try catch error throw (exception handling)

• Do blocks

## Ternary expressions

It takes the form expr ? a : b. It is called ternary because it takes three arguments. The expr is a condition and if it is true then a will be evaluated otherwise b. Example for this is given below −

julia> A = 100
100

julia> A < 20 ? "Right" : "wrong"
"wrong"

julia> A > 20 ? "Right" : "wrong"
"Right"


## Boolean Switching expressions

As the name implies, the Boolean switching expression allows us to evaluate an expression if the condition is met, i.e., the condition is true. There are two operators to combine the condition and expression −

### The && operator (and)

If this operator is used in the Boolean switching expression, the second expression will be evaluated if the first condition is true. If the first condition is false, the expression will not be evaluated and only the condition will be returned.

Example

julia> isodd(3) && @warn("An odd Number!")
┌ Warning: An odd Number!
└ @ Main REPL[5]:1

julia> isodd(4) && @warn("An odd Number!")
false


### The || operator (or)

If this operator is used in the Boolean switching expression, the second expression will be evaluated only if the first condition is false. If the first condition is true, then there is no need to evaluate the second expression.

Example

julia> isodd(3) || @warn("An odd Number!")
true

julia> isodd(4) || @warn("An odd Number!")
┌ Warning: An odd Number!
└ @ Main REPL[8]:1


## If, elseif and else

We can also use if, elseif, and else for conditions execution. The only condition is that all the conditional construction should finish with end.

### Example

julia> fruit = "Apple"
"Apple"

julia> if fruit == "Apple"
println("I like Apple")
elseif fruit == "Banana"
println("I like Banana.")
println("But I prefer Apple.")
else
println("I don't know what I like")
end

I like Apple

julia> fruit = "Banana"
"Banana"

julia> if fruit == "Apple"
println("I like Apple")
elseif fruit == "Banana"
println("I like Banana.")
println("But I prefer Apple.")
else
println("I don't know what I like")
end

I like Banana.
But I prefer Apple.


## for loops

Some of the common example of iteration are −

• working through a list or

• set of values or

• from a start value to a finish value.

We can iterate through various types of objects like arrays, sets, dictionaries, and strings by using “for” loop (for…end construction). Let us understand the syntax with the following example −

julia> for i in 0:5:50
println(i)
end
0
5
10
15
20
25
30
35
40
45
50


In the above code, the variable ‘i’ takes the value of each element in the array and hence will step from 0 to 50 in steps of 5.

### Example (Iterating over an array)

In case if we iterate through array, it is checked for change each time through the loop. One care should be taken while the use of ‘push!’ to make an array grow in the middle of a particular loop.

julia> c = [1]
julia> 1-element Array{Int64,1}:
1

julia> for i in c
push!(c, i)
@show c
sleep(1)
end

c = [1,1]
c = [1,1,1]
c = [1,1,1,1]
...


Note − To exit the output, press Ctrl+c.

## Loop variables

Loop variable is a variable that steps through each item. It exists only inside the loop. It disappears as soon as the loop finishes.

### Example

julia> for i in 0:5:50

println(i)
end
0
5
10
15
20
25
30
35
40
45
50

julia> i
ERROR: UndefVarError: i not defined


### Example

Julia provides global keyword for remembering the value of the loop variable outside the loop.

julia> for i in 1:10
global hello
if i % 3 == 0
hello = i
end
end

julia> hello
9


## Variables declared inside a loop

Similar to Loop Variable, the variables declared inside a loop won’t exist once the loop is finished.

### Example

julia> for x in 1:10
y = x^2
println("$(x) squared is$(y)")
end


### Output

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100

julia> y
ERROR: UndefVarError: y not defined


## Continue Statement

The Continue statement is used to skip the rest of the code inside the loop and start the loop again with the next value. It is mostly used in the case when on a particular iteration you want to skip to the next value.

### Example

julia> for x in 1:10
if x % 4 == 0
continue
end
println(x)
end


### Output

1
2
3
5
6
7
9
10


## Comprehensions

Generating and collecting items something like [n for n in 1:5] is called array comprehensions. It is sometimes called list comprehensions too.

### Example

julia> [X^2 for X in 1:5]
5-element Array{Int64,1}:
1
4
9
16
25


We can also specify the types of elements we want to generate −

### Example

julia> Complex[X^2 for X in 1:5]
5-element Array{Complex,1}:
1 + 0im
4 + 0im
9 + 0im
16 + 0im
25 + 0im


## Enumerated arrays

Sometimes we would like to go through an array element by element while keeping track of the index number of every element of that array. Julia has enumerate() function for this task. This function gives us an iterable version of something. This function will produce the index number as well as the value at each index number.

### Example

julia> arr = rand(0:9, 4, 4)
4×4 Array{Int64,2}:
7 6 5 8
8 6 9 4
6 3 0 7
2 3 2 4

julia> [x for x in enumerate(arr)]
4×4 Array{Tuple{Int64,Int64},2}:
(1, 7) (5, 6) (9, 5) (13, 8)
(2, 8) (6, 6) (10, 9) (14, 4)
(3, 6) (7, 3) (11, 0) (15, 7)
(4, 2) (8, 3) (12, 2) (16, 4)


## Zipping arrays

Using the zip() function, you can work through two or more arrays at the same time by taking the 1st element of each array first and then the 2nd one and so on.

Following example demonstrates the usage of zip() function −

### Example

julia> for x in zip(0:10, 100:110, 200:210)
println(x)
end
(0, 100, 200)
(1, 101, 201)
(2, 102, 202)
(3, 103, 203)
(4, 104, 204)
(5, 105, 205)
(6, 106, 206)
(7, 107, 207)
(8, 108, 208)
(9, 109, 209)
(10, 110, 210)


Julia also handle the issue of different size arrays as follows −

julia> for x in zip(0:15, 100:110, 200:210)
println(x)
end
(0, 100, 200)
(1, 101, 201)
(2, 102, 202)
(3, 103, 203)
(4, 104, 204)
(5, 105, 205)
(6, 106, 206)
(7, 107, 207)
(8, 108, 208)
(9, 109, 209)
(10, 110, 210)

julia> for x in zip(0:10, 100:115, 200:210)
println(x)
end
(0, 100, 200)
(1, 101, 201)
(2, 102, 202)
(3, 103, 203)
(4, 104, 204)
(5, 105, 205)
(6, 106, 206)
(7, 107, 207)
(8, 108, 208)
(9, 109, 209)
(10, 110, 210)


## Nested loops

Nest a loop inside another one can be done with the help of using a comma (;) only. You do not need to duplicate the for and end keywords.

### Example

julia> for n in 1:5, m in 1:5
@show (n, m)
end
(n, m) = (1, 1)
(n, m) = (1, 2)
(n, m) = (1, 3)
(n, m) = (1, 4)
(n, m) = (1, 5)
(n, m) = (2, 1)
(n, m) = (2, 2)
(n, m) = (2, 3)
(n, m) = (2, 4)
(n, m) = (2, 5)
(n, m) = (3, 1)
(n, m) = (3, 2)
(n, m) = (3, 3)
(n, m) = (3, 4)
(n, m) = (3, 5)
(n, m) = (4, 1)
(n, m) = (4, 2)
(n, m) = (4, 3)
(n, m) = (4, 4)
(n, m) = (4, 5)
(n, m) = (5, 1)
(n, m) = (5, 2)
(n, m) = (5, 3)
(n, m) = (5, 4)
(n, m) = (5, 5)


## While loops

We use while loops to repeat some expressions while a condition is true. The construction is like while…end.

### Example

julia> n = 0
0

julia> while n < 10
println(n)
global n += 1
end
0
1
2
3
4
5
6
7
8
9


## Exceptions

Exceptions or try…catch construction is used to write the code that checks for the errors and handles them elegantly. The catch phrase handles the problems that occur in the code. It allows the program to continue rather than grind to a halt.

### Example

julia> str = "string";
julia> try
str[1] = "p"
catch e
println("the code caught an error: \$e")
println("but we can easily continue with execution...")
end
the code caught an error: MethodError(setindex!, ("string", "p", 1), 0x0000000000006cba)
but we can easily continue with execution...


## Do block

Do block is another syntax form similar to list comprehensions. It starts at the end and work towards beginning.

### Example

julia> Prime_numbers = [1,2,3,5,7,11,13,17,19,23];

julia> findall(x -> isequal(19, x), Prime_numbers)
1-element Array{Int64,1}:
9


As we can see from the above code that the first argument of the find() function. It operates on the second. But with a do block we can put the function in a do…end block construction.

julia> findall(Prime_numbers) do x
isequal(x, 19)
end
1-element Array{Int64,1}:
9