Question 1
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
int main(void) {
int sum;
for (int i = 1; i <= 5; i++)
sum += i;
printf("%d\n", sum);
return 0;
}
- A The loop should start at 0
- B sum is never initialised, so it starts with garbage and the total is unpredictable Correct
- C sum must be static
- D There is no bug; it prints 15
Correct Answer: Option B
Local variables are not zeroed. Write int sum = 0;. Compilers warn ("variable 'sum' is uninitialized when used here") – never ignore that warning.
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!