0
0
Swiftprogramming~10 mins

While loop in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a while loop that runs as long as count is less than 5.

Swift
var count = 0
while count [1] 5 {
    print(count)
    count += 1
}
Drag options to blanks, or click blank then click option'
A<
B>
C==
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < will cause the loop to never run.
Using == will only run if count starts exactly at 5.
2fill in blank
medium

Complete the code to stop the loop when number reaches 10.

Swift
var number = 0
while number [1] 10 {
    print(number)
    number += 2
}
Drag options to blanks, or click blank then click option'
A<=
B<
C>
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= will include 10, which might cause unexpected behavior.
Using > or == will not run the loop as expected.
3fill in blank
hard

Fix the error in the while loop condition to avoid an infinite loop.

Swift
var x = 5
while x [1] 0 {
    print(x)
    x -= 1
}
Drag options to blanks, or click blank then click option'
A>
B<
C>=
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < or <= will cause the loop to never run or run infinitely.
Using >= will cause the loop to run one extra time including zero.
4fill in blank
hard

Fill both blanks to create a while loop that prints numbers from 1 to 5.

Swift
var num = 1
while num [1] 5 {
    print(num)
    num [2] num + 1
}
Drag options to blanks, or click blank then click option'
A<=
B<
C+=
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < will miss printing 5.
Using += results in num += num + 1, which is incorrect.
5fill in blank
hard

Fill all three blanks to create a while loop that prints even numbers from 2 to 10.

Swift
var val = [1]
while val [2] 10 {
    print(val)
    val [3] val + 2
}
Drag options to blanks, or click blank then click option'
A2
B<=
C=
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Starting val at 0 will print zero, which is not an even number in this context.
Using < will miss printing 10.
Using += results in val += val + 2, which is incorrect.