Menu Close

Go – Program to calculate sum of natural numbers in go golang

In this article, We are going to learn code and algorithm to get sum of natural numbers in go golang. The positive numbers (1, 2, 3 …. n) are known as natural numbers. We will implement sum of natural numbers using for loop and recursion.

There are many ways to get the sum of natural numbers in go golang.

1:) Using for loop

Algorithm:

  • Get the input as number from user.
  • assign zero value to the variable which will hold the sum of natural number.
  • Run a for loop to calculate the sum of natural number.

Example with Code:

// Sum of n natural number (the positive numbers 1, 2, 3... are known as natural numbers)

package main

import "fmt"

func main(){
    
    var n, sum int
    
    fmt.Print("Enter a positive integer to get sum: ")
    
    fmt.Scan(&n)
    
    fmt.Print("\nNatural numbers are : \n")
    
    sum = 0
    
    for i := 1; i <= n; i++ {
        
        fmt.Printf("%d ", i)
        
        sum = sum + i
    }
    
    fmt.Print("\n\nSum : ",sum)
    
}

2:) Using recursion

Algorithm:

  • Get the input as number from user.
  • Calculate the sum of natural numbers recursively.
  • Return the sum to the main function

Example with Code:

package main

import "fmt"

func sum_of_natural_numbers(n int) int {
    
    if (n == 0) {
        
        return 0
        
    }
    
    return (n + sum_of_natural_numbers(n-1))
}

func main(){

    var n int
    
    fmt.Print("Enter a positive integer to get sum: ")
    
    fmt.Scan(&n)

    result := sum_of_natural_numbers(n)

    fmt.Printf("\nSum is %d", result)
    
}

Output:


Enter a positive integer to get sum: 5
Sum is 15
Reference:
https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF

To learn more about golang, Please follow given below link:
https://www.techieindoor.com/go-lang-tutorial/
Posted in golang, golang program

Leave a Reply

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