30.4k views
4 votes
Which one of the following is the correct code snippet for calculating the largest value in an integer array list aList?

a. int max = aList.get(0); for (int count = 1; count < aList.size(); count++) { if (aList.get(count) > max) { max = aList.get(count); } }
b. int max = 0; for (int count = 1; count < aList.size(); count++) { if (aList.get(count) > max) { max = aList.get(count); } }
c. int max = aList.get(0); for (int count = 1; count > aList.size();count++) { if (aList.get(count) >= max) { max = aList.get(count); } }
d. int max = aList[1]; for (int count = 1; count < aList.size();count++) { if (aList.get(count) > max) { max = aList.get(count); } }

User Hank Lin
by
5.4k points

1 Answer

4 votes

Answer:

Option a. int max = aList.get(0); for (int count = 1; count < aList.size(); count++) { if (aList.get(count) > max) { max = aList.get(count); } }

is the correct code snippet.

Step-by-step explanation:

Following is given the explanation for the code snippet to find largest value in an integer array list aList.

  1. From the array list aList, very first element having index 0 will be stored in the variable max (having data type int).
  2. By using for starting from count =1 to count = size of array (aList), we will compare each element of the array with first element of the array.
  3. If any of the checked element get greater from the first element, it gets replaced in the variable max and the count is increased by 1 so that the next element may be checked.
  4. When the loop will end, the variable max will have the greatest value from the array aList.

i hope it will help you!

User LeslieM
by
5.2k points