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 statementx, y, z =100,200,300println("x = $x, y = $y, z = $z")# Test if x equals 100if x ==100println("$x equals 100")end# Test if y does not equal zif!(y == z)println("$y does not equal $z")end# Test multiple conditionsif x < y < zprintln("$y is less than $z and greater than $x")end# Test multiple conditions using "&&"if x < y && x < zprintln("$x is less than $y and $z")end# Test multiple conditions using "||"if y < x || y < zprintln("$y is less than $x or $z")end# if-else statementif x <100println("$x less than 100")elseprintln("$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 statementif y <100println("$y is less than 100")elseif y <200println("$y is less than 200")elseif y <300println("$y is less than 300")elseprintln("$y is greater than or equal to 300")end
Output:
x =100, y =200, z =300100 equals 100200 does not equal 300200 is less than 300 and greater than 100100 is less than 200 and 300200 is less than 100 or 300100 is equal to or greater than 100100 equal to or greater than 100 again200 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 3while i <=3println("while: $i")global i +=1# updating operator; equivalent to i = i + 1end# for loopfor j =1:3println("for: $j")endfor j in1:3println("for again: $j")end# nested for loopfor j =1:3for k =1:3println("nested for: $j * $k = $(j*k)")endend