What will be the output of the following pseudo code for arr[] = 1, 2, 3, 4, 5…
2024
What will be the output of the following pseudo code for arr[] = 1, 2, 3, 4, 5 ?
initialize i, n
initialize an array of size n
accept the values for the array
for i = 0 to n - 2
arr[i] = arr[i] + arr[i+1]
end for
print the array elements- A.
3 5 7 9 5
- B.
3 5 7 9 11
- C.
3 5 9 15 20
- D.
error
Attempted by 458 students.
Show answer & explanation
Correct answer: A
Concept
An in-place pass of the form arr[i] = arr[i] + arr[i+1] replaces each element with the sum of itself and its immediate right neighbour. When the loop variable i ranges from 0 to n - 2, only the first n - 1 positions are ever written; the very last position (index n - 1) is never the target of an assignment, so its original value is preserved. Because each read of arr[i+1] uses an index that is at most n - 1, every access stays within the array bounds.
Application
Start with arr = [1, 2, 3, 4, 5] (n = 5), so the loop runs i = 0, 1, 2, 3. Tracing each step:
i = 0: arr[0] = arr[0] + arr[1] = 1 + 2 = 3 -> [3, 2, 3, 4, 5]
i = 1: arr[1] = arr[1] + arr[2] = 2 + 3 = 5 -> [3, 5, 3, 4, 5]
i = 2: arr[2] = arr[2] + arr[3] = 3 + 4 = 7 -> [3, 5, 7, 4, 5]
i = 3: arr[3] = arr[3] + arr[4] = 4 + 5 = 9 -> [3, 5, 7, 9, 5]
The last element (index 4, value 5) is never assigned because the loop stops at i = n - 2 = 3, so it stays as 5. The printed array is 3 5 7 9 5.
Cross-check
Bounds safety: the largest index read is arr[i+1] at i = 3, which is arr[4] = arr[n-1], the last valid index, so no out-of-bounds access happens and the program does not error. Sanity on the result: positions 0..3 each equal the sum of two consecutive originals (1+2, 2+3, 3+4, 4+5 = 3, 5, 7, 9) while the final position keeps its original 5, matching 3 5 7 9 5.