Go - for Loop Example

1. Introduction

The for loop is one of the most fundamental control structures in Go, as it is in many programming languages. It allows you to repeatedly execute a block of code with well-defined iteration statements. This blog post will discuss how to use the for loop in Go with a simple example.

Definition

In Go, the for loop is used to iterate over a block of code multiple times. It can be used similarly to the for loop of languages like C, but it can also simulate the while loop since Go doesn't have a while keyword.

2. Program Steps

1. Define a for loop with an initializer, condition, and post statement.

2. Iterate over a slice and print each element.

3. Use a for loop without initialization and post statements to act like a while loop.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Standard for loop with an initializer, condition, and post statement.
	fmt.Println("Counting up:")
	for i := 0; i < 5; i++ {
		fmt.Println(i)
	}

	// Step 2: Iterate over a slice with a for loop.
	fmt.Println("\nIterating over a slice:")
	fruits := []string{"apple", "banana", "cherry"}
	for index, fruit := range fruits {
		fmt.Printf("Index: %d, Fruit: %s\n", index, fruit)
	}

	// Step 3: For loop as a 'while' loop.
	fmt.Println("\nCounting down:")
	counter := 5
	for counter > 0 {
		fmt.Println(counter)
		counter--
	}
}

Output:

Counting up:
0
1
2
3
4
Iterating over a slice:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Counting down:
5
4
3
2
1

Explanation:

1. package main indicates the entry point of an executable program in Go.

2. import "fmt" is for importing the format package, which is used for formatted I/O.

3. The first for loop initializes a counter i to 0, continues looping while i is less than 5, and increments i by 1 after each loop iteration.

4. The fmt.Println(i) statement within the loop prints the value of i to the console.

5. The for loop with the range keyword iterates over the fruits slice. The loop uses two variables, index and fruit, to capture the index and the value of the slice element, respectively.

6. The fmt.Printf function prints the current index and fruit during each iteration of the loop.

7. The final for loop uses only a condition, effectively acting as a while loop, decrementing counter until it is no longer greater than 0.

8. The output consists of three parts: the count-up from 0 to 4, the iteration over the fruits slice printing each index and fruit, and the count-down from 5 to 1.


Comments