Algorithm


  1. Function Definition:

    • Declare a function sumOfNaturalNumbers that takes a parameter n (the last natural number).
  2. Base Case:

    • Check if n is equal to 1.
      • If true, return 1 (the sum of the first natural number).
  3. Recursive Call:

    • Otherwise, make a recursive call to sumOfNaturalNumbers with the parameter n-1.
      • Add the current value of n to the result of the recursive call.
      • Return the sum.

 

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

x
+
cmd
Enter a positive integer: 5
The sum is 15
Advertisements

Demonstration


JavaScript Program to Find Sum of Natural Numbers Using Recursion

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way