The for Loop

The single for loop and its three forms; accumulating a result.

Go has only one loop — for, but it comes in three forms: • classic: for i := 1; i <= n; i++ { ... } • while-like: for condition { ... } • infinite: for { ... } (exit with break) There is no separate while in the language — the second form plays its role.
Go

A counter from 1 to 5

The accumulation technique: create an accumulator variable and update it on every step. Below — reading n numbers and their sum.
Go

Enter: 4, then 10 20 30 40

Go

The while form: how many times is the number divisible by 2? Enter: 96

Task: print all even numbers from 2 to 20 on one line (hint: fmt.Print(x, " ") prints without a newline). Then solve the attached problems "Factorial" and "Sum of Array Elements" — and mark the lesson as completed.

Practice problems

Доска