>For Loop_
The second type of loops are for loops.
They follow this syntax:
Their purpose is to iterate over a list. Also, while loops could do this,
you might argue...
Of course, they could, but for loops are specifically meant to do this. Therefore, for instance, you don't have to declare your counter variable outside the loop. Most importantly, this variable can be accessed from inside the loop.
For loops take this form: Here is a simple example: This first example of code simply displays a welcome message 5 times. The output of this piece of code is:
Ranges can also count backward like this:
Of course, they could, but for loops are specifically meant to do this. Therefore, for instance, you don't have to declare your counter variable outside the loop. Most importantly, this variable can be accessed from inside the loop.
For loops take this form: Here is a simple example: This first example of code simply displays a welcome message 5 times. The output of this piece of code is:
Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 timesThere are also other ways to specify the numerical range . For instance, if your numerical range is too big, you can simply write:
{1..100}
. This piece
of code means every natural number between 1 and 100 (both included). Ranges can also count backward like this:
{10..1}
.
You can even increment the numerical value by steps of two: {0..10..2}
.
This piece of code means every natural number between 0 and 10 in steps of two;
0 2 4 6... 10.