Recursive method for Pascal's triangle

user2932450 picture user2932450 · Nov 18, 2013 · Viewed 18.9k times · Source

I have written a method to evaluate a Pascal's triangle of n rows. However when I test the method I receive the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

Here is the code:

public static int[] PascalTriangle(int n) {
    int[] pt = new int[n + 1];
    if (n == 0) {
        pt[0] = 1;
        return pt;
    }
    int[] ppt = PascalTriangle(n - 1);
    pt[0] = pt[n] = 1;
    for (int i = 0; i < ppt.length; i++) {
        pt[i] = ppt[i - 1] + ppt[i];
    }
    return pt;
}

Please let me know if you have any ideas for how the code could be edited to fix the problem.

Answer

Karthik T picture Karthik T · Nov 18, 2013
for(int i = 0; i < ppt.length; i++)
    {
        pt[i] = ppt[i-1] + ppt[i];

In your first iteration, i == 0 and so (i-1) == -1. This is the cause of the error.

You can special handle the boundaries to avoid this. Or as the others have suggested, start i at 1 instead of 0.