Write a JavaScript program to add ‘n’ numbers?

Program: <html> <script type="text/javascript"> function sumDigits(num) {      var i, sum = 0;              ...

Program:
<html>
<script type="text/javascript">
function sumDigits(num) {
     var i, sum = 0;                  // can declare two variables at once
     for (i = 1; i  <=  num; i++) {
             sum += i;              // add each number to sum (ie, 1 + 2 + ...+ num)
     }
     // Display result
     alert("The sum of the digits from 1 to "+ num + " is:\n\n\t " + sum);
}
</SCRIPT>

<BODY>

Looping Functions - Calculate the sum of the digits.

<FORM NAME="SumNums">

     The sum of the digits from 1 to:

     <INPUT TYPE="text" NAME="charNum">

     <INPUT TYPE="button" VALUE="Calculate"

       onClick="sumDigits(charNum.value)">

</form>

</body>

</html>


OutPut:

sum of n numbers

Related

Web Technology 1598158733467705770

Post a Comment

emo-but-icon

item