for statement in c plus plus



The for statement


The syntax of the for statement is:

For (initialization; test expression; update expression)
{
// Boby of loop – block of statements
}

The three parts of the for statement determine the loop actions. First, the loop initializes the relevant variables. Then there is a test expression, evaluated as true or false. If the test expression is TRUE (this means the test expression is non-zero) the sequence of instructions which forms the body of the loop is executed. Finally, expressions are updated and the process returns to the test expression part of the loop. (The initialization in a loop takes place only when the program enters the loop.)
The sum program can be rewritten using for statement as follows:
int sumSoFar = 0;
//(Start of loop; test condition; increment the loop variable;)
for ( int i=1; I < =100; I = i+1)
 {
sumSoFar = sumSoFar +I; // This is the body of the loop
}

Example of for loop
Here are some examples of simple for loops with different loop parameters. In each case notice that the loop variable is declared in the for statement. In C++ common practice is to declare variable close to their first use, though technically the loop variables could be declared anywhere before the entry into the loop.


// Program segment
//Loop #1
for (int k = 5; k <7; k = k +1)
{
Print k;
}
//Loop #2
for(int k = 50; k < = 56; k = k +2)
{
Print k;
}
//Loop #3
for (int k = -5; k < = 0; k = k +1)
{
Print k;
}
The expression in the for loop are optional but the semi-colons are necessary, i.e.,
For (;;)
{
// statement;
}
This is an infinite loop, with no expression.
More than one expression can also be inside the for loop by separating them using commas. For e.g.,
For (int I =0; int j =10; I <10 && y> 0; i++, y--)
{
// statement;
}
Just like nested-if statements, there can also be nested-for statements i.e, for within for:
for (initialization; test expression; update expression)
{
for (initialization; test expression; update expression)
{
}
}

The nesting can be done to different levels. For loops are basically used to perform the operations over the arrays. The nested-for loop can be used to operate over multidimensional arrays such as matrices.

Flow-chart of for statement

for-statement-flow-chart

Comments

Popular posts from this blog

Rumors of women’s hair cutting in India

President of India

Php Tutorial