Sum Of Natural Numbers Using Recursion JavaScript Example

Share:

Hello Friends,

Now let's see example of how to use sum of natural number using recursion example. We will use how to sum of natural number using recursion in javascript. This is a short guide on sum of natural number using recursion. Let's get started with how to find sum of natural number using recursion in javascript.

Here i will give you many example how you can sum of natural number using recursion javascript.

Example : 1
```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Sum Of Natural Numbers Using Recursion JavaScript Example - MyWebtuts.com</title>
<body>
<h2>Sum Of Natural Numbers Using Recursion JavaScript Example - MyWebtuts.com</h2>
<script type="text/javascript">
function sum(num) {
if(num > 0) {
return num + sum(num - 1);
}
else {
return num;
}
}
const x = parseInt(prompt('Enter a positive integer: '));
const result = sum(x);

document.write(`Output : The sum is \${result}`);
</script>
</body>
</html>
```
Output :
```Enter a positive integer: 5
Output : The sum is 15
```
Example : 2
```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Sum Of Natural Numbers Using Recursion JavaScript Example - MyWebtuts.com</title>
<body>
<h2>Sum Of Natural Numbers Using Recursion JavaScript Example - MyWebtuts.com</h2>
<script type="text/javascript">
const number = parseInt(prompt('Enter a positive integer: '));

let sum = 0;

for (let i = 1; i <= number; i++) {
sum += i;
}
document.write('Output : The sum of natural numbers :', sum);
</script>
</body>
</html>
```
Output :
```Enter a positive integer: 7
Output : The sum of natural numbers : 28
```