Iterating Over Arrays
Part of the Fundamentals section of Coddy's GO journey — lesson 72 of 109.
You can iterate through arrays using a for loop with an index.
Create an array of weekdays:
weekdays := [5]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}Iterate through the array using a for loop:
for i := 0; i < len(weekdays); i++ {
fmt.Println(i, weekdays[i])
}This displays each element with its index:
0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 FridayChallenge
BeginnerIn this challenge, you'll practice iterating over an array of fruits using a for loop. The array is already defined for you. Your task is to complete the for loop to print each fruit in the array on a new line.
Cheat sheet
You can iterate through arrays using a for loop with an index:
weekdays := [5]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
for i := 0; i < len(weekdays); i++ {
fmt.Println(i, weekdays[i])
}This displays each element with its index.
Try it yourself
package main
import "fmt"
func main() {
// Array of fruits
fruits := [5]string{"Apple", "Banana", "Orange", "Grape", "Mango"}
// TODO: Complete the for loop to print each fruit in the array
for i := 0; i < len(fruits); i++ {
// Add your code here to print each fruit
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions10Composite Types: Arrays
Introduction to ArraysDeclaring ArraysInitializing ArraysAccessing Array ElementsArray Length with `len`Iterating Over ArraysMulti-dimensional Arrays2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions