Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen For Loop | Section
Practice
Projects
Quizzes & Challenges
Quizze
Challenges
/
Getting Started with Go

bookFor Loop

Swipe um das Menü anzuzeigen

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:

for initialization; condition; post {
   // Code to be executed
}

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:

index.go

index.go

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:

for condition {
   // Code to be executed
}

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:

index.go

index.go

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:

question mark

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

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 24

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 24
some-alt