Algorithm
-
Function Definition:
- Declare a function
sumOfNaturalNumbers
that takes a parametern
(the last natural number).
- Declare a function
-
Base Case:
- Check if
n
is equal to 1.- If true, return 1 (the sum of the first natural number).
- Check if
-
Recursive Call:
- Otherwise, make a recursive call to
sumOfNaturalNumbers
with the parametern-1
.- Add the current value of
n
to the result of the recursive call. - Return the sum.
- Add the current value of
- Otherwise, make a recursive call to
Code Examples
#1 Code Example- Sum of Natural Numbers Using Recursion
Code -
Javascript Programming
// program to find the sum of natural numbers using recursion
function sum(num) {
if(num > 0) {
return num + sum(num - 1);
}
else {
return num;
}
}
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
const result = sum(number);
// display the result
console.log(`The sum is ${result}`);
Copy The Code &
Try With Live Editor
Output
Enter a positive integer: 5
The sum is 15
The sum is 15
Demonstration
JavaScript Program to Find Sum of Natural Numbers Using Recursion