AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easyarrays1-indexed

~75s

Position of the largest element

The array A is 1-indexed, so its elements are A[1] to A[6]. What is printed?

Integer A[1..6], i, pos
Set A = {4, 19, 7, 23, 2, 11}
Set pos = 1
For i = 2 to 6
    If A[i] > A[pos] Then
        Set pos = i
    End If
End For
Print pos
Show the answer and the worked solution

Correct answer: C.

4

Worked solution

  1. pos starts at 1, where A[1] = 4.
  2. A[2] = 19 beats 4, so pos becomes 2.
  3. A[3] = 7 does not beat 19, but A[4] = 23 does, so pos becomes 4.
  4. A[5] = 2 and A[6] = 11 do not beat 23, so pos stays 4 and 4 is printed.

Answer: 4.

The idea

Keeping an index rather than a value is the standard argmax pattern. The distractor 23 is the value at that position, which the code never prints.

Shortcut. Skip the trace: find the largest element, 23, and count its place in {4, 19, 7, 23, 2, 11}. It is 4th, and pos ends holding exactly that place.

Common trap. 23 is the largest value, not its position; picking it means printing A[pos] instead of pos.

Position of the largest element — Aptitude Question

Position of the largest element: The array A is 1-indexed, so its elements are A[1] to A[6]. What is printed? Answer and worked solution on CodeKairo.

Question

The array A is 1-indexed, so its elements are A[1] to A[6]. What is printed?

Integer A[1..6], i, pos
Set A = {4, 19, 7, 23, 2, 11}
Set pos = 1
For i = 2 to 6
    If A[i] > A[pos] Then
        Set pos = i
    End If
End For
Print pos

Options

  1. 2
  2. 3
  3. 4
  4. 23
Show the answer and the worked solution

Correct answer: C. 4

Worked solution

  1. pos starts at 1, where A[1] = 4.
  2. A[2] = 19 beats 4, so pos becomes 2.
  3. A[3] = 7 does not beat 19, but A[4] = 23 does, so pos becomes 4.
  4. A[5] = 2 and A[6] = 11 do not beat 23, so pos stays 4 and 4 is printed.

Answer: 4.

The idea

Keeping an index rather than a value is the standard argmax pattern. The distractor 23 is the value at that position, which the code never prints.

Shortcut. Skip the trace: find the largest element, 23, and count its place in {4, 19, 7, 23, 2, 11}. It is 4th, and pos ends holding exactly that place.

Common trap. 23 is the largest value, not its position; picking it means printing A[pos] instead of pos.

All Pseudocode questions · placement mock tests