Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Iterating Over Arrays | Arrays and Slices
Introduction to GoLang
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
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:

go

index

copy
12345678910
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:

go

index

copy
1234567891011121314151617
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) }
What is the correct way of using a for loop to loop through an array called `myArr` ?

What is the correct way of using a for loop to loop through an array called myArr ?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 6
We're sorry to hear that something went wrong. What happened?
some-alt