Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Operators

Ajit Deshpande
Greenhorn
Posts: 17
This question is in amock exam:
Can anybody please explain what is the right answer ans and why?
public int guessWhat( int arr[] )
{ int x= 0;
for( int i = 0; i < arr.length; i++ )
x = x < arr[i] ? arr[i] : x;
return x;
}
a) Returns the index of the highest element in the array
b) Returns true/false if there are any elements that repeat in the array
c) Returns how many even numbers are in the array
d) Returns the highest element in the array
e) Returns the number of question marks in the array
Thanks

Anonymous
Ranch Hand
Posts: 18944
Hi Ajit,
The answer is "d". The ternary operators will work like this:
if (x < arr[i])
x=arr[i];
else
x=x;
Let us take array has the following values: a[]={1,2,3,5}
When you pass these values to method:
step 1:
-------
x initialized to 0.
step 2:
--------
Then when i=0 in the loop,the ternary if work like this:
the value of x and the first element of array(ie index is 0)
a[0]=1
if 0 < 1 then
the condition becomes true and so the value of x is replaced with array value.
In this case x=1
step 3
-------
loop is incremented by 1 and so the value of array is the second element in this case it is 2
1 < 2 the condition true and so x is again replaced with array index value.
and so on the process repeats and then the condition becomes false for highest element and then it come out of the loop.
For more details you can put some messages and try to run the program ,you will understand more better.
Hope this clarifies some of your doubts.
Thanks.
Nirmal

Ank Kap
Greenhorn
Posts: 2

hemanshow
Greenhorn
Posts: 25
wat if array is {-1,-2} it will return the value of x i.e. o. So answer should be that it returns the highest value in array or value of x which ever is higher.

Ajit Deshpande
Greenhorn
Posts: 17
Hi Nirmal,
Thanks for the explanation.