I'll try to use a recursive method to print pascals triangle to the standard output. I started by making an iterative method to get an idea of how I wanted the method to work. See the code below.
/**
* Print Pascal's triangle with PrintOut.
*
* @param n The amount of rows in total
*/
public static void printPascal(int n) {
for (int i = 0; i < n; i++) {
System.out.format("%" + (n - i) * 3 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("% 6d", binom(i, j));
}
System.out.println();
}
}
Javadoc and the signature of binom
/**
* Method which calculates the values in Pascal's triangle.
*
* @param n The row of "the place"
* @param k The column of "the place"
* @return A value on "the place" from the triangle
*/
public static int binom(int n, int k)
Then i began to work on the recursive method. I can not use any class variable for printing - so I can not use a vector. I can not have any object, the class the methods are in, the two methods and main are the only methods I can implement. The biggest problem is that I can not save the variables that binom should use because they reset after each iteration. Now I have this code for printPascal:
if (n < 0) {
return;
}
printPascal(n - 1);
for (int k = 0; k <= n; k++) {
System.out.format("%6d", binom(n, k));
}
System.out.println();
Is there a way to make the method above more recursive - is there a way to take away the for-loop?