Start with a main function and read 3 integers into 3 variables called num1, num2, num2.
Create a variable max_value and set it to num1.
If num2 > max_value then max_value is num2.
Same for num3
Yep, Manga's answer is straightforward and fulfills the requirement of conditionals. As a side note, the compiler will nicely optimize if you use the built-in std::max -- something like: std::max(x, std::max(y, z));
I must admit, I haven't a clue why this works, but it seems to.
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream>
#include<algorithm>
usingnamespace std;
int main()
{
int x, y, z;
cout << "Enter 3 numbers separated by spaces: ";
cin >> x >> y >> z;
cout << "The largest number is " << max( { x, y, z } );
}
Yes, I've just been looking all through the <algorithm> library, too! So far, it seems to be just the min and max-related items.
These initialiser-list constructors (which came in with C++11) have some decidedly useful hidden features. The OP will never know how useful I found this thread!
The program asks user to enter 3 integer-valued inputs x, y, z separated by spaces. Then the code compares the values of x, y, z and print the largest value. Use either "if" statements or conditional operators or both. Do not use loop and array.
#include <iostream>
int main()
{
std::cout << "Enter 3 numbers separated by spaces: ";
int x;
int y;
int z;
std::cin >> x >> y >> z;
std::cout << "\nThe largest number is ";
if (x >= y && x >= z)
{
std::cout << x;
}
elseif (y >= x && y >= z)
{
std::cout << y;
}
else
{
std::cout << z;
}
std::cout << ".\n";
}
Enter 3 numbers separated by spaces: 1 6 2
The largest number is 6.