A while loop allows your program to perform a set of instructions as long as a condition is satisfied.
Go has no while keyword: a for loop with only a condition does the same job.
Here is the structure of a while loop:
for condition {
instruction1
instruction2
...
}
Let's check an example:
count := 1
for count <= 5 {
fmt.Println("I made a mistake")
count++
}
fmt.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. fmt.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. fmt.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. fmt.Println("I made a mistake") => Output: I made a mistake
c. count++ => count becomes 4
4. Fourth iteration:
a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes.
b. fmt.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. fmt.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. fmt.Println("Finished!") => Output: Finished!
Pro Tip:
A while loop is essentially 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. PRO is unlimited.
