Find Sum of First N Natural Numbers using Recursion in Go
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)
}
Example 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,
- Define a function named
sumOfNaturalNumbersRec
that takes one parametern
of typeint
. - Check if
n
is equal to 1. If true, return 1 (base case). - Otherwise, return
n
plus the result of callingsumOfNaturalNumbersRec
withn - 1
(recursive case). - 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