1. Why loops are needed and why Go has only one
If you have ever tried to “just repeat an action 10 times” manually, you know how it usually ends: ten identical lines, and on the eleventh one you made a mistake in the variable name. Loops are a way to tell the computer: “do this block of code several times, and let’s agree on when to stop.”
From the standpoint of common sense, a loop is a control structure that repeats a body (the block { ... }) while some rule is being satisfied. In Go, this is especially nice: there is only one loop — for. Yes, no while as a separate keyword. Go is basically saying: “Why do you need two words if one is enough?”.
for in Go: one construct for different tasks
It is important not to be scared by the phrase “the only loop”. This does not mean that Go is “poor” — it means that for supports several forms of writing. But today we will take the most classic and the most useful one for a beginner: the counter loop.
In real life, this looks like “do it 5 times”, “go from 1 to N”, “print numbers from 0 to 9”, “read N values”. Almost all such tasks can be conveniently expressed with the classic for, where there is a start, a condition, and a step.
2. The classic for: init; cond; post
General loop form
This form is like a classic sandwich: three layers with clear roles. It looks like this:
for init; cond; post {
// loop body
}
In Go, you will see this form constantly — even in examples from official materials, for example in the article about defer, where values are printed later inside a loop. There, the familiar counter i := 0; i < 4; i++ is used, that is, exactly the construct we are analyzing now.
Now let us break it down in detail (no nerves, it is all logical).
init: preparation before the start
In the init section, the counter is usually created and initialized. And this is done once — before the first condition check.
Most often you write i := 0 or i := 1. Why sometimes zero, and sometimes one — that is a matter of convenience and how you count mentally. The computer does not care; the human does. If you number “attempts 1..N”, you usually start from 1. If you work with indexes (which we will see later in arrays/slices), you often start from 0.
Mini-example: declare the counter and prepare to print.
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Iteration", i) // Iteration 0 / 1 / 2
}
}
Notice a detail: i is declared with := right inside for. This is normal and very typical: the counter lives inside the loop and is almost never needed outside.
cond: stop condition
cond (condition) is a bool-type expression that is checked before each iteration. If the condition is true — the loop body runs. If it is false — the loop ends, and the program continues after the loop.
It is important to feel a simple idea: the condition is a “guard at the entrance”. It does not let you into the next iteration if the rule is no longer satisfied.
Example for “print numbers 1..5” (inclusive):
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println(i) // 1 2 3 4 5
}
}
Here the condition i <= 5 means: “as long as i is not greater than 5 — keep working”.
Loop body: what exactly we repeat
The loop body is an ordinary code block in curly braces. You have already seen such blocks in if/else and switch. In a loop, the block runs many times — and that is the only difference.
A good habit: keep the code inside the loop body as simple as possible. If there is too much stuff inside the loop, it becomes hard to understand how many times and exactly what is happening. While we are beginners — we write small understandable pieces, and leave the “big messy blocks” to people who enjoy suffering.
The simplest example of a body: print something several times.
package main
import "fmt"
func main() {
for i := 0; i < 2; i++ {
fmt.Println("Go is fine") // Go is fine (2 times)
}
}
post: the step between iterations
post is executed after the body on each iteration. This is the place where you usually change the counter: increase or decrease it so that the loop eventually ends.
If you forget to change the counter (or change the wrong one), the loop can become infinite. But no need to panic yet: this is a typical beginner mistake, and we will learn to spot it with our eyes.
Mini-example: step by 2.
package main
import "fmt"
func main() {
for i := 0; i < 6; i = i + 2 {
fmt.Println(i) // 0 2 4
}
}
Here post is i = i + 2. It runs after each fmt.Println.
i++ and i--: short notation for “plus one” and “minus one”
In Go, counters have two very recognizable symbols from the world of “classic loops”: i++ and i--. These are short forms for “increase by 1” and “decrease by 1”.
An important point when reading code: when you see i++, it almost always means “a regular counter, a regular iteration”.
Example with decreasing:
package main
import "fmt"
func main() {
for i := 3; i > 0; i-- {
fmt.Println(i) // 3 2 1
}
}
Here the condition i > 0 and the step i-- are consistent: we are going down to zero, and the loop will definitely stop.
Execution order: init → cond → body → post
Until you learn to run the loop in your head, any for will feel like magic. The good news: there is no magic — there is a strict order.
First init runs (exactly once). Then cond is checked. If cond == true, the body runs. Then post runs. After that, the loop returns to checking cond. And so on, in a circle, until the condition becomes false.
Here is a diagram that is useful to remember (like a “metro map”):
flowchart TD
A[init: once] --> B{cond?}
B -- true --> C[body: body]
C --> D[post: step]
D --> B
B -- false --> E[after loop]
If you do not like diagrams, you can keep it as a table:
| Element | When it runs | Typical content |
|---|---|---|
|
once, at the start | |
|
before each iteration | |
|
if |
useful work |
|
after the body | |
3. Useful habits and important nuances
Habit: understand what values i will take
This is a super-skill for a beginner: being able to answer the question “what values will the counter take”. Not “roughly”, but really concretely. Otherwise, you will constantly end up in a situation like “I expected 5 repetitions, but got 6”.
Let us analyze an example:
for i := 0; i < 5; i++ { ... }
The counter starts at 0. Condition: i < 5. That means i will be: 0, 1, 2, 3, 4. Five will not be included, because when i == 5 the condition is false.
And here:
for i := 1; i <= 5; i++ { ... }
The counter: 1, 2, 3, 4, 5. Here 5 is included because the condition is “less than or equal to”.
This may seem like a small detail, but in practice it is half the success in loops.
Why i is usually declared directly in for
When you write for i := 0; ..., you are basically saying: “the counter is a service thing, let it live only here”. This helps keep main from being cluttered with extra variables that later get used by accident for the wrong purpose.
It also makes the code more “self-documenting”: you open the file, see the loop, and immediately understand where i appeared and how it changes. No “who is i and why is it suddenly 17” (although, of course, life sometimes still throws surprises).
init, cond, post — parts of one mechanism
A very common beginner mistake is to see init, cond, post as three formalities: like, “everyone writes it this way”. In reality, these are three parts of one control mechanism.
init is responsible for the starting state. cond is responsible for the rule “when we continue”. post is responsible for moving the state toward completion. If even one part is chosen badly, the loop will either do the wrong number of iterations or get “stuck” altogether.
A super-simple common-sense check: try to answer two questions. Which variable changes on each iteration? And how does it bring us closer to the moment when cond becomes false? If there is no answer to these questions — the loop is suspicious.
4. Example: TaskBox
To avoid learning for just for the sake of it, let us start building a small application that will grow together with the course. Let us call it TaskBox: for now, it is a very simple CLI that helps the user enter tasks and see them with numbering.
Today we still do not have arrays and slices, so we still cannot “store a list of tasks”. But we can already do something useful: repeat input N times and nicely number what was entered. This already looks like a real application, not just “print hello 10 times”.
Read N and print task numbers
This substep helps you feel “how many times the loop repeats” and what the numbering looks like.
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
for i := 1; i <= n; i++ {
fmt.Println("Task No.", i) // when n=3: Task No. 1 / 2 / 3
}
}
Here i is human numbering. We intentionally chose to start from 1 so that the output looks friendly.
Repeat input N times and print what was entered
Now let us add a “task name”. Reminder: fmt.Scan reads tokens, so for simplicity let the task be a single word (for example, buy_milk). That is perfectly fine for a learning step.
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
for i := 1; i <= n; i++ {
var title string
fmt.Scan(&title)
fmt.Println(i, "-", title) // example: 1 - buy_milk
}
}
This is already a practical pattern: the loop controls the number of repetitions, and inside we perform the same operation (read and print).
5. Another example: a table of squares
Sometimes it is useful to see that a loop is not only about “input/output”, but also about calculations. Here we print a table of squares from 1 to N. No new constructs — only for and multiplication.
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
for i := 1; i <= n; i++ {
fmt.Println(i, "->", i*i) // when n=3: 1->1, 2->4, 3->9
}
}
This exercise (in the sense of “example”) is especially good because you can quickly check the correctness of the result with your eyes. If 16 suddenly appears where 3 should be — then you went off track somewhere with the counter.
6. Typical mistakes when writing a classic for
Mistake No. 1: mixing up < and <= and getting one extra or one missing iteration.
This is not “carelessness” — it is really the most common story. The brain reads i < 5 and thinks “well, up to five”, but the computer reads it literally: “strictly less than five”. The fix is the habit of saying out loud: “the last value of i will be ...”.
Mistake No. 2: wrong counter start (for example, started from 0, but print “attempt No. 0”).
Technically the code is correct, but the user will look at “attempt No. 0” suspiciously, like at a receipt from a store with “-1 item”. For human numbering, you usually choose to start from 1. For indexing (when it appears later), you often choose to start from 0 — but that is exactly “later”, not “everywhere always”.
Mistake No. 3: the step is not consistent with the condition.
If the condition is i < n, but the step is i--, then you will never get closer to i >= n. It is like driving a car toward the finish line, but after each turn moving in the opposite direction. The compiler is not obliged to save you from logic — it only watches the syntax.
Mistake No. 4: trying to “put everything together” into one line of the loop.
Sometimes beginners try to be “cool”: complex initialization, tricky condition, step with multiple variables — and all of this at once. As a result, the loop becomes a mystery even for the author five minutes later. At the start it is better to keep init simple (i := 0), cond clear (i < n) and post obvious (i++). Beauty will come when the brain stops spending energy on basic mechanics.
GO TO FULL VERSION