C++ for() control executive statement

The ‘for()’ statement like the ‘do() while’ and ‘while()’ statement is use for iterating a code until certain condition is fulfilled.The pictorial representation of for() statement is shown below.

Link :C++ do() while

Link :C++ while()

And the syntax of for() statement is shown below.

for( expression1 ; expression2 ; expression3 ) //note the semi colon separating each expression

In the first ‘expression1’ a variable will be initialized to some value.

The second ‘expression2’ will return true or false value if it returns false the Code1 will stop executing and the

third ‘expression3’ will increment or decrement the value of the variable assigned in expression1.

A program is given below which implements the for() statements.

for( int i=0 ; i<3 ; i++)
  cout<< i << endl;

The first expression inside the ‘for()’ is ‘i’ being assigned to 0,the second one test if ‘i’ is smaller than 3 and the third one increment the ‘i’ value.The output of the program is,


Similarity of for() wiht do() while and while()

The for() statement is same as the do while() or while() statement except it allows you to bundle together the necessary expression for iterating the code as one whole expression.We could also have written the above code as,

int i=0 ;

for( ; i<3 ; )
  cout<< i << endl ;
  i++ ;

Output is till the same.


A little more complex program involving for() is shown below.In this program let us try to draw a triangle with ‘-‘(hyphen-minus sign).

#include <iostream>
#include <iomanip> /*include the function setw() */

using namespace std;

int main( )
int i = 1, count = 1 ;

cout << setw(8) << "-" << endl ; //the tip '-' of the triangle

for (int i = 1; i <8 ; ++i )
  if (i == 7)  /*This is for the base fo the triangle*/
    cout << setw(0) << "-" ; //write the first '-' at the base 
    for (int i1 = 1; i1 < 15 ; ++i1 ) //write '-' at the base of triangle
    cout << setw(1) << "-" ;
  else //generate '-' between tip and base 
    cout << setw(8 - i) << "-" << setw(i * 2) << "-" << endl ;	

cin.get( );
return 0;

The output should look like this,