Go For Loops

In Go, the for loop is the only looping construct provided by the language. It’s versatile and efficient for executing a block of code multiple times, often with a unique value in each iteration. Each cycle through the loop is referred to as an iteration.

Tutorials dojo strip



Syntax of a for Loop

The for loop in Go can include up to three statements:

Go
  • Initialization: This sets up the loop control variable.
  • Condition: This evaluates before each iteration. If TRUE, the loop continues; if FALSE, the loop ends.
  • Increment: This modifies the loop control variable after each iteration.

Note: These statements don’t need to be included within the loop header but must exist elsewhere in the code.




Example 1: Counting from 0 to 4

Go

Output:

Go

Explanation:

  1. Initialization: bikes := 0 sets the starting value to 0.
  2. Condition: bikes < 5 ensures the loop runs as long as bikes is less than 5.
  3. Increment: bikes++ increases the value of bikes by 1 in each iteration.




Example 2: Counting in Tens

Go

Output:

Go

Explanation:

  1. Initialization: motorcycles := 0 starts at 0.
  2. Condition: motorcycles <= 100 keeps the loop running while motorcycles is less than or equal to 100.
  3. Increment: motorcycles += 10 increases the value by 10 with each cycle.




Continue Statement

The continue statement skips the remainder of the current loop iteration and proceeds to the next iteration.

Example: Skipping a specific value (e.g., 3):

Go

Output:

Go




Break Statement

The break statement halts the loop’s execution entirely.

Example: Terminating the loop when a condition is met:

Go

Output:

Go




Nested Loops

Loops can be nested, meaning one loop is placed inside another. The inner loop runs completely during each iteration of the outer loop.

Example: Combining two lists, such as adjectives and motorcycle brands:

Go

Output:

Go




Using the range Keyword

The range keyword provides a convenient way to iterate over elements in arrays, slices, or maps. It returns both the index and the value.

Syntax:

Go

Example: Iterating through motorcycle brands:

Go

Output:

Go




Additional Tips for range

  • To ignore the index: for _, val := range brands { fmt.Println(val) } Output: Suzuki Honda Ducati
  • To ignore the value: for idx, _ := range brands { fmt.Println(idx) } Output: 0 1 2
Tutorials dojo strip