For Loop

The for loop executes a block of code for a specific number of times

Syntax

for(initialization; boolean condition; increment) {
    // the statements here will be executed
    // for each iteration of the loop
}

Execution Steps

The for loop have three parts

initialization
boolean conditional expression
inrement express

1. Initialization

The initialization step is executed only once when the loop is first entered. It sets up any variables that may be needed for the loop.

2. Boolean Conditional Expression

The conditional expression is evaluated for each iteration of the loop. If it evaluates to false the loop ends. If it evaluates to true, it continues to execute the loop code block.

3. Increment Expression

The increment expression is executed after each iteration of the loop. It might increase or decrease the value of the counter.

After the increment expression has been evaluated, execution returns to step 2, and the conditional statement is evaluated again.

Example

Sum all the numbers between 1 and 10.

int sum = 0;
for(int count = 1; count <= 10; count = count + 1){
    sum = sum + count; //This will be executed 10 times
}

// int counter = 1; Is the initialization
// count <= 10; Is the boolean condition. As long as this is true, the loop will continue to run
// count = count + 1; Increment expression. Eventually count will become greater than 10 and the loop will stop

results matching ""

    No results matching ""