Question discussion

What is the output of the following code?public class Test{ public static void main(String args[]){ double[] myList = {1, 5, 5, 5, 5, 1}; d…

281503Medium 1 reply 2,403 views
33
What is the output of the following code?public class Test{ public static void main(String args[]){ double[] myList = {1, 5, 5, 5, 5, 1}; double max = myList[0]; int indexOfMax = 0; for(int i = 1; i < myList.length; i++){ if(myList[i] > max){ max = myList[i]; indexOfMax = i; } } System.out.println(indexOfMax); }}
  • A0
  • B1
  • C2
  • D3
  • E4
Correct answer: B

Discussion 1

0
CCommunity
1

In the given program.
Line 7 : if(myList[i] > max) execute only on time when i =1;
when i = 1 then myList[i] = 5 and max = 1(so the statement is true and if block will be executed).
Then, max = myList[i] = 5 and indexOfMax = i = 1.
After that if statement always false. so indexOfMax value remain 1.

Therefore the value of indexOfMax is 1 at end of the for loop.