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.
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.
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)
}
We can create a recursive function to calculate the sum of the first N natural numbers.
For example,
sumOfNaturalNumbersRec
that takes one parameter n
of type int
.n
is equal to 1. If true, return 1 (base case).n
plus the result of calling sumOfNaturalNumbersRec
with n - 1
(recursive case).sumOfNaturalNumbersRec
function with a sample value and print the result.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)
}
Sum of the first 10 natural numbers using recursion is 55