Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created February 21, 2016 17:51
Show Gist options
  • Save gabhi/775acb896107de99f245 to your computer and use it in GitHub Desktop.
Save gabhi/775acb896107de99f245 to your computer and use it in GitHub Desktop.
Generating Pascal's triangle using recursion
import java.util.Scanner;
public class PascalTriangle {
public static void print(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(pascal(i, j) + " ");
}
System.out.println();
}
}
public static int pascal(int i, int j) {
if (j == 0) {
return 1;
} else if (j == i) {
return 1;
} else {
return pascal(i - 1, j - 1) + pascal(i - 1, j);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the row number upto which Pascal's triangle has to be printed: ");
int row = scanner.nextInt();
print(row);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment