The for Construct

This lesson discusses the for construct in detail.

Introduction

So far, we have studied two types of constructs; the if-else and the switch construct. Another very important and widely used control structure in programming is the for construct.

In Go, the for statement exists to repeat a body of statements a number of times. One pass through the body is called an iteration.

Remark: There is no for match for the do-while statement found in most other languages. It was probably excluded because the use case for it was not that important.

Types of for loops

There are two methods to control iteration:

  • Counter-controlled iteration
  • Condition-controlled iteration

Let’s study them one by one.

Counter-controlled iteration

The simplest form is the counter-controlled iteration. The general format is:

for initialization; condition; modification { }

For example:

for i := 0; i < 10; i++ {}

The body { } of the for-loop is repeated a known number of times; this is counted by a variable i. The loop starts with an initialization for i as: i := 0 ( this is performed only once). This is shorter than a declaration beforehand, and it is followed by a conditional check on i: i < 10, which is performed before every iteration. When the condition is true, the iteration is done. Otherwise, the for-loop stops when the condition becomes false. Then comes a modification of i: i++, which is performed after every iteration, at which point the condition is checked again to see if the loop can continue. This modification could, for example, also be a decrement, or + or –, using a step. The following is a figure that explains the for construct.

Get hands-on with 1400+ tech skills courses.