Conteúdo do Curso
Introduction to GoLang
Introduction to GoLang
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:
index
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:
index
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:
Obrigado pelo seu feedback!