Brief introduction to ranges and for loops
If you wand to say 1 to 10 in Julia, this is a simpler way to do it, its called as range:
1:10
Output:
1:10
It’s syntax is <start value>:<end value>
. And you can print 1 to 10 like this:
for i in 1:10
print(i, ' ')
end
Output:
1 2 3 4 5 6 7 8 9 10
Let me introduce for
loop, this can remove lot of clutter compared to a while
loop. This for
works like this, first you have a variable in this case i
and then it’s followed by a in
keyword and is followed by a range (in future we will see other data types as well). So you can think for
as something that un-bundles 1:10
and puts each value into the variable i
one at a time and executes the loop body that is in the above case is print(i, ' ')
. Notice how the print()
is different from the println()
. println()
prints a new line at the end whereas print()
does not.
Let’s say we want to print numbers from 5 to 100 in steps of 5, range has a way for that too, take a look at the example below:
for i in 5:5:100
print(i, ' ')
end
Output:
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
The format for range with step is this <start value>:<step size>:<end value>
as shown below:
5:5:100
Output:
5:5:100
The notebook for this blog is here https://gitlab.com/data-science-with-julia/code/-/blob/master/ranges.ipynb.