C++ program to find the largest among three numbers can be computed by comparing them with each other. A number x is said to be the largest among three numbers when its value is greater than other two numbers say y and z. For example, 20 is the largest among three numbers 10, 15, 20.
Page content(s):
Additional content(s):
1. Algorithm to find the largest among three numbers
// $x$, $y$, $z$ are three input numbers//
1. Check if $x$ is greater or equal to $y$
2. If step [1] is true, then check if $x$ is greater or equal to $z$
3. If step [2] is true, then print $x$ is the largest
4. If step [2] is false, then print $z$ is the largest
5. If step [1] is false, then check if $y$ is greater or equal to $z$
6. If step [5] is true, then print $y$ is the largest
7. If step [5] is false then print $z$ is the largest
2. Pseudocode to find the largest among three numbers
Input: Three numbers $x$, $y$, $z$
Output: Largest among $x$, $y$, $z$
1. Procedure findLargest($x$, $y$, $z$):
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12. End Procedure
3. Time Complexity to find the largest among three numbers
Time Complexity: O(1)
4. C++ Program to find the largest among three numbers
/************************************************ alphabetacoder.com C++ program to find largest among three numbers *************************************************/ #include <iostream> using namespace std; int main() { // declare variables int x, y, z; //take input of three numbers cout << "Enter the three numbers = "; cin >> x; cin >> y; cin >> z; // find the largest number if (x >= y) { if (x >= z) cout << x << " is the largest number."; else cout << z << " is the largest number."; } else { if (y >= z) cout << y << " is the largest number."; else cout << z << " is the largest number."; } return 0; }
Output
Case 1:
Enter the three numbers = -13 -18 -23
-13 is the largest number.
Case 2:
Enter the three numbers = 10 20 30
30 is the largest number.