Welcome to Code Review! I would suggest some structural changes to your program, first, before discussing the algorithm.
In your main program, you scan for input of the row once before the loop and once inside the loop after calcPascal(r,c)
. You can rearrange the code in the following way to write the scan only once and to also check for stronger boundary conditions. If the user types any negative number, the program should exit so we need to check against that as well. Also, the names can be row
and column
, they will not overload those in the calcPascal
function. Here's my suggestion for main
:
int row, column;
boolean should_exit = false;
Scanner input = new Scanner(System.in);
while (!should_exit) {
System.out.print("Row: ")
row = input.nextInt();
if (row >= 0) {
System.out.print("\nColumn: ");
column = input.nextInt();
if (column >= 0) {
System.out.println("\n" + calcPascal(row, column);
continue;
}
}
should_exit = true;
}
Now for your algorithm. The Pascal triangle is an inherently recursive structure, and therefore it would not be unreasonable to write a recursive method to calculate its values. This works for small values of row
and column
but it will most likely lead to a stack overflow for large values. If you want to stick to a recursive function, the best thing you can do is remove the variables all together and try and get the function into a "tail-recursive form" by which we mean that the function itself is returned as the last statement. Here's what I mean:
public static int calcPascal(int row, int column) {
if (row == column || row == 0 || column == 0)
return 1;
else
return calcPascal(row - 1, column - 1) + calcPascal(row - 1, column);
}
This will improve readability and speed of your code as Java will optimize the call to the calcPascal
.
(Also note that there is nothing wrong with making your base case zero, all this does is zero index the triangle. If you want to make it start at one, then you will need to change the base case to check against one and the loop in main
will have to check against one also. I suggest leaving it like it is, it's actually more mathematically correct.)
The other alternative to the recursive algorithm is to use an iterative method by use of combinations. The row and column of Pascal's triangle are the Binomial Coefficients where row=n
and column=k
. Using the equation for finding the binomial coefficients will be faster than a recursive method for large values of row
and column
.