Nim Repetition
Types of loops
There are four types of repetitive statements in Nim:
- For loops
- While loops
- Do-while loops
- Nested loops
For loops
A for loop iterate over a range of values or a colection. The loop can be intrerupted using keywords "break" or can be shortcut using keyword "continue"
for loop
Example:
Following code prints the numbers from 1 to 10:
for i in 1..10:
print(i)
Nested loops
Nested loops allow you to iterate over multiple ranges of values at the same time. For example, the following code prints the numbers from 1 to 10, but only if the number is even and the number is divisible by 5:
for i in 2..10:
if i % 2 == 0 and i % 5 == 0:
print(i)
Intreruption
An interruption in Nim is a way to break out of a loop early. There are two ways to do this: Using "break" or "return" keywords. Also you can force the loop to iterate using "continue" keyword. This do not intrerupe the loop but force the loop to skip some statement and reiterate.
var i = 0
while i < 10:
i += 1
if i == 3:
continue # Skip over the rest of the loop for this iteration
if i == 7:
break # Exit the loop entirely
echo (i)
echo ("Done!")
While loops
While loops iterate while a condition is true. For example, the following code prints the numbers from 1 to 10, but only if the number is even:
while loop diagram
Example
i = 2
while i <= 10:
if i % 2 == 0:
print(i)
i += 1
Do-while loops
Do-while loops are similar to while loops, but the condition is checked at the end of the loop instead of the beginning. This means that the loop will always execute at least once, even if the condition is false. For example, the following code prints the numbers from 1 to 10, but only if the number is odd:
do-while loop
Example
i = 1
do:
print(i)
i += 1
while i <= 10
Read next: Objects