43. JavaScript Program to Compute the 1+3+5+7+9+ …….+n Series.
How does this program work?
- This program is used to find the Sum of the given series 1+3+5+7+9+ …….+n using JavaScript.
- The integer entered by the user is stored in variable n i.e last term for the given series.
- By using for loop we can find the sum of series for odd numbers upto nth term.
Here is the code
<html>
<head>
<title>JavaScript program to Find the Sum of given series</title>
</head>
<body>
<table>
<tr>
<td> <input type="text" name="a" id="first" placeholder="Enter any number"> </td>
</tr>
<tr>
<td> <button onclick="series1 ()" >Submit</button> </td>
</tr>
</table>
</body>
<script type="text/javascript">
function series1()
{
var n,i,sum = 0;
n = parseInt(document.getElementById ("first").value);
document.write ( "Series till the enter number: </br>");
document.write ( "</br>");
for(i = 1; i <= n; i++ )
{
if(i%2 != 0)
{
document.write (i + " ");
sum = sum+i;
}
}
document.write("</br>Sum of the series : "+sum);
}
</script>
</html>