0
0
Swiftprogramming~20 mins

While loop in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple while loop
What is the output of the following Swift code?
Swift
var count = 3
while count > 0 {
    print(count)
    count -= 1
}
A
3
2
1
B
1
2
3
C
0
1
2
3
D
3
2
1
0
Attempts:
2 left
💡 Hint
Remember the loop runs while count is greater than zero and decreases count each time.
Predict Output
intermediate
2:00remaining
While loop with break statement
What will be printed by this Swift code?
Swift
var i = 1
while i <= 5 {
    if i == 3 {
        break
    }
    print(i)
    i += 1
}
A
1
2
B
1
2
3
C
1
2
3
4
5
D
3
4
5
Attempts:
2 left
💡 Hint
The break statement stops the loop immediately when i equals 3.
Predict Output
advanced
2:00remaining
While loop with continue statement
What is the output of this Swift code snippet?
Swift
var n = 0
while n < 5 {
    n += 1
    if n == 3 {
        continue
    }
    print(n)
}
A
1
2
3
4
B
1
2
3
4
5
C
2
3
4
5
D
1
2
4
5
Attempts:
2 left
💡 Hint
The continue skips printing when n equals 3.
🧠 Conceptual
advanced
1:30remaining
Understanding while loop condition
What happens if the condition in a Swift while loop is initially false?
AThe loop body runs once before checking the condition.
BThe loop body never runs.
CThe loop runs infinitely.
DThe loop runs twice.
Attempts:
2 left
💡 Hint
Think about when the condition is checked in a while loop.
Predict Output
expert
2:30remaining
Counting iterations in a while loop
What is the value of variable 'count' after running this Swift code?
Swift
var count = 0
var x = 10
while x > 0 {
    if x % 3 == 0 {
        x -= 2
    } else {
        x -= 1
    }
    count += 1
}
A9
B8
C7
D10
Attempts:
2 left
💡 Hint
Track how x changes each loop and count how many times the loop runs.