Go while Loop
A while
loop is a control flow statement that allows code to be executed repeatedly until a condition is met. In Go, you use a for
loop with a condition as it does not have a while
.
While loops
Sometimes you do not know in advance how many times you want to repeat a block of code, just that a condition must be met before the loop stops.
In this case, in most programming languages, you use a while
loop.
For example, in C, you would write:
while (condition) {
// do something
}
But in Go, you use a for
loop with a condition instead:
for condition {
// do something
}
It can be slightly confusing at first, but you will get familiar with it quickly.
Approximating the square root of a number
A good usage of a while
loop is to wait for a given precision to be reached in a calculation.
Here let's say that we want to approximate the square root of a number.
package main
import (
"fmt"
"math"
)
func main() {
var number float64
fmt.Print("Enter a number: ")
fmt.Scan(&number)
approximation := number / 2
for math.Abs(approximation*approximation - number) > 0.001 {
approximation = (approximation + number/approximation) / 2
}
fmt.Printf("The square root of %f is %f\n", number, approximation)
}
Some things to note:
- We use
math.Abs
to get the absolute value of a number, it should remind you of thefmt.Println
function we used in the previous tutorials, the only difference is that the former has a return value (more on that in the tutorial on functions), - the condition of the
for
loop ismath.Abs(approximation*approximation - number) > 0.001
, it reads: "the precision is not good enough yet", - the formula to find a better approximation is
approximation = (approximation + number/approximation) / 2
, it is called the Babylonian method.
And sure enough,
$ go run square-root.go
Enter a number: 3
The square root of 3.000000 is 1.732143
And sure enough, 1.732143 squared is around 3.0003, which is close enough to 3.
Waiting for valid input
Another good usage of a while
loop is to wait for the user to enter valid input.
For example, let's say that we want to ask the user to enter a number between 1 and 10.
package main
import "fmt"
func main() {
var number int = 0
for number < 1 || number > 10 {
fmt.Print("Enter a number between 1 and 10: ")
fmt.Scan(&number)
}
fmt.Printf("You entered %d\n", number)
}
The number
variable is initialized to 0
so that the loop is executed at least once.