C++ Program to find the largest of three numbers


January 17, 2023, Learn eTutorial
2176

How do we find the largest of the three numbers?

The largest number among the given three numbers can be found by comparing the three numbers with each other.

How to write a C++ program to find the largest?

Declare 3 float type variables num1, num2, num3. Ask the user to enter three values. Read the three values to the variables. Compare the numbers with each other. comparison can be performed by using an if condition.

  1. If the first number(num1) is greater than or equal to the second number(num2) and the first number(num1) is greater than or equal to the third number(num3). Then print the largest number as the first number.
  2. Else If the second number(num2) is greater than or equal to the first number(num1) and the second number(num2) is greater than or equal to the third number(num3). Then print the largest number as the second number.
  3. If the first 2 conditions are false, then print the largest number as the third number(num3).
largest of three numbers using the C++ program?

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare float type variables; num1, num2, num3.

Step 5: Print a message to enter three numbers.

Step 6: Read the number into the variables num1, num2, and num3.

Step 7:compare num1 with num2 and num3. If num1 is greater, if 2 condiotions are true print num1 and goto step10 otherwise goto step8

Step 8: compare num2 with num1 and num3. If num2 is greater, if 2 condiotions are true print num2 and goto step10 otherwise goto step9

Step 9: print num3.

Step 10: Exit.

C++ Source Code

                                          #include <iostream>
using namespace std;

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

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

    if(num1 >= num2 && num1 >= num3)
        cout << "Largest number: " << num1;

    else if(num2 >= num1 && num2 >= num3)
        cout << "Largest number: " << num2;
    
    else
        cout << "Largest number: " << num3;
  
    return 0;
}
                                      

OUTPUT

Run 1
Enter three numbers: 8
6
12
Largest number: 12
Run 2
Enter three numbers: 5.3
6.4
2.1
Largest number: 6.4