Bird
0
0

You want to write Swift code that prints "Positive", "Negative", or "Zero" depending on the value of an integer variable num. Which code correctly uses if-else statements to do this?

hard📝 Application Q15 of 15
Swift - Control Flow
You want to write Swift code that prints "Positive", "Negative", or "Zero" depending on the value of an integer variable num. Which code correctly uses if-else statements to do this?
Aif num >= 0 { print("Positive") } else if num <= 0 { print("Negative") } else { print("Zero") }
Bif num > 0 { print("Positive") } else if num < 0 { print("Negative") } else { print("Zero") }
Cif num > 0 { print("Positive") } else { print("Negative") } print("Zero")
Dif num == 0 { print("Zero") } else if num > 0 { print("Negative") } else if num < 0 { print("Positive") }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the conditions needed

    We need to check if num is greater than 0, less than 0, or exactly 0.
  2. Step 2: Analyze each option

    if num > 0 { print("Positive") } else if num < 0 { print("Negative") } else { print("Zero") } correctly checks >0, then <0, else zero. if num >= 0 { print("Positive") } else if num <= 0 { print("Negative") } else { print("Zero") } wrongly overlaps conditions. if num > 0 { print("Positive") } else { print("Negative") } print("Zero") prints "Zero" always. if num == 0 { print("Zero") } else if num > 0 { print("Negative") } else if num < 0 { print("Positive") } incorrectly prints "Negative" for positive numbers and "Positive" for negative numbers.
  3. Final Answer:

    if num > 0 { print("Positive") } else if num < 0 { print("Negative") } else { print("Zero") } -> Option B
  4. Quick Check:

    Check >0, else if <0, else zero [OK]
Quick Trick: Check positive first, then negative, else zero last [OK]
Common Mistakes:
  • Overlapping conditions causing wrong output
  • Printing zero outside else block
  • Wrong order of conditions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes