Algorithm
Initialize Loop Variable:
- Declare and initialize the loop variable before entering the loop.
go
i := 0
-
While Loop Condition:
- Use a
for
loop with a condition to create the equivalent of awhile
loop.
go
for i < 5 { // Loop body }
- Use a
-
Loop Body:
- Define the statements that should be executed as long as the loop condition is true.
go
fmt.Println(i)
-
Update Loop Variable:
- Modify the loop variable within the loop body to eventually meet the exit condition.
go
i++
-
End of Loop:
- The loop will continue executing as long as the condition is true. Once the condition becomes false, the control exits the loop.
Flowchart of while loop in Go ::
+---------------------+
| Start of Program |
+---------------------+
|
v
+---------------------+
| Initialize |
| Loop Variable |
+---------------------+
|
v
+---------------------+
| +-------<-----+
| |
| v
| +-----------------+
| | Condition |
| | Check |
| +-----------------+
| |
| v
| +-----------------+
| | Loop Body |
| | Executed |
| +-----------------+
| |
| v
| +-----------------+
| | Update |
| | Loop Variable |
| +-----------------+
| |
| v
| +-----------------+
| | Back to |
| | Condition |
| +-----------------+
| |
| |
| v
| +---<-------------+
| |
+---+
|
v
+---------------------+
| End of Program |
+---------------------+
Code Examples
#1 Go while loop
Code -
Golang Programming
// Program to print numbers between 1 and 5
package main
import ("fmt")
func main() {
number := 1
for number <= 5 {
fmt.Println(number)
number++
}
}
Copy The Code &
Try With Live Editor
Output
2
3
4
5
#2 Create multiplication table using while loop
Code -
Golang Programming
// Program to create a multiplication table of 5 using while loop
package main
import ("fmt")
func main() {
multiplier := 1
// run while loop for 10 times
for multiplier <= 10 {
// find the product
product := 5 * multiplier
// print the multiplication table in format 5 * 1 = 5
fmt.Printf("5 * %d = %d\n", multiplier, product)
multiplier++
}
}
Copy The Code &
Try With Live Editor
Output
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
#3 Go do...while Loop
Code -
Golang Programming
// Program to print number from 1 to 5
package main
import "fmt"
func main(){
number := 1
// loop that runs infinitely
for {
// condition to terminate the loop
if number > 5 {
break;
}
fmt.Printf("%d\n", number);
number ++
}
}
Copy The Code &
Try With Live Editor
Output
2
3
4
5
Demonstration
Go Lang Programming while Loop