Skip to content
Pranav Verma edited this page Nov 26, 2024 · 3 revisions

Loops

for Loop

The for keyword is used to iterate over a range or a collection. This loop will execute a block of code for each item in the specified range or collection.

Syntax

for (initial declaration; final declaration; step increment;)  {
    /* code to execute for each iteration */
}

Example

for (var i = 0; i < 5; i = i + 1;) {
     print(i);
}

while Loop

The while keyword is used to execute a block of code repeatedly as long as a specified condition is true. This loop will check the condition before each iteration, and if the condition is false, it will terminate the loop.

Syntax

while (condition) {
    /* code to execute as long as the condition is true */
}

Example

var i = 0;
while (i < 5) {
    print(i);
    i = i + 1;
}

In this example, the while loop will print the value of i as long as i is less than 5. After each iteration, i is incremented by 1.

Keywords

break

The break keyword can be used to exit a loop prematurely. If a break statement is encountered, the loop will terminate, and the program will continue executing the code following the loop.

continue

The continue keyword is used to skip the current iteration of the loop and proceed to the next iteration. When a continue statement is encountered, the remaining code in the loop for that iteration is skipped.

Clone this wiki locally