Decision Control Statements in C++ – Part 1

Written by

Vaaruni Agarwal

There are many situations where one has to make a decision. If you have a ball in front of you and a video game then you have to decide which one you should pick. These decisions are often based on some conditions. Like you would look for the weather outside before going to play out with the ball. But, in case of a video game, you would have to check for its battery first.

Now in case of weather, if the weather is good you will go out to play else you will stay back and play with a video game.

Such statements are called decision control statements and are widely used in C++ programming languages. 

The different decision control statements in C++ include:

  • If statement
  • If- else statement
  • If – Else If Statements
  • Nested If Else Statements
  • Switch Case Statements

Apart from these, the Conditional Operator (?:) about which we have already learned in the chapter on the Operators can also be used to check conditions in C++.

if statement:

if statement is one that checks a particular condition. If that condition holds true then it executes a set of statements.

These statements when enclosed within curly braces {} form the body of if statement.

Syntax:

if (condition)
{
  statement(s);
}

Example:

#include <iostream.h>

int main()

{

    int a = 5, b = 5 ;

    if ( a == b )

    {

cout<< "a and b are equal\n";

    }

    return 0;

}

The above example will print 

a and b are equal

on the output screen.

if-else statement:

if-else statement ensures that if the given condition is true then a particular block of statements or a single statement is executed.

However, if the condition stands false then some other statements are executed.

Syntax:

if(condition)

    {

        statement;

        statement;

        ....

    }

    else

    {

        statement;

        statement;

        ....

    }

Example:

#include <iostream.h>

int main()

{

    int a ,b;

cout<<”\n Enter two values”;

cin>>a>>b;

    if ( a == b )

    {

 cout<< "a and b are equal\n" ;

    }

    else

    {

cout<< "a and b are not equal\n" ;

    }

    return 0;

}

In the above example if the user enters both values that are same then the condition will be true and the message for equality will be printed. However, if the different values are entered by the user then the else part will be executed.

Both these statements are used to check for a single condition only, however, there may be instances where we need to check multiple conditions, in that case, if –else if statements and Switch case Statements are used, about which we will learn in the next chapter.

 

Decision Control Statements in C++ &#8211; Part 1