For Loops

Organizing our code with simple loops, nested for loops, and array comprehensions.

by Martin D. Maas, Ph.D

@MartinDMaas

Last updated: 2021-09-30

Loops are one of the most basic ways to structure our computations

Simple For Loop

The most basic way to structure computations is by using a for loop. In Julia, the basic syntax of a for loop is

for iterator in range
    execute_statements(iterator)
end

As an example, lets evaluate the sum of the first 100,000 terms of the quadratic series.

x=0
for k in 1:100000
    x = x + (1/k)^2
end

We get the following output

1.6449240667982423

Nested For Loops

It is very common to have nested for loops, and we would normally code them using something like:

for i in 1:3
    for j in 1:3
        print("i=", i, " j=", j, "\n")
    end
end

This can get hard to read when we have more than two nested loops. A nice syntax we can rely on in this case is the following:

for i in 1:3, j in 1:3
    print("i=", i, " j=", j, "\n")
end

Additionally, we can resort to the even nicer:

for i ∈ 1:3, j ∈ 1:3
    print("i=", i, " j=", j, "\n")
end

Array Comprehensions and Generators

In some cases, like when we are using a for loop to initialize an array, we can re-write our code in a more concise way, by resorting to array comprehensions.

The following code first builds an array with all the first 100,000 terms for our sum, and then performs the sum:

v = [1/n^2 for n=1:100000]
x = sum(v)

When using parenthesis instead of the square brackets, Julia will produce a slightly different object: a generator. Generators can be iterated to produce the required values when needed. As the underlying array isn’t allocated in memory in advance, the generator could have better performance than the array comprehension.

gen = (1/n^2 for n=1:100000)
x = sum(gen)

Of course, the above codes can be reduced to a single line:

x = sum([1/n^2 for n=1:100000])