In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. [1]
This page provides syntax for some of the common control flow methods in Julia . Each section includes an example to demonstrate the described methods.
Use Cases and Syntax
Test if a specified expression is true or false
Short-circuit evaluation
Test if all of the conditions are true x && y
Test if any of the conditions are true x || y
Test if a condition is not true !z
Conditional evaluation
if statement
if-else
if-elseif-else
?: (ternary operator)
Conditional Statements
Input:
# conditions.jl
# Demonstrates use of if statement
x, y, z = 100, 200, 300
println("x = $x, y = $y, z = $z")
# Test if x equals 100
if x == 100
println("$x equals 100")
end
# Test if y does not equal z
if !(y == z)
println("$y does not equal $z")
end
# Test multiple conditions
if x < y < z
println("$y is less than $z and greater than $x")
end
# Test multiple conditions using "&&"
if x < y && x < z
println("$x is less than $y and $z")
end
# Test multiple conditions using "||"
if y < x || y < z
println("$y is less than $x or $z")
end
# if-else statement
if x < 100
println("$x less than 100")
else
println("$x is equal to or greater than 100")
end
# Same logic as above but using the ternary or
# base three operator (?:)
println(x < 100 ? "$x less than 100 again" : "$x equal to or greater than 100 again")
# if-elseif-else statement
if y < 100
println("$y is less than 100")
elseif y < 200
println("$y is less than 200")
elseif y < 300
println("$y is less than 300")
else
println("$y is greater than or equal to 300")
end
Output:
x = 100, y = 200, z = 300
100 equals 100
200 does not equal 300
200 is less than 300 and greater than 100
100 is less than 200 and 300
200 is less than 100 or 300
100 is equal to or greater than 100
100 equal to or greater than 100 again
200 is less than 300
Loops
Repeat a block of code a specified number of times or until some condition is met.
while loop
for loop
Use break to terminate loop
Input:
# Demonstrates use of loops
i = 1
# while loop for incrementing i by 1 from 1 to 3
while i <= 3
println("while: $i")
global i += 1 # updating operator; equivalent to i = i + 1
end
# for loop
for j = 1:3
println("for: $j")
end
for j in 1:3
println("for again: $j")
end
# nested for loop
for j = 1:3
for k = 1:3
println("nested for: $j * $k = $(j*k)")
end
end