The following program written in C++ should calculate the sum of an array a that consists...
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
The following program written in C++ should calculate the sum of an array a that consists of n 32 bit integers.
int sum(int n, int* a) {
int answer = 0;
for (int i = 0; i < n; i++) {
[ A ]
}
return answer;
}
Choose the correct statement to fill in for [ A ].
Show answer & explanation
To calculate the sum of array elements, we need to accumulate each element into the answer variable. The += operator adds the current element to the running total. Option A would overwrite answer with each element (result: last element only). Option C uses =+ which is technically assignment of the unary positive operator (same as = alone). Option D is invalid syntax in C++.
Step-by-step Derivation:
For a sum operation, we need: answer = answer + a[i]. The compound assignment operator += is the correct and idiomatic way to express this in C++. Tracing through an example array [1, 2, 3]: initially answer=0, after i=0: answer=0+1=1, after i=1: answer=1+2=3, after i=2: answer=3+3=6. This gives the correct sum. Option A would give 3 (the last element). Option C also assigns but is unusual syntax. Option D is a syntax error (left-shift or invalid operator in this context).