Julia For Loop

Julia for loop is used to iterate a set of statements over a range of elements, or items of an array, etc.

In this Julia Tutorial, we will learn how to write For Loop in Julia programs with examples.

The syntax of For loop in Julia is

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

where for, in and end are keywords.

x is the item of the range or collection for each iteration. You can access x inside the for loop.

Julia For Loop with Range

In the following example, we use for loop to iterate over a range of numbers.

script.jl

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

Output

1
2
3
4

Julia For Loop over elements of an Array of Integers

In the following example, we use for loop to iterate over elements of an Integer Array.

script.jl

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

Output

1
5
22

Julia For Loop with String Array

In the following example, we use for loop to iterate over elements of an String Array.

script.jl

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

Output

John
Adam
Max

Example 1 – Julia For Loop to Print Squares of Numbers

In this example, we will print squares of integers from 1 to 5 using range with for loop.

script.jl

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

Output

1
4
9
16
25

Example – Nested For Loop in Julia

In this example, we use a for loop to initialize a 2-D Array with some initial values.

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

Conclusion

In this Julia Tutorial, we learned about For Loop in Julia, and how to use it with ranges, arrays, etc.