C++ Execution control statement:if() else{ } , for() , while() ,do{} while() ,switch


The execution control statements of C++ consists of if() , if() else, for() , while() , do while() , switch() and go to() (will not discuss here).These statements are known as execution control statements because they direct which code fragment to be executed in your program.

Suppose you have a situation where you want to execute a piece of code in certain condition and some other code in other condition.In such scenario using the appropriate execution control statement will compute your program in a way you want it.Basically,execution control statements will come in handy -very much- when you are writing a decision making programs or option based user interacting program.But this does not mean they are specifically suitable only for such types of program.You will see that they can be used in many other ways .In fact it won’t be an exaggeration to say that they will be used in almost all your programs.

Note:click on the link below to go directly to the particular execution control section.

if() else.
ii)do while().
iii)while().
iv)for().
v)switch().



if() else

This statement is usually written as,

if(expression1)
{
    ///code 1
}
else
{
    ///code 2
}

C++ if else statement
 
If the expression1 is true or returns true code 1 is executed else code 2 is executed for instance,look at the program below.
 

int i1=90 ,i2 =100 ;

if( i1 == i2 )
{
  cout<< i1+i2 ;
}
else
  cout<< i2/i1 ;

Since i1(90) is smaller than i2(100) the expression i1==i2(‘==’ is used not ‘=’) is false so the code under else is executed and we get the output as,

1 (the decimal point value is truncated for int type)
Link: Integral type:Built-in Data types.

We can also add more condition by using the statement else if() in between the if( ) and else statement as shown below.

string case=”cold and cough” ;

if( case==”Summer” )
{
  cout<< “Take chilled Beer” ;
}
else if( case==”Cold and cough”)
{
  cout<< “Take Vodka” ;
}
else
  cout<< “Take water” ;

The code under else is executed only when all the other cases under if() and else if() statements are false,so else is added at the last.Note else statement is not inevitable, even without including it the if() and else if() statement will just work fine.



do while()

This statement helps in iterating the code until certain condition is fulfilled.The rule is straightforward if the expression under while() statement returns false the code under do statement stops executing.

C++ do while statement

In the code below when i becomes 3 the expression i<3 returns false and so the code stops executing.

int i=0 ;

do
{
  cout<< i ;
++i ;
}
while( i<3 )

 
The output is
 
0
1
2






While()

When ‘do‘ statement is removed from the do while we get while control statement.

C++ while loop statement

A code example using while() statement is provided below.

int i=0 ;

while( i<3 )
{
  cout<< i << endl ;
++i ;
}

The output is the same as do while() code.While() is preferred instead of the do while() statement which omits the need for writing the extra do statement in your program.



for( )

This statement is written as,

for( expression1 ; expression2 ; expression3 )
{
  //Code
}

 
for statement

In the first expression:expression1 a variable will be initialized to some value.The second expression:expression2 will return true or false value if it returns false the code will stop executing and the third expression: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 output is

0
1
2

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++ ;
}

 
The above code will also work perfectly like the previous code.



Switch( ) case

Switch() statement is like the if() else statement but the syntax is a bit different.It uses switch() and case statement to control the execution of the code.The syntax is shown below.

switch(exp1)
{
  case expa :
    //code 1
    break ;

  case expb :
    //code 2
    break;

  case expc :
    //code 3
    break;

  default :
    //code 4
}

 
C++ switch case statement

If exp1 matches with expa then code 1 is executed or if exp1 matches with expb then code 2 is executed and so on.If exp1 does not match with expa or expb or expc then the code under default i.e. code 4 is executed.Note the break; statement after every code.The function of this statement is to stop iterating the code under the switch() statement.A program using the switch() statement is given below.

char c=’c’;
switch(c)
{
case ‘a’ :  //If c is equal to ‘a’ case
    cout<< “The character in c is a “;
    break;

case ‘b’ :  //If c is equal to ‘b’ case
    cout<< “The character in c is b “;
    break;

default:  //if c is unknown case
    cout<<“The character of c is unknown “;
    break ;
}

 
Since c(‘c’) is not equal to ‘a’ or ‘b’ the code under default is executed so the output is

The character of c is unknown

The expression pass to switch() statement cannot be a string or a float type,it can only be a character or an integer,if you pass a string or a float you will get an error.
 

string s=”happy” ;

switch( s )   ///You will get error here
{
&nbsp ; case 89.75 :
    cout<< “new” << endl ;
    break;

  default:
    cout<< s << endl;
    break ;
}

 
If you want to compare string or use string as a value to determine the correct code to execute in the program then you can use if() else statement.




Which is faster if() else or switch() statement?

There is certain curiosity as to which control statement is faster if() else or switch() statement.To test it I wrote a program with 5000 cases each for if() else and switch() statement.The program will accept an integer value and the time taken by the if() else or switch() statement to find the correct case/value is noted.The program is given below.

i)The first program uses if() else statement.
ii)The second program uses switch() statement.

***Note:The programs are tested in Ubuntu.
 

/****If() else case ****/

#include <iostream>
#include <sys/time.h>

using namespace std ;

typedef unsigned long long timestamp_t;

static timestamp_t get_timestamp ()
{
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
}

int main()
{
int i ;
cout<<“Enter any number between 0 to 1000 \n”;
cin>> i ;
cin.ignore() ;

timestamp_t t0 = get_timestamp() ;

if(i==0)
{
  cout<< i << endl ;
}
else if(i==1)
{
  cout << i << endl ;
}
else if(i==2)
{
  cout << i << endl ;
}
    .   /*else if from 3 to 4998 is not shown here */
    .
    .
else if(i==4999)
{
  cout << i << endl ;
}
else if(i==5000)
{
  cout<< i << endl ;
}

timestamp_t t1 = get_timestamp();
double secs = (t1 – t0) / 1000000.0L;

cout<< secs ;

cin.get() ;
return 0 ;
}

 

 

/**switch() ***/

#include <iostream>
#include <sys/time.h>

using namespace std ;

typedef unsigned long long timestamp_t;

static timestamp_t get_timestamp ( )
{
struct timeval now;
gettimeofday (&now, NULL) ;
return now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
}

int main( )
{
int i ;
cout<<“Enter any number between 0 to 200 \n”;
cin>> i ;
cin.ignore();
timestamp_t t0 = get_timestamp() ;

switch(i)
  {
  case 0:
    cout<< i << endl ;
    break ;

  case 1:
    cout<< i << endl ;
    break ;
  .   /*Switch case from 2 to 4998 is not shown here */
  .
  .
  case 4999:
    cout<< i << endl ;
    break ;

  default :
    cout<< i << endl ;
    break ;
  }

timestamp_t t1 = get_timestamp();
double secs = (t1 – t0) / 1000000.0L;

cout<< secs ;
cin.ignore();
return 0;
}

 

 
The table below shows the input value and the time taken by the if() else and switch() statement to find the correct code of the input value.
 

Input valueif() elseswitch()
20004.2e-053.4e-05
7773.6e-055.6e-05
45000.0001443e-05
39995.3e-053.1e-05
45558.4e-053.3e-05
13e-055e-05
28903.2e-052.9e-05
Average6.0142e-053.757e-05

 
You can see that the average time of switch() is lesser than the if() else statement.If you are running the program to check the execution time of the if else and switch() statement you may not get the same execution time for the same input as given in the table above but the average value of switch() will always be lesser than the if() else statement.