I was just stumped on this programming challenge for my Java class, and could not find help anywhere that only uses recursion with no loops. So after hours of pain here it is. All it needs is a main method or demo class to create an instance of this PascalsTriangle
class and initialize it with the number of rows.
public class PascalsTriangle {
private StringBuilder str; // StringBuilder to display triangle
/**
* Starts the process of printing the Pascals Triangle
* @param rows Number of rows to print
*/
public PascalsTriangle(int rows) {
str = new StringBuilder();
printTriangle(rows, str);
}
/**
* Uses recursion to function as an "outer loop" and calls
* itself once for each row in triangle. Then displays the result
* @param row The number of the row to generate
* @param str StringBuilder to insert each row into
*/
public static void printTriangle(int row, StringBuilder str) {
// calls itself until row equals -1
if (row >= 0) {
// calls lower function to generate row and inserts the result into front of StringBuilder
str.insert(0, getRow(row, 0) + "\n");
// calls itself with a decremented row number
printTriangle(row - 1, str);
} else {
// when the base case is reached - display the result
JOptionPane.showMessageDialog(null, str);
System.exit(0);
}
}
/**
* Uses recursion to act as the "inner loop" and calculate each number in the given row
* @param rowNumber Number of the row being generated
* @param elementNumber Number of the element within the row (always starts with 0)
* @return String containing full row of numbers or empty string when base case is reached
*/
public static String getRow(int rowNumber, int elementNumber) {
// calls itself until elementNumber is greater than rowNumber
if (elementNumber <= rowNumber) {
// calculates element using combinations formula: n!/r!(n-r)!
int element = fact(rowNumber) / (fact(elementNumber) * (fact(rowNumber - elementNumber)));
// calls itself for each element in row and returns full String
return element + " " + getRow(rowNumber, elementNumber + 1);
} else return "";
}
/**
* Helper function that uses recursion to calculate factorial of given integer
* @param n Number to calculate factorial
* @return Factorial
*/
public static int fact(int n) {
if (n <= 0)
return 1;
else
return n * fact(n - 1);
}