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
init
statement: This statement is executed before the first iteration starts. (Each time thefor
statement executes the statements contained within it is called an iteration.) - A
condition
expression: This expression is evaluated before the iteration starts to determine if the iteration should continue. - A
post
statement: This statement is evaluated at the end of each iteration.
The best way to understand a for
loop is with an example:
package main ...
Get Go Programming Language For Dummies now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.