Many programming tasks involve performing the same, or similar, actions multiple times. For instance, you might need to process every student record in a class, calculate the interest for multiple bank accounts, or simply print a series of numbers. Writing individual instructions for each repetition would be inefficient and error-prone. This is where loops provide a powerful solution. The for loop in Julia is designed to iterate over a sequence of items, executing a block of code for each item in that sequence. This makes it an excellent tool for automating repetitive processes when you know how many times you need to repeat or have a collection of items to go through.
for LoopAt its core, a Julia for loop has a straightforward structure. Let's break down its syntax:
for variable in iterable
# Code to be executed in each iteration
# This is the loop body
end
Here’s what each part means:
for: This keyword signals the beginning of a for loop.variable: This is a temporary variable that holds the current item from the iterable during each pass (or iteration) of the loop. You choose the name for this variable (e.g., i, item, number, char). In each iteration, Julia assigns the next value from the iterable to this variable.in: This keyword separates the loop variable from the iterable collection.iterable: This is the sequence or collection of items the loop will go through. Common iterables include ranges of numbers, arrays, tuples, and strings.for line and the end keyword form the loop body. This is the code that gets executed repeatedly.end: This keyword marks the end of the for loop.for loops truly shine when working with collections of data. Let's see how they work with some of the most common iterable types in Julia.
Ranges are a common way to specify a sequence of numbers. A range like $1:5$ represents the numbers 1, 2, 3, 4, and 5.
println("Counting from 1 to 5:")
for i in 1:5
println(i)
end
When this code runs, Julia executes the println(i) line five times.
In the first iteration, $i$ is 1.
In the second, $i$ is 2, and so on, until $i$ is 5.
The output will be:
Counting from 1 to 5:
1
2
3
4
5
You can also create ranges with a "step". For example, $2:2:10$ creates a sequence starting at 2, incrementing by 2, up to 10 (i.e., 2, 4, 6, 8, 10).
println("Even numbers from 2 to 10:")
for num in 2:2:10
println(num)
end
Output:
Even numbers from 2 to 10:
2
4
6
8
10
Arrays are ordered collections of items. You can use a for loop to process each element in an array.
colors = ["red", "green", "blue"]
println("My favorite colors are:")
for color in colors
println(color)
end
Output:
My favorite colors are:
red
green
blue
In each iteration, the color variable takes on the value of the next element from the colors array.
Tuples are similar to arrays but are immutable (meaning they cannot be changed after creation). They can also be iterated over with a for loop.
point = (10, 20, 30) # A tuple representing coordinates
println("Coordinates:")
for coordinate in point
println(coordinate)
end
Output:
Coordinates:
10
20
30
In Julia, strings can be treated as collections of characters. A for loop can iterate over each character in a string.
message = "Hello"
println("Characters in 'Hello':")
for char in message
println(char)
end
Output:
Characters in 'Hello':
H
e
l
l
o
The loop variable (like i, color, char in our examples) is a temporary placeholder.
iterable to this variable.for loop. This means it exists only within the loop's body and cannot be accessed from outside the loop after it has finished executing (unless it was declared outside the loop, which is a more advanced scenario). For the common for item in collection pattern, consider item to be freshly available for each iteration and gone once the loop concludes.The loop body can contain any valid Julia code. This is where you perform the actions you want to repeat. You can do calculations, call functions, and even use conditional statements like if.
A common pattern is to use a loop to accumulate a result. For example, to sum all numbers in a range:
total_sum = 0 # Initialize an accumulator variable
for number in 1:10
total_sum = total_sum + number # Add current number to total_sum
end
println("The sum of numbers from 1 to 10 is: ", total_sum)
Output:
The sum of numbers from 1 to 10 is: 55
In each iteration, total_sum is updated. This demonstrates how expressions (like total_sum + number) are evaluated within the loop.
You can also include conditional logic within a loop. For instance, let's sum only the even numbers in a range:
sum_of_evens = 0
for num in 1:10
if num % 2 == 0 # Check if num is even
sum_of_evens = sum_of_evens + num
end
end
println("Sum of even numbers from 1 to 10: ", sum_of_evens)
Output:
Sum of even numbers from 1 to 10: 30
Here, the if statement inside the for loop controls whether the addition happens in each iteration.
for LoopsYou can place one for loop inside another. This is called a nested loop. Nested loops are useful when you need to iterate over combinations of items or work with multi-dimensional data structures (like a grid or a table).
Consider printing pairs of numbers and letters:
for i in 1:2
println("Outer loop: i = ", i)
for char_val in ['a', 'b']
println(" Inner loop: char_val = ", char_val, ", Pair: (", i, ", ", char_val, ")")
end
end
The output shows how the inner loop completes all its iterations for each single iteration of the outer loop:
Outer loop: i = 1
Inner loop: char_val = a, Pair: (1, a)
Inner loop: char_val = b, Pair: (1, b)
Outer loop: i = 2
Inner loop: char_val = a, Pair: (2, a)
Inner loop: char_val = b, Pair: (2, b)
The outer loop runs twice. For i = 1, the inner loop runs twice (for 'a' and 'b'). Then, for i = 2, the inner loop runs twice again.
The general process of a for loop can be visualized as follows:
This diagram illustrates the flow: the loop starts, checks if there are items, assigns an item to the variable, executes the body, and then repeats by checking for more items. If no items are left, the loop ends.
for Loopsfor loops are ideal when:
1:100).Later in this chapter, you will learn about while loops, which are more suited for situations where the number of iterations is not known beforehand but depends on a condition being met. For now, mastering the for loop will give you a solid foundation for automating many common programming tasks. As you'll see, the ability to control program flow with loops is a significant step in writing more powerful and efficient Julia code.
Was this section helpful?
for loops and other control flow constructs.for loops with clear examples and explanations.© 2026 ApX Machine LearningEngineered with