W3Basic Logo

Go for Loop

In Programming, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly.

In this tutorial, we are going to print the multiplication table of a number given by the user. You can already do this without the use of a loop, but it is a lot of work.

package main

import "fmt"

func main() {
	var number int
	fmt.Print("Enter a number: ")
	fmt.Scan(&number)

	fmt.Printf("%d * 1 = %d\n", number, number*1)
	fmt.Printf("%d * 2 = %d\n", number, number*2)
	fmt.Printf("%d * 3 = %d\n", number, number*3)
	fmt.Printf("%d * 4 = %d\n", number, number*4)
	fmt.Printf("%d * 5 = %d\n", number, number*5)
	fmt.Printf("%d * 6 = %d\n", number, number*6)
	fmt.Printf("%d * 7 = %d\n", number, number*7)
	fmt.Printf("%d * 8 = %d\n", number, number*8)
	fmt.Printf("%d * 9 = %d\n", number, number*9)

Here a lot of code is repeated, and we designed computers specifically to avoid repeating tasks, so there must be a better way.


The for loop

The for loop is a way to repeat a block of code a certain number of times while keeping track of the index of the current iteration.

for i := 0; i < 10; i++ {
	// do something
}

It reads: "starting with i equal to 0, repeat the block of code until i is equal to 10, and increment i by 1 each time".

Note: i++, i += 1 and i = i + 1 are all equivalent ways to increment i by 1.

Our multiplication table program can be rewritten as follows:

package main

import "fmt"

func main() {
	var number int
	fmt.Print("Enter a number: ")
	fmt.Scan(&number)

	for i := 1; i <= 9; i++ {
		fmt.Printf("%d * %d = %d\n", number, i, number*i)
	}
}

Way cleaner, isn't it?

Output

Enter a number: 4
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36

More advanced examples on for loop

While the previous example covers 90% of the use cases of the for loop, there are a few more examples worth mentioning.

Iterating backwards

for i := 10; i > 0; i-- {
	// do something
}

i-- is similar to i++, but it decrements i by 1 instead of incrementing it.

Iterating over even numbers

for i := 0; i < 10; i += 2 {
	// do something
}

Infinite loops

Sometimes you want a program to run forever, for example, a web server. An infinite loop is a right tool for the job. You could write it like this:

for i := 0; i < 1, i = 0 {
	// do something
}

But there is a better way:

for {
	// do something
}

© 2023 W3Basic. All rights reserved.

Follow Us: