Go - Array Example

1. Introduction

Arrays in Go are fundamental data structures that hold a fixed number of values of a single type. Although slices are more commonly used due to their flexibility, arrays provide the benefits of knowing the size of the collection upfront and memory efficiency. This blog post will demonstrate how to use arrays in Go with a simple example.

Definition

An array is a numbered sequence of elements of a single type with a fixed length. In Go, the size of an array is part of its type, and it cannot be resized, making it different from a slice, which can be dynamically resized.

2. Program Steps

1. Declare and initialize an array with specific values.

2. Access and print individual elements from the array.

3. Iterate over the array using a for loop to print all elements.

4. Modify an element of the array.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Declare and initialize an array
	var temperatures [5]float64 = [5]float64{23.4, 26.6, 24.8, 25.2, 22.8}

	// Step 2: Access and print individual elements
	fmt.Println("First temperature:", temperatures[0])
	fmt.Println("Second temperature:", temperatures[1])

	// Step 3: Iterate over the array to print all elements
	fmt.Println("All temperatures:")
	for i, temp := range temperatures {
		fmt.Printf("Day %d: %.2f°C\n", i+1, temp)
	}

	// Step 4: Modify an element of the array
	temperatures[4] = 23.3 // Change the temperature for day 5
	fmt.Println("Updated temperature for day 5:", temperatures[4])
}

Output:

First temperature: 23.4
Second temperature: 26.6
All temperatures:
Day 1: 23.40°C
Day 2: 26.60°C
Day 3: 24.80°C
Day 4: 25.20°C
Day 5: 22.80°C
Updated temperature for day 5: 23.3

Explanation:

1. package main - The program's package is declared as main.

2. import "fmt" - The fmt package is imported for formatted output.

3. temperatures array is declared with a size of 5 and a type of float64, then initialized with five temperature values.

4. Individual elements of temperatures are accessed using an index, starting from 0.

5. A for loop with the range keyword is used to iterate over temperatures. The loop prints each day's temperature with the day number (i+1) and temperature value (temp).

6. The fourth index (fifth element) of temperatures is modified to a new value, 23.3°C.

7. The program prints the first two temperature readings, then all the temperatures, and finally the updated temperature for day 5.

8. The output shows the temperatures in Celsius for a 5-day forecast, along with the updated value for day 5 after modification.


Comments