Friday, September 16, 2011

Code Magic : Loopy Loops -> Twisting the For Loop (C and C++)


Every textbook that teaches the basics of the programming languages 'C' and 'C++' will clearly state the syntax for the "For" loop as :-

for( initialization; comparison; update )
{

Body of Loop;

}

For example,

for( int i=0; i<5; i++)
{
cout<<"\n "<<i;
getch();
}

This will give us the output :-

 0
 1
 2
 3
 4

Now here comes the interesting part. Though in most cases a program will throw up errors while compiling if the syntax is not strictly followed, in certain cases, we can exploit the weaknesses in the coding of the programming language itself to veer away from the syntax without causing the compiler to interpret it as an error. In some cases, this provides us with definite advantages such as faster running of the program due to less number of calculations required to complete the program.
I will now demonstrate how to get the same result as the above example program with one such exploit.

New Syntax :-

for( initialization; update; )
{

Body of the loop;

}

New Example :-

for( int i=4; i--; )
{
cout<<"\n "<<(4-i);
getch();
}

In this, the value of the integer 'i' is first assigned as 4, then 3, 2, 1 and 0 respectively on subsequent loops.
So, the output of the program will remain the same. This modified loop will basically decrement the initialized value down to zero. That will be the point at which the program will be terminated.


P.S : Please comment if you liked this post. I hope to make this the first of many "Code Magic" articles.

No comments:

Post a Comment