Sum of Digits in JavaScript

Write a program to accept a no. from user and display Sum of Digits.
(example: 214= 2+1+4 =  7)



Enter a Number:


JavaScript Code:

<HTML><body>
<script>
function find()
  {
 var sum=0;
    var no=parseInt(frm.txt1.value);
    while(no>0)
     {
       sum=sum+no%10;
       no=Math.floor(no/10);
      }
    alert("Sum of digits  "+sum);    
         
   }
</script>
<form name="frm">


Enter a Number:<input name="txt1" type="text" />
<input name="b1" onclick="find();" type="button" value="display" /></form>
</BODY>
</HTML>

8 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. provide program for Sum of Digits provide single digit only ex:123456=>1+2+3+4+5+6 gives 21 but also add 2+1=>3 so final result we have to produce as sinle digit 3

    ReplyDelete
    Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training in India. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

      Delete
  3. provide program for Sum of Digits provide single digit only ex:123456=>1+2+3+4+5+6 gives 21 but also add 2+1=>3 so final result we have to produce as sinle digit 3

    ReplyDelete
    Replies
    1. Why don't you add two while() in series.......Its a small program
      So use output first as input in second.

      Delete
  4. Instead of floor you can use parseInt

    ReplyDelete
  5. while(n>=1)
    {
    s=s+(n%10);
    n=parseInt(n/10);
    }
    alert(s);

    ReplyDelete

Thanks for visiting my Blog!

Have a Question ? Need Help in College Assignments, Need Code that is not available here? Just leave a comment & get your code instantly.

Tips to Enhance Your Blog