found largest numbers among three numbers

In this page we will find the largest number in any three number in C++, Here we have used && – operator.

As we know that the && – operator is used to add two or more conditions together. such as,

if(condition1 && condition2 && condition_n) 
  {
     ......... 
  }

&& – In the operator, only when more than one condition is true, the body-of-if is executed.

Here is the program,

find a largest number in any three number in C++

#include<iostream>
using namespace std;

int main()
 {
   int num1,num2,num3;

   cout<<"Enter any three number:"; 
   cin>>num1>>num2>>num3;

   cout<<endl; 
if(num1>num2 && num1>num3)       // expression
       cout<<num1<<" greatest number among number "<<num2<<" and "<<num3;

   else if(num1<num2 && num3>num2)
       cout<<num2<<" greatest number among number "<<num1<<" and "<<num3;

   else
       cout<<num3<<" greatest number among number "<<num1<<" and "<<num2;

getch();
}

OUTPUT

Enter any three number: 3 4 5
5 is greatest number among number 3 and 4

In this program, three variables are declared.

int num1,num2,num3;

The program has been executed twice.

1st execution

In both these variables, the input is taken from the user. such as

num1 = 3
num2 = 4
num3 = 5

after this, in if statement condition will be checked

num1 > num2 && num1 > num3

means,

3 > 4 && 3 > 5

Because both conditions is becoming false, so the body of if will be skip here. Now the execution will go to the next statement where else-if statement is defined,

In else if statement condition will be checked,

num1 < num2 && num3 < num2

means,

3 < 4 && 5 < 4

Because here, the first condition is becoming true 3<4 but second condition false 5<4, So here body of if-else will also be skipped,

because both conditions are becoming false, so here the body of else will be executed,

Thus a program is successfully executed,

2nd execution

Here, suppose user-entered following input,

num1 = 1
num2 = 6
num3 = 2

after this, in if statement condition will be checked

num1 > num2 && num1 > num3

means,

1 > 6 && 1 > 5

Because both condition is becoming false, so body of if will be skip here.
Now the execution will go to the next statement where else-if statement is defined,

In else-if statement condition will be checked as before,

num1 < num2 && num3 < num2

means,

1 < 6 && 2 < 6

Because here, both conditions is becoming true, so here the body of else if will be printed.

after the program will be terminated.

In 2nd execution, only the else-if statement has the condition true so it is printed while the other two statements if-statement and else statement is false so it is skipped. remember here that the else-statement is executed only when the other statement is false.


C++ Examples

Like it?

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version