Question 7
Back to Exercise
The function should return the sum of an array. Called twice on {1, 2, 3}, what does the program print, and why?
#include <stdio.h>
int total = 0;
int sum_array(const int *a, int n) {
for (int i = 0; i < n; i++)
total += a[i];
return total;
}
int main(void) {
int a[] = {1, 2, 3};
printf("%d ", sum_array(a, 3));
printf("%d\n", sum_array(a, 3));
return 0;
}
- A 6 6
- B 6 12 – sum_array uses the global total, which is never reset, so the second call adds onto the first result Correct
- C 12 12
- D It does not compile
Correct Answer: Option B
The function forgot to declare its own accumulator and silently uses the global. Declare int total = 0; inside the function – and avoid mutable globals so mistakes like this cannot compile.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!