Control Flow#

Learning Objectives#

  • Understand and use conditions statement (if, else, else if) in Julia

  • Implement for and while loops to execute repetitive tasks

  • Recognize how control flow structures are used to manage the execution of code based on conditions

  • Write programs that use loops and conditional statement to solve problems

  • Understand the syntax and applications of different control flow constructs in Julia

Conditional Statements#

Julia uses if, else, and elseif to allow your program to execute different sections of code based on whether a coniditon (or set of conditions) is true or false. For example the code below will determine if a given number is negative, positive or zero.

x = 100
println("Value equals ", x)
if x < 0
    println("The value is negative!")
elseif x == 0
    println("The value is zero!")
else
    println("The value is positive!")
end
Value equals 100
The value is positive!

Loops#

Loops are used to repeat a block of code multiple tims. Two common types of loop are, for and while. A for loop is used to iterate over a range or collection.

# Print the values 1 through 5.
for i in 1:5
    println(i)
end
1
2
3
4
5

A while loop repeats as long as a certain condition is true.

# Prints the values from 5 down to 1 
x = 5 
while x > 0
    println(x)
    x -= 1 # Decrease the value of x by 1 on each iteration
end
5
4
3
2
1