Easy Tutorial
❮ Input Output Operators Overloading Cpp Date Time ❯

C++ if...else Statement

C++ Decision

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

Syntax

The syntax for an if...else statement in C++:

if(boolean_expression)
{
   // Statements to execute if the boolean expression is true
}
else
{
   // Statements to execute if the boolean expression is false
}

If the boolean expression is true, the code inside the if block is executed. If the boolean expression is false, the code inside the else block is executed.

Flowchart

Example

#include <iostream>
using namespace std;

int main ()
{
   // Local variable declaration
   int a = 100;

   // Check the boolean condition
   if( a < 20 )
   {
       // Statement to execute if the condition is true
       cout << "a is less than 20" << endl;
   }
   else
   {
       // Statement to execute if the condition is false
       cout << "a is greater than 20" << endl;
   }
   cout << "The value of a is " << a << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

a is greater than 20
The value of a is 100

if...else if...else Statement

An if statement can be followed by an optional else if...else statement, which can be used to test multiple conditions.

When using if...else if...else statements, the following points should be noted:

Syntax

The syntax for an if...else if...else statement in C++:

if(boolean_expression 1)
{
   // Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
   // Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
   // Executes when the boolean expression 3 is true
}
else 
{
   // Executes when none of the above conditions are true
}

Example

#include <iostream>
using namespace std;

int main ()
{
   // Local variable declaration
   int a = 100;

   // Check the boolean condition
   if( a == 10 )
   {
       // Statement to execute if the if condition is true
       cout << "The value of a is 10" << endl;
   }
   else if( a == 20 )
   {
       // Statement to execute if the else if condition is true
       cout << "The value of a is 20" << endl;
   }
   else if( a == 30 )
   {
       // Statement to execute if the else if condition is true
       cout << "The value of a is 30" << endl;
   }
   else
   {
       // Statement to execute if none of the above conditions are true
       cout << "No matching value" << endl;
   }
   cout << "The exact value of a is " << a << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

No matching value
The exact value of a is 100

C++ Decision

❮ Input Output Operators Overloading Cpp Date Time ❯