Login    New User    Forgot Password    Help      

For Statements

GO TO INDEX

For statements

By far, the most utilized looping statement in C++ is the for statement. The for statement is ideal when we know exactly how many times we need to iterate, because it lets us easily declare, initialize, and change the value of loop variables after each iteration.

The for statement looks pretty simple:

 
for (init-statement; expr1; expr2)
   statement;

The easiest way to think about for loops is convert them into equivalent while loops. In older versions of C++, the above for loop was exactly equivalent to:

 
// older compilers
init-statement;
while (expr1)
{
    statement;
    expr2;
}

However, in newer compilers, variables declared during the init-statement are now considered to be scoped inside the while block rather than outside of it. This is known as loop scope. Variables with loop scope exist only within the loop, and are not accessible outside of it. Thus, in newer compilers, the above for loop is effectively equivalent to the following while statement:

 
// newer compilers
{
    init-statement;
    while (expr1)
    {
        statement;
        expr2;
    }
} // variables declared in init-statement go out of scope here

A for statement is evaluated in 3 parts:

1) Init-statement is evaluated. Typically, the init-statement consists of variable declarations and assignments. This statement is only evaluated once, when the loop is first executed.

2) The expression expr1 is evaluated. If expr1 is false, the loop terminates immediately. If expr1 is true, the statement is executed.

3) After the statement is executed, the expression expr2 is evaluated. Typically, this expression consists of incremented/decrementing the variables declared in init-statement. After expr2 has been evaluated, the loop returns to step 2.

Let’s take a look at an example of a for loop:

Simplest for loop statement

                               

#include < iostream·h>
int main() { int count; for(count=1; count <= 100; count=count+1) cout << count << " "; return 0; }

OUTPUT


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5
7 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 
                                  


GO TO INDEX