Thursday 23 June 2011

Find the sum of the digits

A simple program to show How to find the sum of the digits from 1 to desired digit using JavaScript.
Create a simple HTML page using this code and view the result.

<html>
<head>
<title>Sum of Nos</title>
</head>
<script language="javascript">
function findsum(num) {
     var i, sum = 0;                 
     for (i = 1; i <= num; i++) {
     sum += i;            
     }
      alert("The sum of the digits from 1 to "+ num + " is:\n\n\t " + sum);

}
</script>
<body>
JavaScript Program - Find the sum of the digits.
<form name="adddigits">
     The sum of the digits from 1 to:
     <input type="text" name="num">
     <input type="button" value="Calculate" onClick="findsum(adddigits.num.value)">
</form>
</body>
</html>

When you test it in your browser yow will see something like this:

No comments:

Post a Comment