Sum of Natural Numbers Using Recursion


Example: Sum of Natural Numbers

# Program to find the sum of
# natural numbers upto n
# using recursive function

calculate_sum() <- function(n) {
    if(n <= 1) {
        return(n)
    } else {
        return(n + calculate_sum(n-1))
    }
}

Output

> calculate_sum(7)
[1] 28

Here, we ask the user for a number and use recursive function calculate_sum() to compute the sum up to that number.

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community