You are teaching beginners A, B, C at your company.
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
You are teaching beginners A, B, C at your company. The beginners wrote the following functions. These functions receive an array of integers a and outputs the sum of all elements in array a.
Choose all functions that work properly. At least 1 function works properly.
Beginner A
function sum(a) {
let answer = 0;
for (let i = 0; i < a.length; i++) {
answer += a[i];
}
return answer;
}
Beginner B
function sum(a) {
let answer = 0;
for (let i = a.length; i > 0; i--) {
answer += a[i];
}
return answer;
}
Beginner C
function sum3(a) {
let answer = 0;
let i = 0;
while (i) {
if (i == a.length) {
break;
}
answer += a[i];
i++;
}
return answer;
}
Show answer & explanation
Beginner A's function correctly iterates from index 0 to length-1, accumulating all array elements. Beginner B has an off-by-one error: it starts at a.length, causing it to access a[a.length] which is undefined. Beginner C's while loop condition while (i) fails immediately when i = 0, never entering the loop body, so it returns 0.
Step-by-step Derivation:
Beginner A: Loop runs for i = 0, 1, 2, ..., length-1. Each a[i] is valid and added to answer. ✓
Beginner B: Loop condition is i = a.length; i > 0; i--. First iteration accesses a[a.length] which is undefined (arrays are 0-indexed to length-1). This causes NaN in the sum. ✗
Beginner C: while (i) evaluates i as a boolean. When i = 0, the condition is falsy, so the loop never executes. Returns 0 instead of the sum. ✗