While Loop

Loops are used to execute a code block many times.

Syntax

Example

A loop can be used to print all numbers in certain range. Like from 1 to 10

Output:

At line 3 the condition of the loop is set. Since num is less than 10 the loop executes.

In order to print the numbers to 10, num increases by 1 at line 5.

The loop ends when num reaches value of 11.

Infinite Loop

Infinite Loop has a condition that's always true.

It can be created due to development mistake or used in advanced algorithm.

Here are examples:

Output:

Since num is never changed, the condition num < 5 is always true and the loop executes infinitely (or until the program takes more ram than it is allowed).

In order to end the loop num needs to be incremented (like num++) inside the loop's body.

Output:

Since the condition at line 3 is always true, the loop keeps on repeating.