1

I'm very new to programming. However, I've written a method called "succ" that's adds 1 to a given parameter. It looks like this:

int succ(int x) {
  return x += 1;
}

Now I'm supposed to write another method that adds 2 numbers using my first method. This is what my attempt looks like:

int add(int x, int y) {
  for(int i = 0; i < y; i++) {
    succ(x);
  }
  return x;
}

Unfortunately it doesn't seem to work; it always returns the initial x. For example: If I type add(8,5) it just returns 8. Can someone help me? What am I doing wrong?

Thanks in advance.

Shinubi
  • 33
  • 4
  • try doing `x = succ(x)` . Also, read this https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1 – dumbPotato21 Mar 16 '17 at 18:29
  • Oh wow, it worked. I can't believe I didn't think of that. Thanks a lot! – Shinubi Mar 16 '17 at 18:31
  • 1
    Welcome to programming!! You're really going good. As answer is also posted would recommend you to refer [this link](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1) – Pratik Ambani Mar 16 '17 at 18:32
  • @Shashwat has the fix and I would change your `succ(int x)` to `succ(int somethingelse)` just for readability. It's easy to get confused starting out. – Ross Keddy Mar 16 '17 at 18:32

3 Answers3

2

You're not doing anything with the returned value. If you want to assign it back to x, do that:

x = succ(x);

Edit: Or, perhaps you mean to add to x, since you're doing it in a loop? It's not entirely clear what this code is meant to do, and I suspect more applicable variable/method names would help. But if you want to keep adding the result, you'd just do this:

x += succ(x);

Additionally, you don't need to modify x in your succ function. Doing so in this manner may lead to unexpected behavior in the future in other examples. Keep the operations as simple as possible. Just return the calculated value:

return x + 1;
David
  • 208,112
  • 36
  • 198
  • 279
  • Thanks a lot, that was the solution. Also thanks for the advice about modifying `x` in my `succ` function! – Shinubi Mar 16 '17 at 18:37
0

You are missing the return value of the succ method, replace the succ(x); with x = succ(x);

int add(int x, int y) {

  for(int i = 0; i < y; i++) {
    x = succ(x);
  }
  return x;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

You keep overwriting the x value with the return value from the function. You need to add to it in each iteration, not overwrite it.

E LaRoche
  • 1,106
  • 1
  • 7
  • 8