LearnFrenzy
Sign in Take a free test

C Loops · Find the Error · Question 3

Error: using a for-loop variable after the loop Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links