Julia For Loop

A Julia for loop repeats a block of statements for each value produced by an iterable object. The iterable can be a numeric range, array, tuple, string, dictionary, generator, or another collection.

In this Julia tutorial, you will learn the for loop syntax, how to iterate over ranges and arrays, how to use a custom step value, how to access indexes, how nested loops work, and how break and continue control loop execution.

Julia For Loop Syntax

The syntax of a for loop in Julia is:

</>
Copy
for x in range_or_collection
    #statement(s)
end

Here, for, in, and end are Julia keywords. On each iteration, the next item from range_or_collection is assigned to x, and the statements inside the loop are executed.

Julia also allows = instead of in in a for loop.

</>
Copy
for item = collection
    statements
end

Both forms are valid, although in often reads more naturally when iterating through a collection.

Julia For Loop with a Numeric Range

In the following example, the loop iterates over the inclusive range 1:4. Julia assigns each number in the range to n.

script.jl

</>
Copy
for n in 1:4
    println(n)
end

Output

1
2
3
4

The stop value is included in a Julia range when it can be reached by the range’s step.

Julia For Loop Range with a Custom Step

Use the form start:step:stop to control the increment between values. The following loop starts at 2 and increases by 2 until it reaches 10.

</>
Copy
for n in 2:2:10
    println(n)
end
2
4
6
8
10

A negative step can be used to count backwards.

</>
Copy
for n in 5:-1:1
    println(n)
end
5
4
3
2
1

Julia For Loop over an Integer Array

A for loop can iterate directly over the values stored in an array. In this example, n receives one integer during each iteration.

script.jl

</>
Copy
for n in [1, 5, 22]
    println(n)
end

Output

1
5
22

Julia For Loop over a String Array

The same syntax works with an array of strings. The loop variable contains one string from the array on each iteration.

script.jl

</>
Copy
for name in ["John", "Adam", "Max"]
    println(name)
end

Output

John
Adam
Max

Julia For Loop over Characters in a String

A Julia string is iterable, so a loop can process its characters one at a time.

</>
Copy
for character in "Julia"
    println(character)
end
J
u
l
i
a

Julia For Loop with Array Index and Value

Use enumerate() when both the position and value of each array element are required.

</>
Copy
languages = ["Julia", "Python", "R"]

for (index, language) in enumerate(languages)
    println("$index: $language")
end
1: Julia
2: Python
3: R

Julia arrays normally use one-based indexing, so the first element has index 1.

Julia For Loop to Print Squares of Numbers

In this example, the loop calculates and prints the square of every integer from 1 through 5.

script.jl

</>
Copy
for n in 1:5
    println(n*n)
end

Output

1
4
9
16
25

Julia For Loop with break

The break keyword immediately exits the nearest enclosing loop. In the following example, iteration stops when n becomes 4.

</>
Copy
for n in 1:10
    if n == 4
        break
    end

    println(n)
end
1
2
3

Julia For Loop with continue

The continue keyword skips the remaining statements in the current iteration and proceeds with the next value. This example skips even numbers.

</>
Copy
for n in 1:6
    if iseven(n)
        continue
    end

    println(n)
end
1
3
5

Nested For Loop in Julia

A nested for loop places one loop inside another. The inner loop completes all of its iterations for each iteration of the outer loop.

In this example, nested loops initialize a two-dimensional array. The row index is stored in i, and the column index is stored in j.

script.jl

</>
Copy
m, n = 5, 5
A = fill(0, (m, n))

for i in 1:m
    for j in 1:n
        A[i, j] = i + j
    end
end

A

Output

5×5 Array{Int64,2}:
 2  3  4  5   6
 3  4  5  6   7
 4  5  6  7   8
 5  6  7  8   9
 6  7  8  9  10

Compact Nested Julia For Loop Syntax

Julia permits multiple iteration specifications in one for statement. This form is useful when the iterations belong to one logical nested loop.

</>
Copy
for row in 1:2, column in 1:3
    println("row=$row, column=$column")
end
row=1, column=1
row=1, column=2
row=1, column=3
row=2, column=1
row=2, column=2
row=2, column=3

Julia For Loop over a Dictionary

A dictionary can be iterated as key-value pairs. Destructuring assigns each pair to separate loop variables.

</>
Copy
scores = Dict("Anna" => 84, "Ben" => 91)

for (name, score) in scores
    println("$name scored $score")
end

The iteration order of a general dictionary should not be used when a program requires entries to appear in a particular sorted order.

Variable Scope inside a Julia For Loop

A for loop introduces a local scope. Inside a function, an outer local variable can be updated normally. At global scope, such as in a script or REPL session, explicitly writing global may be necessary when modifying a global variable.

</>
Copy
function sum_numbers(limit)
    total = 0

    for n in 1:limit
        total += n
    end

    return total
end

println(sum_numbers(5))
15

Julia For Loop Compared with a Python For Loop

Julia and Python both iterate directly over iterable values, but Julia closes the loop body with end rather than relying only on indentation.

</>
Copy
for n in 1:3
    println(n)
end

Julia does not use a C-style for (initialization; condition; update) statement. Numeric iteration is normally expressed with a range such as 1:10 or 1:2:10.

Incrementing Values in a Julia For Loop

Julia does not provide ++ or -- increment and decrement operators. Use += 1 or -= 1 when a separate counter must be changed.

</>
Copy
counter = 0

for value in [10, 20, 30]
    counter += 1
    println("Item $counter: $value")
end
Item 1: 10
Item 2: 20
Item 3: 30

When the counter represents an array position, enumerate() is usually clearer than manually incrementing it.

Common Julia For Loop Mistakes

  • Forgetting the closing end keyword.
  • Expecting the C-style for (i = 0; i < n; i++) syntax to work in Julia.
  • Using ++ to increment a value even though Julia does not define that operator.
  • Using 1:length(array) when direct value iteration or eachindex(array) would better express the operation.
  • Modifying a collection’s structure while iterating over it without accounting for changed indexes or elements.
  • Assuming a dictionary’s iteration order is sorted.

Julia For Loop FAQs

How do you write a for loop in Julia?

Write for variable in iterable, place the statements on the following lines, and close the loop with end. For example, for n in 1:5 iterates from 1 through 5.

How do you set a step in a Julia for loop?

Use a stepped range in the form start:step:stop. For example, 1:2:9 produces 1, 3, 5, 7, and 9.

Can Julia use ++ inside a for loop?

No. Julia does not define the ++ operator. Use value += 1, or use a range or enumerate() so that manual incrementing is unnecessary.

How do you get an array index in a Julia for loop?

Use enumerate(array) when both indexes and values are needed. Use eachindex(array) when the loop mainly needs valid indexes for accessing the array.

What is the difference between break and continue in a Julia loop?

break exits the loop completely. continue skips the rest of the current iteration and moves to the next item.

Julia For Loop Tutorial Summary

In this Julia Tutorial, we learned how to use a Julia for loop with ranges, custom steps, arrays, strings, dictionaries, indexes, nested iterations, break, and continue. A Julia loop iterates directly over values from an iterable and ends with the end keyword.