Search code examples
c#modulusalternate

Need help alternating a series range from 1 to the number entered.


I am trying to alternate addition and subtraction on a range of numbers. In this series, the process alternates between addition and subtraction. For example, if your target number is 5 the series goes 1 + 2 - 3 + 4 - 5 or -1.

I am working with the logic that you add if the number is odd and you subtract if the number is even. I am using the modulus operator to determine if the number is even. My logic doesn't seem to work if the variable results = 0. Any help would be greatly appreciated.

Here is my code:

 private void alturnating_Input()
    {
        int numberEntered = int.Parse(txtenterNumber.Text);
        int results = 1;
        int i = 0;
        int even = 0;
        for (i = 1;  i < numberEntered; i++)
            even = i % 2;
            if (even != 0)
              results = results + i;
            else
              results = results - i;
        txtAlternating.Text= results.ToString();  


    }

I am using Visual Studio Pro C# 2012.

Thank you. I greatly appreciate your help.


Solution

  • If you have more than one line in the body of your for loop,you must use the curly-braces:

    for (i = 1;  i < numberEntered; i++)
    {
         even = i % 2;
         if (even != 0)
            results = results + i;
         else
           results = results - i;
    }