Easy Tutorial
❮ Cpp Pointer Operators Cpp Stl Tutorial ❯

Nested if Statements in C++

C++ Decision Making

In C++, nested if-else statements are legal, which means you can use another if or else if statement within an if or else if statement.

Syntax

The syntax for a nested if statement in C++:

if( boolean_expression 1)
{
   // Executed when boolean expression 1 is true
   if(boolean_expression 2)
   {
      // Executed when boolean expression 2 is true
   }
}

You can nest else if...else in a similar way to nesting if statements.

Example

#include <iostream>
using namespace std;

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

   // Check boolean condition
   if( a == 100 )
   {
       // Check the following condition if the condition is true
       if( b == 200 )
       {
          // Print the following statement if the condition is true
          cout << "The value of a is 100, and the value of b is 200" << endl;
       }
   }
   cout << "The exact value of a is " << a << endl;
   cout << "The exact value of b is " << b << endl;

   return 0;
}

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

The value of a is 100, and the value of b is 200
The exact value of a is 100
The exact value of b is 200

C++ Decision Making

❮ Cpp Pointer Operators Cpp Stl Tutorial ❯