Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
For Loop | Control Structures
Introduction to GoLang
course content

Course Content

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

book
For Loop

In programming, a loop enables us to execute a block of code repeatedly, either a fixed number of times or until a condition is met. In Go, the basic syntax of a loop is as follows:

In the initialization section, we create and initialize a new integer variable. In the condition section, we use a boolean expression that is checked during each iteration, and the loop continues to execute the code inside it as long as the condition is true. In the post section, we include a statement to be executed after every iteration.

Note

An iteration in a loop refers to each individual execution of the loop's code block. It represents a single cycle or repetition of the loop.

Here's an example of a for loop to help you better understand the concept:

go

index

copy
12345678
package main import "fmt" func main() { for i := 1; i < 10; i++ { fmt.Println(i) } }

We initialized a variable i with a value of 1. In the condition, we specified i < 10, which is initially true; hence, the loop runs. After each iteration, the loop executes i++, incrementing the value of i. After nine iterations, the condition i < 10 becomes false, and the loop stops running. Here's a diagram that illustrates the loop's execution:

Using this type of loop, we can specify a fixed number of times a code will be executed. However, if we want to execute a block of code until a condition is met, we can use the following syntax:

This type of loop is commonly referred to as a "while loop" in other programming languages, as it's typically created using the while keyword. However, in Go, there is a single keyword for for creating both types of loops.

Here's a practical example of how it can be used:

go

index

copy
12345678910
package main import "fmt" func main() { var value float64 = 100 for value > 0.5 { value = value / 2 fmt.Println(value) } }

The program above divides a number by 2 repeatedly until it becomes less than 0.5. Here's a diagram to help you better understand the execution of this loop:

What will be the last line in the output of the following loop?

What will be the last line in the output of the following loop?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 6
We're sorry to hear that something went wrong. What happened?
some-alt