Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Iterating Over Arrays | Section
/
Getting Started with Go

bookIterating 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.go

index.go

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:

index.go

index.go

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) }
question mark

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

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  39

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  39
some-alt