An Odd Loop

An Odd Loop

As I mentioned about the loop a little twist with its parameters, here's an example :

using namespace std;
int main()
    int i=1,j=5;
    for( ; ;i++,j--)
        cout<<"i = "<<i<<" AND j = "<<j<<endl;
            cout<<"Hey i and j are equal."<<endl;
            cout<<"Its about time we should get out of loop."<<endl;
    cout<<"We are out of loop with i = "<<i<<" AND j = "<<j<<endl;

    Here we've already initialize value of i and j in the beginning of program. So there is no need to reinitialize them again loop. So area1 is left blank. 
    The 'if' statement in the loop is working as the condition check. How? What condition check
does is to bring the loop at an end and terminate it. Now,carefully look at our 'if' condition. It has a 'break' statement. Whenever 'break' is encountered, loop immediately gets terminated. No matter we still could have statements left to complete our execution of body of loop. In our program, this break is encountered when value of i and j becomes equal.This is the reason 'if' is serving as condition check in our program.
    Now look at area3. As we discussed earlier, a single area can have multiple statements to execute. In area3, we
have an increment and a decrement statement. You can also add a 'cout' statement or something else by just putting a comma.I leave it upto you to try it yourself.
    So with this knowledge we are ready to solve the problems that we generally face while solving these for loops.

    Here's the output of our program.

<<Evaluation Of for Loop                                    Home

No comments:

Post a Comment