This blog presents a simple Go Programming Practice Exercise.
Here’s a simple practice exercise to get you started with Go programming.
Go Programming Practice Exercise: Calculate Average Write a Go program that calculates the average of a list of numbers.
- Create a new Go file named
average.go
. - Write a program that prompts the user to enter a series of numbers, separated by spaces.
- Parse the input string to extract individual numbers.
- Calculate the average of the numbers.
- Print the average to the console.
package main
import (
"fmt"
"strconv"
)
func main() {
var numbers []float64
var input string
fmt.Println("Enter numbers (type 'done' when finished):")
for {
fmt.Print("Enter number: ")
fmt.Scanln(&input)
if input == "done" {
break
}
num, err := strconv.ParseFloat(input, 64)
if err != nil {
fmt.Printf("Error parsing number: %v\n", err)
continue
}
numbers = append(numbers, num)
}
if len(numbers) == 0 {
fmt.Println("No valid numbers entered.")
return
}
// Calculate sum
var sum float64
for _, num := range numbers {
sum += num
}
// Print the sum
fmt.Printf("Sum: %.2f\n", sum)
// Calculate the average
average := sum / float64(len(numbers))
// Print the average
fmt.Printf("Average: %.2f\n", average)
}
In order to run the program,
- Save the code above in a file named
average.go
. - Open a terminal or command prompt.
- Navigate to the directory containing
average.go
. - Run the program using the command
go run average.go
.
Output
Further Reading
Spring Framework Practice Problems and Their Solutions
How to Create and Run a Simple Program in Go?
20+ Interview Questions on Go Programming Language
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language