While loops

Intermediate Julia

Anthony Markham

Quantitative Developer

While loops - syntax

  • Less common than the for loop, but still useful in some cases.
  • Repeat the expression while the condition is true.
  • Often used to repeat an action until a certain condition is met.
while condition
    expression
end
Intermediate Julia

While loops - example

  • Repeat a set of actions until a condition is true
counter = 10
while counter != 0
    print(counter, " ")
    counter = counter - 1
end
10 9 8 7 6 5 4 3 2 1
Intermediate Julia

While loops - example first iteration

# First iteration
counter = 10
while counter != 0  # counter = 10 here, so this is true
    print(counter, " ")  # print counter, equal to 10
    counter = counter - 1  # decrease the value of counter by 1
end
10
Intermediate Julia

While loops - example second iteration

# Second iteration
counter = 10
while counter != 0  # counter now = 9 here, so this is true
    print(counter, " ")  # print counter, equal to 9
    counter = counter - 1  # decrease the value of counter by 1
end
10 9
Intermediate Julia

While loops - example third iteration

# Third iteration
counter = 10
while counter != 0  # counter now = 8 here, so this is true
    print(counter, " ")  # print counter, equal to 8
    counter = counter - 1  # decrease the value of counter by 1
end
10 9 8
Intermediate Julia

While loops - infinite loop

  • What will happen if we forget to decrement the counter variable?
# Second iteration
counter = 10
while counter != 0  # counter now = 9 here, so this is true
    print(counter, " ")  # print counter, equal to 9
end
10 10 10 10 10 10 10 10 10
Intermediate Julia

While loops - termination

  • In the DataCamp environment, an infinite loop will cause the session to disconnect
  • On your local machine, terminate the Julia program using Ctrl + C
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...