47. PHP Program to find the Sum of N even numbers.
How does this program work?
- In this program we are going to learn about how to find the Sum of N even numbers using PHP.
- The integer entered by the user is stored in variable n.
- Declare variable sum to store the sum of even numbers and initialize it with 0.
- By using for loop we can add the sum of n even numbers.
Here is the code
<html>
<head>
<title>PHP Program To find the Sum of N even numbers</title>
</head>
<body>
<form method="post">
<table border="0">
<tr>
<td> <input type="text" name="num" value="" placeholder="Enter a number"/> </td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Submit"/> </td>
</tr>
</table>
</form>
if(isset($_POST['submit']))
{
$n = $_POST['num'];
$sum = 0;
//Using loop to do sum of even numbers
for($i = 0; $i <= $n; $i += 2)
{
$sum = $sum + $i; //Addition of even numbers
}
echo "Sum of $n even numbers = $sum";
return 0;
}
?>
</body>
</html>