for loop
- Go course
- Beginner
- Lesson 36/90
- 4 min
Learn for, Go's only loop construct.
The for loop
Go's only loop keyword is for; it has three forms:
for i := 0; i < 3; i++ { // classic
fmt.Println(i)
}
n := 1
for n < 100 { // like while
n *= 2
}
for { // infinite loop
break
}There is no while or do-while; everything is written with for.
The loop variable
In the classic form, i := 0 is the start, i < 3 the condition and i++ the step after each iteration. The loop variable exists only inside the loop. Since Go 1.22 every iteration gets its own copy of i, so goroutines and closures started inside the loop can safely use i.
Practice Factorial
Write the faktoriyel(n int) int function with a for loop. Print the result of faktoriyel(5).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func faktoriyel(n int) int {
sonuc := 1
for i := 2; i <= n; i++ {
sonuc *= i
}
return sonuc
}
func main() {
fmt.Println(faktoriyel(5))
}Expected output
120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 After <code>n := 1; for n < 100 { n *= 2 }</code>, what is n?
- 128 Correct answer
- 64
- 100
- 99
Explanation: n goes 1, 2, 4, ..., 64; since 64 < 100 it doubles once more and the loop stops at 128.
2 Condition
for i := 1; i ____ 5; i++ {
fmt.Print(i, " ")
} // 1 2 3 4 5
for i := 1; i <= 5; i++ {
fmt.Print(i, " ")
} // 1 2 3 4 5
Explanation: The condition i <= 5 includes 5 in the loop.
3 Loop form
| Term | Meaning |
|---|---|
for i := 0; i < n; i++ |
Counter-based |
for kosul |
Like while |
for {} |
Infinite |
for i, v := range s |
Iterating a collection |