“for” Construct in C++

In performing numeric calculations, it is common to do a calculation with the number one, then with the number two, then with three, and so forth, until some last value is reached. For example, to add one through ten, we want the computer to perform the following statement ten times, with the value of n equal to 1 the first time and with n increased by one each subsequent time:

sum = sum + n;

The following is one way to accomplish this With a while-statement:

sum = 0;
n = 1;
while, (n <= 10)
{
sum = sum + n;
n++;
}

Although a while-loop will do here, this sort of situation is just what the for-statement (also called the for-loop) was designed for. The following for-statement will neatly accomplish the same task:

sum = 0;
for (n = 1; n < =10; n++)
sum = sum + n;

A for-statement begins with the keyword for followed by three things in parentheses that tell the computer what to do with the controlling variable. The beginning of a for-statement looks like the following.

for (Initialization_Action; Boolean_Expression; Update_Action)

Syntax:
for (Initialization_Action; Boolean_Expression; Update_Action)
Body Statement

Example:                                    ,
for (number = 100; number >= 0; number-—)
cout << number << “bottles of beer on the shelf. \n”;

Equivalent while-loop:
Equivalent syntax:

Initialization Action;
while (Boolean_Expression)
{
Body_Statement
Update_Action;
}

The first expression tells how the variable is initialized, the second gives a Boolean expression that is used to check for when the loop should end, and the last expression tells how the loop control variable is updated after each iteration of the loop body. For example, the above for-loop begins.
for (n = 1; n <= 10; n++)

n = 1 says that n is initialized to 1. n <= 10 says the loop will continue to iterate the body as long as n is less than or equal to 10. The last expression, n++, says that n is incremented by one after each time the loop body is executed. The three expressions at the start of a for-statement are separated by two, and only two, semicolons.

Syntax:
for (initialization_Action; Boolean_Expression; Update_Action)
Body-statements

It's very calm over here, why not leave a comment?

Leave a Reply

You must be logged in to post a comment.