This week's book giveaway is in the Android forum. We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line! See this thread for details.

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

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

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

Joined: Jun 15, 2000
Posts: 17

posted

0

Hi Nirmal, Thanks for the explanation. It has made things clearer. But d is not correct if the first element of the array is 0? What then?

The problem hemanshow pointed out occurs only if all array elements are negative. (If at least one is zero or higher, then it will be correctly identified as the greatest i.e. most positive.) If all are negative, then none of the answers given are correct. Obviously the question writer did not think of this possibility, so the best possible answer is D. Just answer that, and it will be "right" as far as that author is concerned. If you know what mock exam this came from, then you can contact the author and let them know of the error in the question - maybe it will be corrected.