Conditional Operator

// Enter 2 numbers. Program should use CONDITIONAL OPERATOR to determine which
// is larger and which is smaller. Need help. Tony Gaddis book does not go into
// this very much at all.
#include <iostream>
using namespace std;

int main(int argc, const char * argv[])
{
int num_1, num_2, x;

cout << "Enter a number: " << endl;
cin >> num_1;

cout << "Enter another number: " << endl;
cin >> num_2;
// Need to use CONDITIONAL OPERATOR, does not work
(num_1 > num_2) ? (num_1 = x) : (num_2 = x);

cout << x << " is the larger number" << endl;

// Conditional Operator not used, but this works
/*if (num_1 > num_2)
cout << num_1 << " is the larger number." << endl;

else if (num_2 > num_1)
cout << num_2 << " is the larger number." << endl;

else
cout << "The numbers are equal." << endl;*/



return 0;
}

Last edited on
Please use code tags around your code. You can either press the <> button or put [ code] before and [ /code] after (without the space) example:
[code]int main()
{
     return 0;
}[/code]
would look like
1
2
3
4
int main()
{
    return 0;
}


normally you would do something like
 
some_variable = conditon ? value1 : value2;



Also you have your assignment backwards. In math would you do num_1 = x to assign a value to x? No, you would do x = ... To use the ternary operator you would do x = num_1 > num_2 ? num_1 : num_2; which is the same as
1
2
3
4
5
6
7
8
if(num_1 > num_2)
{
    x = num_1;
}
else
{
    x = num_2;
}
Last edited on
You're doing it backwards.
(num_1 > num_2) ? (num_1 = x) : (num_2 = x);
should be
num_1 > num_2 ? x = num_1 : x = num_2;
@yay295 he is doing it backward but, there is also no need for the x = when getting to the true/false parts. That should be at the front of the expression. It should look like x = num_1 > num_2 ? num_1 : num_2;
Good point. I had actually just been thinking he could do cout << ( num_1 > num_2 ? num_1 : num_2 ); but I didn't think to apply that to setting x.
Thanks you so much. Ive been stuck on this for weeks. It worked! The book I'm using doesn't go into detail on conditional operators.
You're welcome. Check out the bottom of this page for more in depth information: http://www.cplusplus.com/doc/tutorial/operators/
Topic archived. No new replies allowed.