C++ nested if statements

  • When if, if-else or if- else if- else statements are used inside another if, else if or else statements then these type of statements are known as nested if statements.
  • Here is a syntax of nested if statement as follows:
  • Syntax

    if (condition1)

    {

    if(condition2)

    {

    Statements;

    }

    else

    {

    Statements;

    }

    }

    else

    {

    Statements;

    }
  • A nested if statement contains various structures like if..else statement inside if, if statement inside else etc. In the above syntax if condition1 present in the parenthesis of outer if block is true then compiler will check the condition2 present in the parenthesis of inner if statement if it is true then the statements present inner if block will be executed if it is false then the statements present inner else block will be executed and if condition1 is false then the statements present inside the outer else block will be executed. You can understand this concept more clearly with the help of following diagram:
  • decision-making
  • Here is an example of nested if statement as follows:

Example

#include<iostream.h>

#include<conio.h>

int main()

{

int a,b;

cout<<"\n Enter the value of a and b:";

cin>>a>>b;

if(a==10)

{

cout<<"\ninside outer if block:value of a is:"<<a;

if(b==20)

{

cout<<"\ninside inner if block:value of b is:"<<b;

}

else

{

cout<<"\ninside inner else block:value of b is:"<<b;

}

}

else

{

cout<<"\ninside outer else block:value of a is:"<<a<<"and value of b is:"<<b;

}

getch();

return 0;

}

Output

The output of the above program is as follows:

Enter the value of a and b: 10

20

inside outer if block:value of a is:10

inside inner if block:value of b is20