A while loop allows your program to perform a set of instructions as long as a condition is satisfied.
Here is the structure of a while loop:
while(condition) {
instruction1
instruction2
...
}
Let's check an example:
var count = 1
while(count <= 5) {
println("I made a mistake")
count++
}
println("Finished!")
The output of this program is:
I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!
And this is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable count = 1
1. First iteration:
a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes.
b. println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 2
2. Second iteration:
a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes.
b. println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 3
3. Third iteration:
a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes.
b. println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 4
4. Forth iteration:
a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes.
b. println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 5
5. Fifth iteration:
a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes.
b. println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 6
6. Sixth iteration:
a. Is count <= 5 true? <=> Is 6 <= 5 true? No.
b. Terminate the loop.
7. println("Finished!"); => Output: Finished!
Pro Tip:
A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.
Assignment
Let's print "I promise to learn coding" 5 times using a loop.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.