C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Variables, Construct & Looping  >  Loop Construct   > for loop
 

for Loop

The while and the do..while loops are used when the number of iteration(the number of times the loop body is executed) is not known. The for loop is used for fixed iterations.

The following program illustrates the usage of the for loop:

//Program 2.4
//This program calculates the square of the first ten natural numbers
#include<iostream.h>
void main()
{
int iVar;
for(iVar = 1; iVar <= 10; iVar++)
{
cout<<iVar*iVar<<"";
}
}


The output of Program 2.4 is:

1 4 9 16 25 36 49 64 81 100

The for statement consists of the keyword for, followed by parentheses containing three expressions, each separated by a semicolon.

These three expressions are the initialization expression, test expression and the increment/decrement(re-initialization) expression.

The general format of a for loop is:

for(initialization; test; re-initialization)
{
body;
}


In the statement,

for(iVar = 0; iVar <= 10; iVar++)

iVar = 0 is the initialization expression, iVar <= 10 is the test expression, and iVar++ is the increment expression.

Initialization Expression

The initialization expression is executed only once when the loop first starts. It gives the loop variable an initial value.

Test Expression

The test expression involves relational operators. It is executed each time through the loop before the body of the loop is executed. If the test expression is true, the loop is executed, and if it is false, the control passes to the statement following the for loop.

Increment/Decrement(re-initialization) Expression

The increment/decrement expression is always executed at the end of the loop, after the loop body.

The body of the loop is enclosed within braces and is not executed if the for statement is followed by a semicolon. For example, in the following statement is followed by a semicolon. For example, in the following statement:

for(iVar = 0; iVar <= 10; iVar++);
{
cout<<iVar*iVar<<"";
}

the body of the for loop is not executed.

 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.