THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
In this blog post, You will learn two programs for finding the average of array/slice numbers.
Following are golang features are required to under this programs.
Following is a sequence of steps.
package main
import "fmt"
func main() {
var numbs = [] int {
51, 4, 5, 6, 24
}
total: = 0
for _, number: = range numbs {
total = total + number
}
average: = total / len(numbs) // len function return array size
fmt.Printf("Average of array %d", average)
}
The output of the above program
Average of array 18
In this program,
User gives the numbers input via command line using fmt.Scanln function
.
Here is a program code to read numbers from the command line and return the average of it
package main
import "fmt"
func main() {
var array[50] int
var total, count int
fmt.Print("How many numbers you want to enter: ")
fmt.Scanln( & count)
for i: = 0;
i < count;
i++{
fmt.Print("Enter value : ")
fmt.Scanln( & array[i])
total += array[i]
}
average: = total / count
fmt.Printf("Average is %d", average)
}
The output of the above program is
How many numbers you want to enter: 5
Enter value : 1
Enter value : 2
Enter value : 3
Enter value : 4
Enter value : 5
Average is 3
A Step by step tutorial and Program to Calculate average using an Array/slice of numbers read input from the command line and average of numbers example.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts