Go How To Find The Average Of 10 Numbers Using A While Loop
In Go (Golang), there isn't a traditional while loop like in some other programming languages. Instead, Go uses for loops for most iterative tasks. To find the average of 10 numbers in Go, you can use a for loop. Here's an example of how to do it:
package main
import (
"fmt"
"strconv"
)
func main() {
sum := 0.0
count := 0
for count < 10 {
fmt.Printf("Enter number %d: ", count+1)
var input string
fmt.Scanln(&input)
number, err := strconv.ParseFloat(input, 64)
if err == nil {
sum += number
count++
} else {
fmt.Println("Invalid input. Please enter a valid number.")
}
}
if count > 0 {
average := sum / float64(count)
fmt.Printf("The average of the 10 numbers is: %.2f\n", average)
} else {
fmt.Println("No valid numbers entered.")
}
}
In this Go code:
- We use the fmt and strconv packages to handle input and conversion.
- We initialize variables to keep track of the sum and count of numbers.
- We use a for loop to repeatedly prompt the user for input until they have entered 10 valid numbers.
- Inside the loop, we use fmt.Scanln to read input and strconv.ParseFloat to parse it into a float. If it's a valid number, we add it to the sum and increment the count. If not, we print an error message.