Iterative Statements

Iterative statements let you repeat a statement until a specified expression becomes false, or a return within the statement body is executed.

While Statement

Syntax

iteration-statement:  while (expression) statement

Example

int a = 0;
while (a != 2) {
    a++;
}

In this example, a is increased by 1 until it is equal to 2.

For Statement

The body of a for statement is executed zero or more times until an optional condition becomes false. You can use optional expressions within the for statement to initialize and change values during the for statement's execution.

Syntax

iteration-statement:  for ( init-expressionopt ; cond-expressionopt ; loop-expressionopt ) statement

Example

for (int i = 4; i > 0; i--) {
}

In this example, i is decreased by 1 until it is equal to zero.

Last updated