45. PHP Program to find the Sum of N natural numbers.
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 for loop we can add the sum of n natural numbers.
Here is the code
<html>
<head>
<title>PHP Program To find the Sum of N natural numbers</title>
</head>
<body>
<form method="post">
<table border="0">
<tr>
<td> <input type="text" name ="num" value="" placeholder="Enter a positive integer"/> </td>
</tr>
<tr>
<td> <input type="submit" name ="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<?php
if(isset($_POST['submit']))
{
$n = $_POST['num'];
$sum = 0;
//Using loop to do sum of N natural numbers
for($i = 1; $i <= $n; ++$i)
{
$sum = $sum + $i;
}
echo "Sum of $n natural numbers = $sum";
return 0;
}
?>
</body>
</html>