Tutorial#30 - For Loop

For Loop



For Loop:

The while loop discussed in the previous section is general enough to implement most forms of repetitions. The C++ for looping structure discussed here is a specialized form of the while loop. Its primary purpose is to simplify the writing of counter-controlled loops. For this reason, the for loop is typically called a counted or indexed for loop.
The general form of the for statement is:
for (initial statement; loop condition; update statement)
statement
The initial statement, loop condition, and update statement (called for loop control statements) enclosed within the parentheses control the body (statement) of the for statement.
For Loop 

This Figure shows the flow of execution of a for loop.

The for loop executes as follows:
1. The initial statement executes.
2. The loop condition is evaluated. If the loop condition evaluates to true:
i. Execute the for loop statement.
ii. Execute the update statement (the third expression in the parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.
The initial statement usually initializes a variable (called the for loop control, or
for indexed, variable).
In C++, for is a reserved word.
Example-1: The following for loop prints the first 10 nonnegative integers:
for (i = 0; i < 10; i++){
cout << i << " ";
cout << endl;
    }
The initial statement, i = 0;, initializes the int variable i to 0. Next, the loop condition, i < 10, is evaluated. Because 0 < 10 is true, the print statement executes and outputs 0. The update statement, i++, then executes, which sets the value of i to 1. Once again, the loop condition is evaluated, which is still true, and so on. When i becomes 10, the loop condition evaluates to false, the for loop terminates, and
the statement following the for loop executes.

Example-2: The following for loop outputs Hello! and a star (on separate lines)
five times:
for (i = 1; i <= 5; i++)
{
cout << "Hello!" << endl;
cout << "*" << endl;
}

Example-3: In this example, a for loop reads five numbers and finds their sum and average.
Consider the following program code, in which i, newNum, sum, and average are
int variables.
sum = 0;
for (i = 1; i <= 5; i++)
{
cin >> newNum;
sum = sum + newNum;
}
average = sum / 5;
cout << "The sum is " << sum << endl;
cout << "The average is " << average << endl;
In the preceding for loop, after reading a newNum, this value is added to the previously calculated (partial) sum of all the numbers read before the current number. The variable sum is initialized to 0 before the for loop. Thus, after the program reads the first number and adds it to the value of sum, the variable sum holds the correct sum of the first number.

Comments