Go program to find Sum and Average of Natural Numbers

This Go program uses the for loop to iterate from 1 to n and finds the sum and average of natural numbers. Inside the for loop, we add each number to the total, and outside the loop, we calculated the average.

package main

import "fmt"

func main() {

    var num, i int

    fmt.Print("\nEnter the Maximum Natural Number = ")
    fmt.Scanln(&num)

    total := 0

    for i = 1; i <= num; i++ {
        total = total + i
    }
    average := total / num

    fmt.Println("The Sum of Natural Numbers from 1 to ", num, " = ", total)
    fmt.Println("The Average of Natural Numbers from 1 to ", num, " = ", average)
}
SureshMac:GoExamples suresh$ go run sumofNatural1.go

Enter the Maximum Natural Number = 10
The Sum of Natural Numbers from 1 to  10  =  55
The Average of Natural Numbers from 1 to  10  =  5
SureshMac:GoExamples suresh$ go run sumofNatural1.go

Enter the Maximum Natural Number = 20
The Sum of Natural Numbers from 1 to  20  =  210
The Average of Natural Numbers from 1 to  20  =  10

Golang Program to Sum and Average of Natural Numbers

In this Golang program, we declared a new function that returns the sum of natural numbers from 1 to N. In that function, we used the mathematical formula n(n+1)/2 to get the sum. 

package main

import "fmt"

func sumAvg(num int) int {
    if num == 0 {
        return num
    } else {
        return (num * (num + 1) / 2)
    }
}
func main() {

    var num int

    fmt.Print("\nEnter the Maximum Natural Number = ")
    fmt.Scanln(&num)

    total := sumAvg(num)
    average := total / num

    fmt.Println("The Sum of Natural Numbers from 1 to ", num, " = ", total)
    fmt.Println("The Average of Natural Numbers from 1 to ", num, " = ", average)
}
SureshMac:GoExamples suresh$ go run sumofNatural2.go

Enter the Maximum Natural Number = 15
The Sum of Natural Numbers from 1 to  15  =  120
The Average of Natural Numbers from 1 to  15  =  8
SureshMac:GoExamples suresh$ go run sumofNatural2.go

Enter the Maximum Natural Number = 60
The Sum of Natural Numbers from 1 to  60  =  1830
The Average of Natural Numbers from 1 to  60  =  30

In this Go program, we are recursively calling the sumAvg function with the updated value. The main part of this Go program to find Sum and Average of Natural Numbers is (num + sumAvg(num-1)).

package main

import "fmt"

func sumAvg(num int) int {
    if num == 0 {
        return num
    } else {
        return (num + sumAvg(num-1))
    }
}
func main() {

    var num int

    fmt.Print("\nEnter the Maximum Natural Number = ")
    fmt.Scanln(&num)

    total := sumAvg(num)
    average := total / num

    fmt.Println("The Sum of Natural Numbers from 1 to ", num, " = ", total)
    fmt.Println("The Average of Natural Numbers from 1 to ", num, " = ", average)
}
Golang Program to find Sum and Average of Natural Numbers 3