Conteúdo do Curso
Introduction to GoLang
Introduction to GoLang
Iterating Over Arrays
Arrays can potentially contain a large amount of related data, and sometimes, we want to access and modify data in bulk. An easier way to achieve this is by looping through an array to work with its elements collectively.
We can traverse the entire array using a for
loop. The len
function provides us with the length of the array, which we can use in the loop condition to specify the number of iterations:
index
package main import "fmt" func main() { numbers := [] int { 5, 10, 15, 20, 25, 30, 25 } for i := 0; i < len(numbers); i++ { fmt.Printf("Element %d: %d\n", i, numbers[i]) } }
In the code above, we employ a for
loop to iterate len(numbers)
times, where len(numbers)
represents the length of the array. Within the loop, we utilize the variable i
for indexing and accessing the elements.
The following code increments all odd numbers and squares all even numbers in an array:
index
package main import "fmt" func main() { numbers := [] int { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } fmt.Println(numbers) for i := 0; i < len(numbers); i++ { if numbers[i] % 2 == 0 { numbers[i] *= numbers[i] } else { numbers[i]++ } } fmt.Println(numbers) }
Obrigado pelo seu feedback!