Question 5
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
int main(void) {
int sum = 0;
for (int i = 1; i <= 2000; i++)
sum += i * i * i;
printf("%d\n", sum);
return 0;
}
- A The loop runs one time too many
- B The sum (about 4 × 10¹²) far exceeds INT_MAX, and i * i * i itself overflows for large i – signed overflow is undefined Correct
- C i * i * i must be written pow(i, 3)
- D There is no bug
Correct Answer: Option B
INT_MAX is about 2.1 × 10⁹. Use long long sum and compute (long long) i * i * i so the multiplication happens in 64 bits.
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!