Wednesday, 12 November 2014

Control Structures - The for loop in C++ with example

Control Structures - The for loop in C++ with example:

The syntax of the for loop is shown below

for (initialization; condition; increase/decrease)
statement 1;
statement 2;
statement N;

There are 3 prosions exists in the for loop.
1. Initialization
2. Condition
3. Increment / Decrement

The initialization statement is executed only once at the beginning of the for loop. Then the program verifies the expression. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.

Let us have a look into the pictorial representation of the for loop

The for loop main function is to repeat statement while condition remains true, like the while loop. In addition, the for loop provides specific locations to contain an initialization statement and an increase/decrease statement.
So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration.
Have a look into the below steps:
1. Initialization is executed only once.
2. Condition is checked.
3. Statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
4. Finally, whatever is specified in the increase field is executed and the loop gets back to condition checking.

The below example will help us to understand the usage of the for loop

NOTE: In the for loop the initialization and increase fields are optional.
We can leave them empty, if those are no required. We can write the loop as shown below.
for(; iCnter <= iTotal;)

It is also possible to specify that no initialization and no increment/decrement
for(; iCnter <= iTotal; ++iCnter); 

There is a possibility that we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected.
The below example helps us to understand how to make multiple expressions in the for loop
for (int iInd = 0, iInd = 10 ; iCnt!= iInd ; iCnt++, iInd--)
   // your statements are here…
This loop will execute for 10 times if neither iCnt or iInd  are modified within the loop.
iCnt starts with a value of 0, and iInd with 10, the condition is iCnt!= iInd   Because iCnt is increased by one and iInd decreased by one, the loop's condition will become false after the 5th loop, when both iCnt and iInd will be equal to 5.

No comments: