Bird
0
0

You want to write a C function that returns the index of the first prime number in an array, or -1 if none found. Which code snippet correctly uses return inside a loop to achieve this?

hard📝 Application Q15 of 15
C - Loop Control Statements
You want to write a C function that returns the index of the first prime number in an array, or -1 if none found. Which code snippet correctly uses return inside a loop to achieve this?
Afor(int i=0; i<n; i++) { if(isPrime(arr[i])) return i; } return -1;
Bfor(int i=0; i<n; i++) { if(isPrime(arr[i])) break; return i; } return -1;
Cfor(int i=0; i<n; i++) { if(isPrime(arr[i])) return -1; } return i;
Dfor(int i=0; i<n; i++) { if(isPrime(arr[i])) continue; return i; } return -1;
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want to return the index of the first prime number found, or -1 if none.
  2. Step 2: Analyze each option's logic

    for(int i=0; i
  3. Final Answer:

    for(int i=0; i -> Option A
  4. Quick Check:

    Return index on first prime, else -1 after loop [OK]
Quick Trick: Return inside loop on condition, return default after loop [OK]
Common Mistakes:
  • Returning wrong value inside loop
  • Using break without return
  • Returning default inside loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Quizzes