Question Mark

hi
i'm gonna using question mark for comparing several numbers
like this:
a>b?a:b;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main(){
	
	int num[5];
	int i;
	for( i=0;i<5;i++){
		cout<<"enter number: ";
		cin>>num[i];
		
		num[i]>num[i]?num[i]:num[i];
}
		cout<<(num[i]>num[i]?num[i]:num[i]);
	return 0;
}
Last edited on
That's nice.

Do you have a question?
lol
yes i have a question
answer is wrong
You didn't ask a question, so I'm going to point out a couple of problems.

Line 11: This line does nothing. The ternary operator is an expression. You do nothing with the result of the evaluation of the expression.

Line 13: This line is outside the range of the for statement. The value of i may be out of range. If you had used for (int i=0; ... i would be undefined.

In both lines 11 and 13, your conditional expression makes no sense. num[i] will never be greater than itself.

Also on lines 11 and 13, You have the same expression on both sides of the :
That's not illegal, but it serves no purpose.

That is called a Ternary operator.

Like you said it is generally used to compare two numbers ,

syntax:

<type> variable = (condition)? if:else

e.g.

int var = (7>5)? 5 : 4

in this case the condition is true so the value to be assigned for the "var" goes for if part
i.e, var =5

Regards,
Visweswaran
got it
thanks
question again
i couldn't get correct answer
how should i compare several numbers with this way (a>b?a:b)
i dont know num[i] compare with ????

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main(){
	
	int num[5];
	int com;
	
	for(int i=0;i<5;i++){
		cout<<"enter number: ";
		cin>>num[i];		
		com=num[i]>num[i]?num[i]:num[i];
		if(num[i]==i)
		cout<<com;
}
	
	return 0;
}
Line 11: You're now storing the result of the expression (com), but your ternary expression still makes no sense.

There are three parts to a ternary expression (hence the name). The first part is a conditional expression that evaluates true or false.
 
com = num[i] > num[i] ? num[i] : num[i];

Here you're testing if num[i] is greater than num[i]. How can that ever be true?

Second and third parts:
 
com = num[i] > num[i][/u] ? num[i] : num[i];

If the condition is true (which it will never be), the value after the ? is used.
If the condition is false, the value after the : is used.
Since the value after the ? and after the : are the same, what is the point of the statement?
You are essentially writing:
a<a ? a : a;




Last edited on
Topic archived. No new replies allowed.