Which Swift code correctly uses if-else statements to print "Positive", "Negative", or "Zero" based on the value of an integer variable value?
hard📝 Application Q8 of 15
Swift - Control Flow
Which Swift code correctly uses if-else statements to print "Positive", "Negative", or "Zero" based on the value of an integer variable value?
Aif value == 0 {
print("Zero")
} else if value > 0 {
print("Positive")
} else {
print("Negative")
}
Bif value >= 0 {
print("Positive")
} else if value <= 0 {
print("Negative")
} else {
print("Zero")
}
Cif value > 0 {
print("Positive")
} else if value > 0 {
print("Negative")
} else {
print("Zero")
}
Dif value > 0 {
print("Positive")
} else if value < 0 {
print("Negative")
} else {
print("Zero")
}
Step-by-Step Solution
Solution:
Step 1: Understand conditions
Check if value is greater than 0, less than 0, or zero.
Step 2: Analyze options
if value > 0 {
print("Positive")
} else if value < 0 {
print("Negative")
} else {
print("Zero")
} correctly checks >0, <0, else zero.
Step 3: Identify errors in other options
if value >= 0 {
print("Positive")
} else if value <= 0 {
print("Negative")
} else {
print("Zero")
} uses overlapping conditions; C repeats same condition; D order is incorrect for logic.
Final Answer:
if value > 0 {
print("Positive")
} else if value < 0 {
print("Negative")
} else {
print("Zero")
} correctly implements the logic.
Quick Check:
Conditions cover all cases without overlap [OK]
Quick Trick:Check conditions cover all cases without overlap [OK]
Common Mistakes:
Overlapping or repeated conditions
Incorrect order of if-else blocks
Missing else block for zero case
Master "Control Flow" in Swift
9 interactive learning modes - each teaches the same concept differently