A common use case for a for
loop is to iterate over a predefined range or collection, and do the same task for all its elements. For instance, here we combine a for
loop with a conditional if
-elseif
-else
statement:
for i in 1:100
if i % 15 == 0
println("FizzBuzz")
elseif i % 3 == 0
println("Fizz")
elseif i % 5 == 0
println("Buzz")
else
println(i)
end
end
This is the classic Fizz Buzz interview question. The (truncated) output is:
1
2
Fizz
4
Buzz
Fizz
7
8