Home | | Computer Science 11th std | C++ Nested if

Flow of Control | C++ - C++ Nested if | 11th Computer Science : Chapter 10 : Flow of Control

Chapter: 11th Computer Science : Chapter 10 : Flow of Control

C++ Nested if

An if statement contains another if statement is called nested if.

Nested if

 

An if statement contains another if statement is called nested if. The nested can have one of the following three forms.

1. If nested inside if part

2. If nested inside else part

3. If nested inside both if part and else part

The syntax of the nested if:


If nested inside if part

if (expression-1)

{

      if (expression)

      {

           True_Part_Statements;

      }

      else

      {

           False_Part_Statements;

      }

}

else

      body of else part;

 

If nested inside else part

if (expression-1)

{

      body of else part;

}

else

{

      if (expression)

      {

           True_Part_Statements;

      }

      else

      {

           False_Part_Statements;

      }

}

If nested inside both if part and else part

if (expression)

{

      if (expression)

      {

           True_Part_Statements;

      }

      else

      {

           False_Part_Statements;

      }

}

else

{

      if (expression)

      {

      True_Part_Statements;

      }

      else

      {

      False_Part_Statements;

      }

}

In the first syntax of the nested if mentioned above the expression-1 is evaluated and the expression result is false then control passes to statement-m. Otherwise, expression-2 is evaluated,if the condition is true, then Nested-True-block is executed, next statement-n is also executed. Otherwise Nested-False-Block, statement-n and statement-m are executed.

The working procedure of the above said if..else structures are given as flowchart below:



 

Illustration 10.5 – C++ program to calculate commission according to grade using nested if statement

#include <iostream>

using namespace std;

int main()

{

      int sales, commission;

      char grade;

      cout << "\n Enter Sales amount: ";

      cin >> sales;

      cout << "\n Enter Grade: ";

      cin >> grade;

      if (sales > 5000)

      {

           commission = sales * 0.10;

           cout << "\n Commission: " << commission;

      }

      else

      {

           commission = sales * 0.05;

           cout << "\n Commission: " << commission;

      }

      cout << "\n Good Job ..... ";

      return 0;

}

Output:

Enter Sales amount: 6000

Enter Grade: A

Commission: 600

Good Job .....


Tags : Flow of Control | C++ , 11th Computer Science : Chapter 10 : Flow of Control
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 10 : Flow of Control : C++ Nested if | Flow of Control | C++


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.