147. PHP Program to find the Sum of N natural numbers using recursion.
How does this program work?
- In this program we are going to learn about how to find the Sum of N natural numbers using PHP.
- The integer entered by the user is stored in variable n.
- Declare variable sum to store the sum of numbers and initialize it with 0.
- By using Recursion method we can find the sum of n natural numbers.
Here is the code
<html>
<head>
<title>To find the sum of N natural numbers using recursion </title>
</head>
<body>
<form method="post">
<table border="0">
<tr>
<td> <input type="text" name="num1" value="" placeholder="Enter a number"/>
</td>
</tr>
<tr>
<td> <input type="text" name="num2" value="" placeholder="Enter a number"/>
</td>
</tr>
<tr>
<td> <input type="submit" name="submit"value="Submit"/>
</td>
</tr>
</table>
</form>
<?php
function Sum($n)
{
if ($n <= 1)
return $n;
return $n + Sum ($n - 1 );
}
if(isset($_POST[ 'submit'])) {
$n1 = $_POST ['num1' ];
echo "The sum of $n1 natural numbers are : ".Sum($n1)."<br>";
$n2 = $_POST ['num2' ];
echo "The sum of $n2 natural numbers are : ".Sum($n2)."<br>";
return 0;
}
?>
</body>
</html>