Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Last active August 29, 2015 14:12
Show Gist options
  • Save RussellAndrewEdson/9812e9c88c75c22dc190 to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/9812e9c88c75c22dc190 to your computer and use it in GitHub Desktop.
Java code for Pascal's Triangle.
public class PascalsTriangle {
private int[][] triangle;
/* Creates a new PascalsTriangle representation with n rows. */
public PascalsTriangle(int n) {
triangle = new int[n][n];
// The first column is all 1's.
for (int i = 0; i < n; i++) {
triangle[i][0] = 1;
}
// We fill in the rest by summing the two elements above.
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
triangle[i][j] = triangle[i-1][j] + triangle[i-1][j-1];
}
}
}
public void print() {
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
PascalsTriangle pascal = new PascalsTriangle(5);
pascal.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment