-1

I am using recursion to add two numbers together, By adding 1 to the first input one at a time until I have reached the value of the second. Why does this work...

        private static int AddMethod(int input1, int input2)
    {
        if (input2 == 0)
        {
            Console.WriteLine(input1);
            return (input1);
        }
        else
        {
            input1++;
            input2--;
            return AddMethod(input1, input2);
        }

    }

But not this..

    private static int AddMethod(int input1, int input2)
    {
        if (input2 == 0)
        {
            Console.WriteLine(input1);
            return (input1);
        }
        else
        {
            return AddMethod(input1++, input2--);
        }

    }

I am using Visual Studio 2010 and .Net 4.0

Brandon
  • 915
  • 4
  • 23
  • 44
  • 6
    What doesnt work about it? it looks more like you want `return AddMethod(++input1, --input2);` – Sayse Jul 29 '14 at 12:35
  • 3
    There's a good explanation of what is going on at [What is the difference between i++ and ++i?](http://stackoverflow.com/questions/3346450/what-is-the-difference-between-i-and-i/3346729#3346729). – Andrew Morton Jul 29 '14 at 12:39
  • Useful [related question](http://stackoverflow.com/questions/484462/difference-between-i-and-i-in-a-loop) – Sayse Jul 29 '14 at 12:39

3 Answers3

6

Because return AddMethod(input1++, input2--); first passes your inputs, and THEN increments and decrements.

Try return AddMethod(++input1, --input2);

Benjamin Diele
  • 1,177
  • 1
  • 10
  • 26
2

Post fix increment works by first "assigning" the value, then incrementing the value.

Compare:

int a = 1;
int b = 1;

int x = a++;
int y = ++b;

So in your case, the value you pass to AddMethod is the unchanged value, it modifies the value of input1 and input2 after they are passed.

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
2

Because the ++ and -- operators are executed after passing the values as parameters to the function.

Your code:

return AddMethod(input1++, input2--);

Is equal to:

int result AddMethod(input1, input2);
input1++;
input2--;
return result;

Instead of all this, you could use:

return AddMethod(++input1, --input2);
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325