Question 3
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
int main(void) {
int a[] = {4, 8, 15, 16};
for (int i = 0; i < 4; i++)
if (a[i] == 15)
break;
printf("found at %d\n", i);
return 0;
}
- A break cannot be used in a for loop
- B i is declared in the for header, so it does not exist after the loop Correct
- C a must have a size
- D There is no bug; it prints found at 2
Correct Answer: Option B
The scope of a variable declared in the for initialisation ends with the loop. Declare int i; before the loop to keep its final value.
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!