Looping 10 times adding input, with for and do while loop in C#?

drowningincoffee picture drowningincoffee · Mar 19, 2012 · Viewed 10.5k times · Source

I'm new taking a basic C# course and I'm having trouble getting an assignment to work. I built a basic calculator and it works fine. Now I had to add a new button called "Sum" that will take an input from one of my boxes (number1Txtbox) and add it to itself 10 times through a loop.

I poured through pages of my c# book and can't figure this one out. I figured out how to initialize the loop with the counter etc, I just can't get this to work for the life of me.

I was told to use a for loop, then switch to a do while loop. Which doesn't really make sense to me, I assumed I could do this with just a for loop. So my question is:

1) Do I even need to switch to a do while loop to do this?
2) What am I doing wrong?

Here is what I have so far and it just makes my program freeze when I attempt to hit the sum button after putting a number in the textbox:

private void sumBtn_Click(object sender, EventArgs e)
{
    int counter;
    int loopAnswer;
    int number1;

    number1 = int.Parse(number1Txtbox.Text);

    for (counter = 1; counter <= 10; counter++)
    {
        loopAnswer = number1 + number1;
        do
        {
            loopAnswer = loopAnswer + number1;
        } while (counter <= 10);

        equalsBox.Text = loopAnswer.ToString();
    }
}

Thanks guys!

Answer

Adriano Carneiro picture Adriano Carneiro · Mar 19, 2012

You mixing things. You either do this:

private void sumBtn_Click(object sender, EventArgs e)
{
    int counter;
    int loopAnswer = 0;
    int number1 = int.Parse(number1Txtbox.Text);

    for (counter = 1; counter <= 10; counter++)
    {
        loopAnswer += number1; //same as loopAnswer = loopAnswer + number1;
    }
    equalsBox.Text = loopAnswer.ToString();
}

or this:

private void sumBtn_Click(object sender, EventArgs e)
{
    int counter = 1;
    int loopAnswer = 0;
    int number1 = int.Parse(number1Txtbox.Text);

    do
    {
        loopAnswer += number1; //same as loopAnswer = loopAnswer + number1;
        counter++;
    } while (counter <= 10);


    equalsBox.Text = loopAnswer.ToString();

}

Also, the final answer (equalsBox.Text = loopAnswer.ToString();) should be out of the loop.