Back to: Golang
Go does not have a particular “while” keyword for a loop. But we can use a while loop like a concept using the “for” keyword in the Go programming language.
The Go programming language provides a while loop construct that allows you to repeatedly execute a block of code as long as a certain condition is true. The syntax for the while loop is:
for condition {
// code to execute
}
Here, the condition
is a boolean expression that determines whether the loop should continue executing. The loop will execute the code block repeatedly as long as the condition is true.
Let’s take an example where we use a while loop to print numbers from 1 to 5:
i := 1
for i <= 5 {
fmt.Println(i)
i++
}
In this example, we initialize the variable i
to 1 and then use a while loop to print the value of i
and increment it by 1 on each iteration until it reaches 6. The output of the above code will be:
1
2
3
4
5
Another example can be to use a while loop to search for a specific value in a slice:
arr := []int{1, 2, 3, 4, 5}
key := 3
i := 0
for i < len(arr) {
if arr[i] == key {
fmt.Println("Found key at index:", i)
break
}
i++
}
Here, we use a while loop to iterate over the slice arr
until we find the value of key
and print its index. If the value is not found, the loop will continue until it reaches the end of the slice. The output of the above code will be:
Found key at index: 2
Here is an example of a Go while loop with complete code and output:
package main
import "fmt"
func main() {
i := 1
for i <= 5 {
fmt.Println("The value of i is", i)
i++
}
}
Output:
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
In this example, we are using a Go while loop to print the value of variable i
from 1 to 5.
In our example, the condition is i <= 5
, which checks if the value of i
is less than or equal to 5. If the condition is true, the code inside the for loop will be executed.
Inside the while loop, we are using the fmt.Println()
function to print the value of i
using string concatenation. The variable i
is initialized outside the loop, and then incremented by 1 after each iteration using i++
.
The output of the program shows the values of i
from 1 to 5. The while loop is used when we don’t know the number of iterations beforehand, and the loop is terminated when a certain condition is met.
Follow us on social media
Follow Author