Sunday, December 16, 2018

Golang example - Program to calculate Sum of natural numbers

This post we will cover three programs to find the sum of natural numbers
  • Sum of first n natural numbers entered by the user
  • Sum of first n natural numbers using for loop
  • Sum of first n natural numbers Recursive function
Natural numbers are positive integers or whole numbers which starts from 0,1, 2 .... n. These also called nonpositive numbers. This post is about calculating the sum of natural numbers from 1 to n where n is read from console by the user. 

To understand this programs, You should have an understanding of following golang features.

Example program 1- Sum of first n natural numbers Entered by user

The below program takes an input number from command line console from a user and calculates the sum of natural numbers up to a given number

package main

import (
 "fmt"
)

func main() {
 //reading an multiple input string
 var number int
 fmt.Print("Please enter number:")
 fmt.Scanln(&number)
 sumResult := 0
 for i := 0; i <= number; i++ {
  sumResult += i
 }
 fmt.Printf("Sum of  %d numbers is  %d", number, sumResult)
}

Output is
Please enter number:10
Sum of  10 numbers is  55

The above program read an input from the user using the Scanln function, store the number in a variable number.
Using for loop, iterate and calculates the values from 0 up to n
Finally, a sum is printed to console

Example program 2- Sum of natural numbers using for loop

In this program, Instead of taking input from the user, the variable value is fixed, Like an above program, for loop is used to calculate up to a given number.
Finally printed value to the console
package main

import (
 "fmt"
)

func main() {
 max := 10
 sumResult := 0
 for i := 0; i <= max; i++ {
  sumResult += i
 }
 fmt.Printf("Sum of  %d numbers is  %d", max, sumResult)
}

Output is
Sum of  10 numbers is  55

Example program 3- Recursion function Sum of natural numbers

package main

import (
 "fmt"
)

func sumNatural(numb int) int {
 if numb != 0 {
  return numb + sumNatural(numb-1)
 } else {
  return numb
 }
}

func main() {
 number := 10
 fmt.Printf("Sum of  %d numbers is  %d", number, sumNatural(number))
}
Output is

Sum of  10 numbers is  55

In the above program, sumNatural recursive function is declared. This will be called in the main function initially at first using sumNatural(10) function.
the number 10 is added the result of sumNatural(9). next function call will be fired from sumNatural which again calls sumNatural(8) and add this result. This sequence of the process will continue until numb is equal to 0.

recursive call execution will be stopped When numb is zero and finally returned the result to the main function

Related article


EmoticonEmoticon