Go Tutorials

Go Programs

Go Find Sum of First N Natural Numbers using Recursion


Go Find Sum of First N Natural Numbers using Recursion

In this tutorial, we will learn how to find the sum of the first N natural numbers using recursion in Go. We will cover the basic concept of recursion and implement a recursive function to perform the calculation.


What is the Sum of Natural Numbers

The sum of the first N natural numbers is the sum of all positive integers from 1 to N. This can be calculated using recursion by adding the current number to the sum of the previous numbers.


Syntax

The syntax to find the sum of the first N natural numbers using recursion in Go is:

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


Finding the sum of the first N natural numbers using recursion

We can create a recursive function to calculate the sum of the first N natural numbers.

For example,

  1. Define a function named sumOfNaturalNumbersRec that takes one parameter n of type int.
  2. Check if n is equal to 1. If true, return 1 (base case).
  3. Otherwise, return n plus the result of calling sumOfNaturalNumbersRec with n - 1 (recursive case).
  4. In the main function, call the sumOfNaturalNumbersRec function with a sample value and print the result.

Go Program

package main

import (
    "fmt"
)

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

func main() {
    // Find the sum of the first 10 natural numbers using recursion
    result := sumOfNaturalNumbersRec(10)

    // Print the result
    fmt.Printf("Sum of the first 10 natural numbers using recursion is %d\n", result)
}

Output

Sum of the first 10 natural numbers using recursion is 55