Chapter 4
Over and Over and Over: Using Loops
IN THIS CHAPTER
Looping using the for statement
Repeating a group of instructions through a range of values
The greatest thing about computers is that, unlike you and me, they can perform tasks repeatedly without getting tired. To support this feature, programming languages use constructs known as loops to enable programmers to execute blocks of code repeatedly.
Although programming languages like C and Java have multiple types of looping — while, do…while, and for — Go has only one looping construct: the for loop. But don't let the simplicity fool you: The for loop is powerful enough to meet all your programming needs.
Performing Loops Using the for Statement
In Go, this is what a for statement looks like:
for (init; condition; post) {}
This loop has the following three components:
- An
initstatement: This statement is executed before the first iteration starts. (Each time theforstatement executes the statements contained within it is called an iteration.) - A
conditionexpression: This expression is evaluated before the iteration starts to determine if the iteration should continue. - A
poststatement: This statement is evaluated at the end of each iteration.
The best way to understand a for loop is with an example:
package main ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access