Julia While Loop

A Julia while loop repeatedly executes a block of statements as long as its condition evaluates to true. It is useful when the number of iterations depends on a condition rather than a fixed collection or range.

In this Julia tutorial, you will learn the while loop syntax, how its condition is evaluated, how to update loop variables, and how to use break and continue safely.

Julia while loop syntax

The syntax of While loop in Julia is

</>
Copy
while boolean_expression
    statement(s)
end

Here, while and end are Julia keywords. Before each iteration, Julia evaluates boolean_expression. The loop body runs only when that expression is true.

  • The condition is checked before the first iteration.
  • If the condition is initially false, the loop body does not run.
  • A variable used in the condition usually needs to be updated inside the loop.
  • The loop ends when the condition becomes false or a break statement is executed.

How a Julia while loop executes

Consider a counter that begins at 1 and continues while it is less than or equal to 5. Julia checks the condition, executes the body, updates the counter, and then checks the condition again.

</>
Copy
count = 1

while count <= 5
    println(count)
    count += 1
end
1
2
3
4
5

After printing 5, the counter becomes 6. The expression 6 <= 5 is false, so the loop terminates.

Example 1 – Julia while loop to count

In this example, we use a while loop to print the numbers from 1 to 4.

script.jl

</>
Copy
n = 0
while n < 4
    n += 1
    println(n)
end

Output

1
2
3
4

The variable n starts at 0. Each iteration increments it before printing, which produces the values from 1 through 4.

Example 2 – Julia while loop with a string array

In this example, we will use the while loop to greet all the guests, whose names are stored in a string array.

script.jl

</>
Copy
guests = ["Ted", "Robyn", "Barney"]

i = 1
while i <= length(guests)
    friend = myfriends[i]
    println("Hi $friend, good to see you!")
    i += 1
end

Output

Hi Ted, good to see you!
Hi Robyn, good to see you!
Hi Barney, good to see you!

In the script above, the array is assigned to guests, so the indexed expression should refer to the same variable. A corrected version is shown below.

</>
Copy
guests = ["Ted", "Robyn", "Barney"]

i = 1
while i <= length(guests)
    friend = guests[i]
    println("Hi $friend, good to see you!")
    i += 1
end

Julia arrays use one-based indexing, so the first element is accessed with index 1. The condition i <= length(guests) prevents the loop from reading beyond the final element.

Example 3 – Julia while loop to find a factorial

In this example, we will use the while loop to find the factorial of a number.

script.jl

</>
Copy
n = 0
result = 1
while n < 4
    n += 1
    result *= n
end
println(result)

Output

24

The loop multiplies result by 1, 2, 3, and 4. Therefore, the final value is 4! = 24.

Read input repeatedly with a Julia while loop

A while loop is suitable when a program should continue until the user enters a particular value. The following example stops when the user enters quit.

</>
Copy
text = ""

while text != "quit"
    print("Enter text, or type quit: ")
    text = readline()

    if text != "quit"
        println("You entered: $text")
    end
end

The number of iterations is not known in advance because it depends on the entered values. This is a common reason to choose while instead of for.

Stop a Julia while loop with break

The break statement immediately exits the nearest enclosing loop. It is useful when the stopping condition is detected inside the loop body.

</>
Copy
number = 1

while true
    println(number)

    if number == 3
        break
    end

    number += 1
end
1
2
3

The condition true would otherwise create an infinite loop. When number reaches 3, break terminates it.

Skip an iteration with continue in a Julia while loop

The continue statement skips the remaining statements in the current iteration and starts the next condition check.

</>
Copy
n = 0

while n < 6
    n += 1

    if iseven(n)
        continue
    end

    println(n)
end
1
3
5

The counter is incremented before continue. This detail is important because skipping the counter update could cause an infinite loop.

Use a Julia while loop with multiple conditions

A loop condition can combine Boolean expressions with operators such as && for AND and || for OR.

</>
Copy
attempts = 0
connected = false

while attempts < 3 && !connected
    attempts += 1
    println("Connection attempt $attempts")

    if attempts == 2
        connected = true
    end
end
Connection attempt 1
Connection attempt 2

The loop continues only while fewer than three attempts have been made and connected remains false.

Julia while loop versus for loop

Use a while loop when repetition is controlled mainly by a condition. Use a for loop when iterating directly over a known range, array, tuple, string, or other iterable object.

RequirementPreferred Julia loop
Repeat until a condition changeswhile
Process each item in an arrayfor
Repeat until valid input is enteredwhile
Iterate over a fixed numeric rangefor
Run until an internal event triggers breakwhile

For example, printing values from 1 to 5 is usually simpler with for i in 1:5. Waiting until a value satisfies a changing condition is usually clearer with while.

Variable scope inside Julia while loops

Scope behavior can differ between the Julia REPL and code stored in a file or function. For predictable behavior, place loop-based calculations inside a function, especially when a loop updates local variables.

</>
Copy
function sum_to(limit)
    current = 1
    total = 0

    while current <= limit
        total += current
        current += 1
    end

    return total
end

println(sum_to(5))
15

Both current and total are local to sum_to, which makes their behavior clear and avoids depending on global variables.

Avoid infinite Julia while loops

An infinite loop occurs when the condition never becomes false and no reachable break statement exits the loop.

</>
Copy
n = 1

while n <= 5
    println(n)
    # n is not updated, so the condition remains true
end

To prevent this problem, identify which value controls the condition and confirm that every relevant execution path updates it or reaches a valid break.

Common Julia while loop mistakes

  • Not updating the condition variable: The condition remains true and the loop does not terminate.
  • Using the wrong array variable: The indexed name must match the array that was created.
  • Starting an array index at zero: Julia arrays normally begin at index 1.
  • Using < instead of <=: The final intended value or array element may be skipped.
  • Updating a counter after continue: The update may never execute, resulting in an infinite loop.
  • Using assignment in place of comparison: Use == to compare values and = to assign a value.
  • Forgetting end: Every Julia while block must be closed with end.

Frequently asked questions about Julia while loops

What is the syntax of a while loop in Julia?

Write while condition, place the statements to repeat on the following lines, and close the block with end. The body runs repeatedly while the condition evaluates to true.

Does a Julia while loop always run at least once?

No. Julia checks the condition before executing the loop body. If the condition is false initially, the body runs zero times.

How do I exit a Julia while loop early?

Use break inside the loop. Julia immediately exits the nearest enclosing loop and continues with the statement that follows it.

How do I skip one iteration of a Julia while loop?

Use continue. Ensure that any required counter or state update occurs before continue, or the loop may repeat with the same condition values.

When should I use while instead of for in Julia?

Use while when the number of iterations is not known in advance and execution depends on a changing condition. Use for when iterating over a known range or collection.

Editorial QA checklist for Julia while loop examples

  • Verify that every while block has a condition that evaluates to a Boolean value.
  • Confirm that each terminating loop updates the counter or state used by its condition.
  • Check that Julia array examples begin with index 1 and stop at length(array).
  • Test every break and continue path to ensure that it cannot create an unintended infinite loop.
  • Confirm that variable names used inside each loop match the variables declared before it.
  • Run each example in a Julia file or function and compare the actual output with the documented output.

Summary of Julia while loop syntax and control flow

In this Julia Tutorial, we learned the syntax and usage of While Loop in Julia, with the help of example scripts. A while loop checks its condition before every iteration, requires its controlling state to be updated, and can be managed with break and continue when conditional exit or skipping is required.