C++ Programming Series: Using Conditional Statements (Part 6)

In the previous posts, we learned very beautiful things of which the most beautiful is game development.

We have covered if-statement, if-else statement, if-else-if-statement, switch-statement, while-statement and do-while statement but there is another very important and most frequently used conditional statement called as the for-statement. It is a bit more complex but neat and short.

Following is the code to which you are already familiar with:

#include <iostream>
using namespace std;

int main()
{
  int loopCounter = 0; //Declaring and initializing a loop counter

  while(loopCounter < 10) //Condition (related with loop counter)
  {
    //All looping codes

    loopCounter++; //Changing loop counter
  }

  return 0;
}

Now, here is the code which is exactly the same as the above code but is neat and short:

#include <iostream>
using namespace std;

int main()
{
  //for(Declaring and initializing loop counter;
  //Condition (related with loop counter);
  //Changing loop counter)
  for(int loopCounter = 0; loopCounter < 10; loopCounter++)
  {
    //All looping codes
  }

  return 0;
}

for loop requires two semi-colon. Leaving them empty i.e for( ; ; ), will cause an infinite loop. Here is the format of for-statement for a quick overview:

for( Initializing variable(s); Condition(s); Changing variable(s) )
{ -Codes to be executed- }

Remember that each variable has a limited scope after which it is destroyed or deallocated from the memory and can not be used after that. Its scope is limited only to its block (or space between any two flower brackets). Hence, there is a definite difference between the loopCounter variables of while and for loops mentioned above.

The one used in the while-statement can be called after the while-statement’s block. The other used in the for-statement can not be called after the for-statement’s block.

It will not effect anything if loopCounter++; or ++loopCounter; is used in the for-statement.

Getting used to such small differences will lead to a better programming style, lesser errors and of course, better programming. Now, you have to use for-statement(s), cout << "*";, cout << " "; and cout << endl; in the best way possible to have that output:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Good luck! And come back if there are some doubts…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s