Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding numbers from 1 to N in C#

Tags:

c#

while-loop

I'm writing code in C# and trying to add all of the numbers between the number 1 and N, N being the number that is inputted in a textbox. I'm doing this, at least trying to do this, by putting it into a while loop.

I have added all the numbers between 2 textboxes before but for some reason I'm driving myself crazy and can't figure this out. I'm a beginning programmer so please be gentle.

Any help would be greatly appreciated.

Edit: One of the six thousand things I've tried. I think this has me in an infinite loop?

       private void btnAddAll_Click(object sender, EventArgs e)
       {
           int n;
           int count = 0;
           int answer = 0;

           n = int.Parse(txtNum.Text);

           count = n;

           while (count >= 1)
           {
               answer = answer + count;
               count++;
           }
               lstShow.Items.Add("Sum = " + answer);
               lstShow.Text = answer.ToString();
       }
like image 279
jsacha Avatar asked Dec 06 '22 11:12

jsacha


2 Answers

Why not use Gauss formula. (N*(N+1))/2

private void btnAddAll_Click(object sender, EventArgs e)
{
     int n, answer;  
     n = int.Parse(txtNum.Text);
     answer = (n*(n+1))/2;
     lstShow.Items.Add("Sum = " + answer);
     lstShow.Text = answer.ToString();
}
like image 137
nerdybeardo Avatar answered Dec 10 '22 01:12

nerdybeardo


If you change the ++ to a -- it should work as you want it to.

   int n;
   int count = 0;
   int answer = 0;

   n = 3;

   count = n;

   while (count >= 1)
   {
       answer = answer + count;
       count--; // here was the error
   }

   Console.WriteLine (answer);

Output: 6

Also, just for a point of additional interest you can use That uses Enumerable.Range and Enumerable.Sum instead of the while loop (probably goes beyond what is expected for a homework but it's useful to know what's out there).

answer =  Enumerable.Range(1, n).Sum();
like image 43
Aaron Anodide Avatar answered Dec 10 '22 01:12

Aaron Anodide