I am trying to create Pascal's Triangle, and the line:
return pascalTriangle(row-1, col-1) + pascalTriangle(row-1, col);
in the recursive method that returns int
values in the Pascal's triangle, causes
Exception in thread "main" java.lang.StackOverflowError
It only prints one row 1
, then throws exception for other rows. What do I need to fix so it doesn't throw any exception, and forms the Pascal's triangle? Here's my code:
import java.util.Scanner;
/**
* This program takes n input from the user, and forms
* Pascal's Triangle in n number of rows that the user entered.
*/
public class DD_PascalsTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
// the number of rows created in the Pascal's Triangle
int n = scanner.nextInt();
// print Pascal's Triangle
printTriangle(n);
}
/**
* @param row rows in Pascal's Triangle
* @param col columns in Pascal's Triangle
* @return values in the Pascal's Triangle
*/
private static int pascalTriangle(int row, int col) {
if (col == 0 || col == row)
// base case
return 1;
else
// create the values in Pascal's Triangle
return pascalTriangle(row-1, col-1) + pascalTriangle(row-1, col);
}
/**
* @param n the input from the user, aka the n
* number of rows in Pascal's Triangle
*/
private static void printTriangle(int n) {
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
System.out.println(pascalTriangle(row, col) + " ");
}
System.out.println();
}
}
}