How to add the numbers used in loops?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sinoka
    New Member
    • Jan 2011
    • 1

    How to add the numbers used in loops?

    Like

    1
    2
    3
    4
    5

    And here it will write the sum of the numbers above using loops
    So 1+2+3+4+5=15
    what is the code should I use to make it show 15 using loops or while statements or if else codes?
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    actually, you don’t need a loop at all, just some maths. the formula to calculate the series of natural numbers is well known.
    Code:
    ∑(n) = n · (n + 1) / 2

    Comment

    • Bharat383
      New Member
      • Aug 2011
      • 93

      #3
      Code:
      <script type="text/javascript">
      var  temp = 0;
      for(a=1;a<=5;a++)
      {
          temp = temp + a;
      }
      
      alert(temp);
      </script>
      Last edited by acoder; May 23 '12, 10:38 PM. Reason: Please use [code] tags

      Comment

      Working...