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")
}
Dif num == 0 {
print("Zero")
} else if num > 0 {
print("Negative")
} else if num < 0 {
print("Positive")
}
Step-by-Step Solution
Solution:
Step 1: Understand the conditions needed
We need to check if num is greater than 0, less than 0, or exactly 0.
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.
Final Answer:
if num > 0 {
print("Positive")
} else if num < 0 {
print("Negative")
} else {
print("Zero")
} -> Option B
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
Master "Control Flow" in Swift
9 interactive learning modes - each teaches the same concept differently