Website For Developers

Nested if else in C++



if statement within an if statement is called nested if statement.
For applying multiple condition we use nested if else in C++.
For example: We have to apply two conditions on a shirt. One is to check the size; and second one is to check the color.


Syntax

if (Outer Condition) {
  // Outer if body
  if (Inner Condition) {
    // Inner if body
  }
}
else () {
  // else body
}


Example of nested if in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int number;
  cout<< "Enter Number: ";
  cin<< number;

  if(number<10) {
    if(number>5) {
      cout<< "Number is less than 10 but greater than 5";
    }
  }

  else {
    cout<< "Number is greater than 10";
  }
  getch();
  return 0;
}

Output

Enter Number: 7
Number is less than 10 but greater than 5


Example of nested if else in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int num1, num2;
  cout<< "Enter First Number: ";
  cin<< num1;
  cout<< "Enter Second Number: ";
  cin<< num2;

  if(num1<10) {
    if(num2<10) {
      cout<< "Both numbers are less than 10";
    }
    else {
      cout<< "Only first number is less than 10";
    }
  }

  else {
    if(num2<10) {
      cout<< "Only second number is less than 10";
    }
    else {
      cout<< "Both numbers are greater than 10";
    }
  }
  getch();
  return 0;
}

Output

Enter First Number: 34
Enter Second Number: 21
Both numbers are greater than 10