Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Sum of Natural Numbers Using Recursion
In this example, you'll learn to find the sum of natural numbers using recursion. To solve this problem, a recursive function calculate_sum() function is created.
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.