Computer Science Canada

Stack overflow

Author:  username123 [ Sun Nov 01, 2015 11:32 am ]
Post subject:  Stack overflow

When I try to run this code, I always get a stack overflow, and I don't know why. It works when I get rid of triangle on line 13 though, but I need this to be recursive.
Java:

public int triangle(int rows)
{
  if(rows == 0)
  {
    return 0;
  }
  else if(rows == 1)
  {
    return 1;
  }
  else
  {
    return triangle(rows * (rows + 1)/2);
  }
}

Author:  Insectoid [ Sun Nov 01, 2015 12:46 pm ]
Post subject:  RE:Stack overflow

A stack overflow happens when your program recurses too many times in a row. In this case, it's probably because rows never reaches 0 or 1, so it's recursing infinitely. Does line 13 ever resolve rows to 0 or 1?

Author:  username123 [ Sun Nov 01, 2015 1:42 pm ]
Post subject:  Re: RE:Stack overflow

Insectoid @ Sun Nov 01, 2015 12:46 pm wrote:
A stack overflow happens when your program recurses too many times in a row. In this case, it's probably because rows never reaches 0 or 1, so it's recursing infinitely. Does line 13 ever resolve rows to 0 or 1?

That's what I tried to do with lines 3 - 10, but I didn't do it properly. I made it work though.
Java:

public int triangle(int rows)
{
  if(rows == 0)
  {
    return 0;
  }
  return rows + triangle(rows - 1);
}


: