19. JavaScript 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 JavaScript.
- 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 distinct numbers.
Here is the code
<html>
<head>
<title>JavaScript program to find the Sum of n even numbers</title>
</head>
<body>
<table>
<tr>
<td> <input type="text" name="a" id="first" placeholder="Enter a number"/> </td>
</tr>
<tr>
<td> <button onclick="sum ()">Submit</button> </td>
</tr>
</table>
<div id ="num"></div>
</body>
<script type="text/javascript">
function sum()
{
var n,i, sum = 0;
n = parseInt(document.getElementById ("first").value);
for (i = 1; i <= n; i++)
{
if(i%2 == 0)
{
sum = sum+i;
}
}
document.getElementById ("num").innerHTML ="Sum of " +n+ " even natural numbers is :"+sum;
}
</script>
</html>