Bird
0
0

Identify the error in this C function:

medium📝 Debug Q6 of 15
C - Loop Control Statements
Identify the error in this C function:
int findValue(int arr[], int size) {
  for(int i = 0; i < size; i++) {
    if(arr[i] == 10)
      return i;
    else
      return -1;
  }
}
AThe loop condition is incorrect.
BThe function returns -1 too early, inside the loop.
CThe function does not return any value.
DThe return statement syntax is invalid.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze return inside loop

    Return -1 is inside else, so if first element is not 10, function returns -1 immediately, not checking rest.
  2. Step 2: Understand correct logic

    Return -1 should be after loop to check all elements before concluding not found.
  3. Final Answer:

    The function returns -1 too early, inside the loop. -> Option B
  4. Quick Check:

    Return inside else causes premature exit [OK]
Quick Trick: Place return -1 after loop, not inside it [OK]
Common Mistakes:
  • Returning failure inside loop instead of after
  • Not checking all elements before return
  • Misplacing else return inside loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Quizzes