Chapter 4. Control Structures
Now that you know how to use variables, it’s time to start writing some useful programs. First, let’s write a program that counts to 10, starting from 1, with each number on its own line. Using what you’ve learned so far, you could write this:
packagemainimport"fmt"funcmain(){fmt.Println(1)fmt.Println(2)fmt.Println(3)fmt.Println(4)fmt.Println(5)fmt.Println(6)fmt.Println(7)fmt.Println(8)fmt.Println(9)fmt.Println(10)}
Or this:
packagemainimport"fmt"funcmain(){fmt.Println(`12345678910`)}
But both of these programs are pretty tedious to write. What we need is a way of doing something multiple times.
The for Statement
The for statement allows us to repeat a list of statements (a block) multiple times. Rewriting our previous program using a for statement looks like this:
packagemainimport"fmt"funcmain(){i:=1fori<=10{fmt.Println(i)i=i+1}}
First, we create a variable called i that we use to store the number we want to print. Then we create a for loop by using the keyword for, providing a conditional expression that is either true or false and finally supplying a block to execute. The for loop works like this:
-
We evaluate (run) the expression
i <= 10(“i less than or equal to 10”). If this evaluates to true, then we run the statements inside of the block. Otherwise, we jump to the next line of our program after the block (in this case, there is nothing after theforloop, so we exit the program).
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