Iterative Statement : for Loop

For some programming objectives it is necessay to repeat a set of statements a number of times until a certain condition is fulfilled. In such situations iteration statements can be used. The iteration statements are also called loops or looping statements.

Parts of a loop

1. Initialization Expression.

2. Test Expression

3. Update Expressions

4. Body of the loop.

The for Loop

The for loop is a deterministic loop in the sense that the program knows inadvance how many times the loop is to be executed.

Its format is:

for( variable initialization; conditional expression; modification of variable)

body-of-the loop;

where for : is a reserved word.

It works the following way:

1. initialization is executed. Generally it is an initial value setting for a counter varible. This is

executed only once.

2. condition is checked, if it is true the loop continues, otherwise the loop finishes and statement is

skipped.

3. statement is executed. As usual, it can be either a single instruction or a block of instructions

enclosed within curly brackets { }.

4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop.

// countdown using a for loop OUTPUT

#include <iostream.h> 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, SHOOT!

int main ()

{

for (int n=10; n>0; n--) {

cout << n << ", ";

}

cout << "SHOOT!";

return 0;

}

The initialization and increase fields are optional. They can be avoided but not the

semicolon signs among them.

For example we could write: for (;n<10;)

if we want to specify no initialization and modification. if we want to include an increase

field but not an initialization, we could write

for(;n<10;n++).

The Comma OperatorOptionally, using the comma operator (,) we can specify more than one instruction in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an instruction separator, it serves to separate more than one instruction where only one instruction is generally expected. For example, suppose that we wanted to intialize more than one variable in our loop:

for ( n=0, i=100 ; n!=i ; n++, i-- ) { // the code...

}

This loop will execute 50 times if neither n nor i are modified within the loop:

or i are modified within the loop:

n starts with 0 and i with 100, the condition is (n!=i) (that n be not equal to i). Beacuse n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

HOME LEARN C++ PREVIOUS NEXT