Last active
August 29, 2015 14:12
-
-
Save RussellAndrewEdson/9812e9c88c75c22dc190 to your computer and use it in GitHub Desktop.
Java code for Pascal's Triangle.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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