We can achieve many different outcomes with while loops.
For example, we can print print all the numbers from 0 through 4:
var i = 0
while(i < 5) {
println(i)
i++
}
The output of this program is:
0
1
2
3
4
And this is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable i = 0
1. First iteration:
a. Is i < 5 true? <=> Is 0 < 5 true? Yes.
b. println(i); => Output: 0
c. i++; => i = 1
1. Second iteration:
a. Is i < 5 true? <=> Is 1 < 5 true? Yes.
b. println(i); => Output: 1
c. i++; => i = 2
2. Third iteration:
a. Is i < 5 true? <=> Is 2 < 5 true? Yes.
b. println(i); => Output: 2
c. i++; => i = 3
3. Forth iteration:
a. Is i < 5 true? <=> Is 3 < 5 true? Yes.
b. println(i); => Output: 3
c. i++; => i = 4
4. Fifth iteration:
a. Is i < 5 true? <=> Is 4 < 5 true? Yes.
b. println(i); => Output: 4
c. i++; => i = 5
5. Sixth iteration:
a. Is i < 5 true? <=> Is 5 < 5 true? No.
b. Exit the loop.
Assignment
Let's print all numbers from 3 to 10 using a while loop.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check