What is flow control in Julia?
Flow control in Julia is the different constructs offered by the language to control the flow of execution/control in the program.
Julia provides the following flow control constructs:
- Conditional
if-elseif-elseconstruct - Short-circuit evaluation
- Repeated evaluation via loops.
Conditional construct
The if-elseif-else is a conditional construct used to execute a block of code based on a boolean expression’s value.
The basic syntax of if-elseif-else is as follows:
if boolean-expression
block-of-code
elseif boolean-expression
block-of-code
else
block-of-code
end
Code example
Let’s look at the code below:
a = 5b = 10if a > bprintln("a > b")elseif b > aprintln("b > a")elseprintln("a = b")end
Short-circuit evaluation
Short-circuiting is a programming concept where the compiler bypasses some logical expressions, sub-expressions, execution, or evaluation. Once the expression’s value has been established, the compiler stops analyzing the subsequent subexpressions. For this purpose, Julia’s && and || operators are used, which stand for logical “and” and “or”, respectively.
x && y: The subexpressionyis only evaluated ifxevaluates totrue.x || y: The subexpressionyis only evaluated ifxevaluates tofalse.
Code example
Let’s look at the code below:
#include <iostream>using namespace std;int main() {// your code goes herecout << "Hello World";return 0;}
Repeated evaluation via loops.
There are two constructs for repeated evaluation via loops.
forloopwhileloop
Note: To understand more about the loops, refer to For vs. While loop in Julia .
Code example
Let’s look at the code below:
print("Using for loop:\n")arr = [1,2,3,4,5]for i in arrprint(i, " ")endprint("\nUsing while loop:\n")num = 1while num <= 5print(num, " ")num+=1end
Free Resources