Go

Go Programming Practice Exercise

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.

  1. Create a new Go file named average.go.
  2. Write a program that prompts the user to enter a series of numbers, separated by spaces.
  3. Parse the input string to extract individual numbers.
  4. Calculate the average of the numbers.
  5. 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,

  1. Save the code above in a file named average.go.
  2. Open a terminal or command prompt.
  3. Navigate to the directory containing average.go.
  4. Run the program using the command go run average.go.

Output

Computing Average of Numbers in Go
Computing Average of Numbers in Go

Further Reading

Getting Started With Go

How to Install Go?

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

Creating and Executing Simple Programs in Go

Java Practice Exercise

programmingempire

Princites

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *