Bird
0
0

Examine the following nested if code snippet. What is the logical error?

medium📝 Debug Q7 of 15
C - onditional Statements

Examine the following nested if code snippet. What is the logical error?

int num = 7;
if (num > 0) {
  if (num % 2 == 0)
    printf("Even\n");
  else
    printf("Odd\n");
} else
  printf("Non-positive\n");
AThe else statement is incorrectly paired with the outer if instead of the inner if.
BThere is no error; the code correctly distinguishes even and odd positive numbers.
CThe code does not handle zero correctly as a positive number.
DThe modulus operator (%) cannot be used inside nested if statements.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the code logic

    The outer if checks if num is positive. The inner if checks if num is even or odd.
  2. Step 2: Check else pairing

    The else after the inner if correctly pairs with the inner if to print "Odd" if num is not even.
  3. Step 3: Consider zero handling

    Zero is not greater than zero, so it goes to the outer else and prints "Non-positive" which is correct.
  4. Final Answer:

    The code correctly distinguishes even and odd positive numbers without logical errors. -> Option B
  5. Quick Check:

    Inner else pairs with inner if; outer else handles non-positive. [OK]
Quick Trick: Check else pairs with correct if block [OK]
Common Mistakes:
  • Assuming else pairs with outer if incorrectly
  • Not considering zero as non-positive
  • Believing modulus operator is invalid in nested if

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Quizzes