Nim Provides the following loop types for the execution of multiple statements

  • while loops
  • for loops

NIM language has no process for statements inside if or if-else blocks

Code statements inside if and else are indented with 2 or 4 spaces.

Nim while loops

while loop is used to execute multiple code statements based on The conditional expression.

Condition always results in the bool type and the possible values - true and false only. Here is the syntax of a simple if statement.

while conditional expression:
   // code block executed

Here is an example

import os

var i = 5
while i > 0:
 echo i
 dec i

Output:

5
4
3
2
1

While loop uses two keywords continue: can be used to skip the iteration break: Used to exit from loop execution

break while loop example:

import os

var i = 5
while i > 0:
 echo i
 dec i
 if i==2 :
  break

Output:

5
4
3

Continue keyword inside while loop example

import os

var i = 5
while i > 0:
 if i==2 :
  continue
 echo i
 dec i

Output:

5
4
3

Nim for loop statements

for loop used to iterate over multiple values using counter

Syntax

for index in countup function:
    echo index

Code blocks inside if and else are indented with two spaces.

for index in countup(1, 5):
    echo index

Index assigned with an initial value of countup first parameter i.e 1. It increments the value by 1 and executes the loop body until the last parameter is matched.

Alternatively, the countup function can be replaced with two dots

for index in 0..<2:
    echo index

Output:

0
1

0..<2 iterated with 0,1 exclusive 2 0..2 iterated with 0,1,2.

For loop is also used to iterate characters in a string

Here is an example

for  character in "test":
    echo character

Output:

t
e
s
t

the body inside for loop can also contain continue and break.