Go for Loop

Go for Loop

Kishore V


Go for Loop

In Go, the for loop is the only looping construct available. It is highly versatile and can be used to implement traditional loops, condition-based loops, and even infinite loops.

Loops are essential when you need to execute a block of code repeatedly. Each repetition is called an iteration.

Basic Syntax of the for Loop

for initialization; condition; post { // code executed in each iteration }

Components Explained

  • Initialization: Sets up the loop variable (executed once at the start).
  • Condition: Evaluated before each iteration. If true, the loop continues; if false, it stops.
  • Post statement: Updates the loop variable after each iteration.

Note: These components are optional, but the loop must still be logically controlled.

Example 1: Printing Numbers

Count: 1 Count: 2 Count: 3 Count: 4 Count: 5

Example 2: Loop with Custom Step

This loop increments by 5 in each iteration.

0 5 10 15 20 25 30 35 40 45 50

Using continue in a Loop

The continue statement skips the current iteration and moves to the next one.

1 2 3 5 6

Using break in a Loop

The break statement immediately terminates the loop.

1 2 3

Nested Loops in Go

A loop can exist inside another loop. The inner loop runs completely for each iteration of the outer loop.

Red Pen Red Book Red Bag Blue Pen Blue Book Blue Bag

The range Keyword in Go

The range keyword simplifies iteration over arrays, slices, and maps. It returns both the index and the value.

Syntax

for index, value := range collection { // code }

Example: Iterating with range

Index: 0, Value: Go Index: 1, Value: Python Index: 2, Value: Java

Ignoring Index or Value

You can use _ (blank identifier) to ignore unwanted values.

Ignore Index:

Go Python Java

Ignore Value:

0 1 2


Our website uses cookies to enhance your experience. Learn More
Accept !