0
0
Goprogramming~15 mins

Iterating over arrays in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Iterating over arrays
📖 Scenario: You are helping a small shop owner who wants to check the prices of some fruits they have in stock.
🎯 Goal: You will create a program that stores fruit prices in an array, then uses a loop to print each fruit's price.
📋 What You'll Learn
Create an array with exact fruit prices
Create a variable to count the number of fruits
Use a for loop with index to iterate over the array
Print each fruit price with a message
💡 Why This Matters
🌍 Real World
Arrays and loops are used in many programs to store and process lists of data, like prices, names, or measurements.
💼 Career
Understanding how to iterate over arrays is a fundamental skill for software developers working with data collections.
Progress0 / 4 steps
1
Create the fruit prices array
Create an array called prices of type float64 with these exact values: 1.25, 0.75, 2.50, 3.00.
Go
Hint

Use the syntax prices := [4]float64{1.25, 0.75, 2.50, 3.00} to create the array.

2
Create a variable for the number of fruits
Create a variable called count and set it to the length of the prices array using the len function.
Go
Hint

Use count := len(prices) to get the number of items in the array.

3
Use a for loop to iterate over the prices array
Use a for loop with the variable i from 0 to count (exclusive) to iterate over the prices array.
Go
Hint

Use for i := 0; i < count; i++ and access each price with prices[i].

4
Print each fruit price inside the loop
Inside the for loop, use fmt.Println to print the message "Price of fruit at index i: $price" where i is the index and price is the price at that index. Use fmt.Printf with formatting to show the price with two decimals.
Go
Hint

Use fmt.Printf("Price of fruit at index %d: $%.2f\n", i, prices[i]) to print the message.