Find the largest of three numbers
Description: Write largest(int a, int b, int c). Test with (12, 45, 30) and (7, 7, 3).
Hint:
- Compare with
>=and&&, or callstd::maxwith a list.
Solution
#include <algorithm>
#include <iostream>
int largest(int a, int b, int c) {
if (a >= b && a >= c) return a;
if (b >= c) return b;
return c;
}
int main() {
std::cout << largest(12, 45, 30) << '\n';
std::cout << largest(7, 7, 3) << '\n';
std::cout << std::max({12, 45, 30}) << '\n'; // the library way
}
Output
45
7
45
How it works
- If
ais not the biggest, the answer isborc, so one more check is enough.
Read C++ if else.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |