JavaScript and HTML code to calculate sum of 1 to n - Practical [ SWPD 4311603 ]

 Practical Aim:

JavaScript and HTML code to calculate sum of 1 to n

Sample output:
calculate sum of 1 to n


First, try at own

Code

sum_1_to_n_number_javascript.html file

Untitled Document

<html>
<head>
<title>JavaScript sum 1 to n Number</title>
<style>
button {
background-color: black;
border: none;
color: white;
padding: 10px 10px;
text-align: center;
text-decoration: none;
font-size: 15px;
cursor: pointer;
border-radius: 12px;
}

</style>
<script>
function sum()
{
var n,i, sum = 0, enterednumbers="", result;
n = parseInt(document.getElementById ("number").value);
for (i = 1; i <= n; i++)
{
sum = sum+i;
enterednumbers =enterednumbers + i + " + ";
}
result = document.getElementById ("result").innerHTML="Sum of 1 to "+n+ " natural numbers is :";
document.getElementById ("result").innerHTML=result + "<br>"+ enterednumbers +"= "+ +sum;
}
</script>

</head>
<body>
Sum of 1 to <input id="number" /> number is:<br><br>
<button onclick="sum()">Print Sum</button>
<hr> <div id="result" >


</body>

</html>


Try here

<!DOCTYPE html >
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<h1> Try your code here</h1>
</body>
</html>



Output


Post a Comment

0 Comments