Find Maximum From Three Numbers Using Nested If in CPP

  1. Home
  2. Tutorials
  3. CPP
  4. CPP Programs
  5. Nested If Statement
  6. Program

Source Code:

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    
    int a,b,c;
    cout<<"Enter First Number: ";
    cin>>a;
    cout<<"Enter Second Number: ";
    cin>>b;
    cout<<"Enter Third Number: ";
    cin>>c;
    
    if( a > b ) {
        if( a > c ) {
            cout<<a<<" is Greater";
        } else {
            cout<<c<<" is Greater";
        }
    } else {
        if( b > c ) {
            cout<<b<<" is Greater";
        } else {
            cout<<c<<" is Greater";
        }    
    }
    return 0;
}

Output:

find maximum out of three numbers using nested if statement

Working:

In this program example we declare three variables of int data type.These variables are used to take input from user. After declaration we write input statements for taking individual input in these three variables. We can also use single cin statement for taking input in these three variables. But it is good practice to write individual statement for taking input in all variables.

After input process is completed then we use nested if statement for displaying maximum number. First of all we compare A with variable B. If A is greater in outter if statement the we will compare this greater A with the third available variable C. At this point if A > C  also true then if means A is greater than both B and C. Then we will print value of A.

In Second Case if in inner if statement  A > C  become false then it menas C is greater beacuse A is already greater than B but smaller than C.

In third case the else statement of outter if statement will execute and in inner if statement of else part will be execute in the same semantic.

Comments
Login to TRACK of Comments.