Java Program Source Code to Print Pascal Triangle

Print a Pascal Triangle using Java Programming


Pascal's triangle is an array of triangle. This program will generate a pascal triangle like below
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

This can be done by using two dimensional array. Here I used array tri and I stored the result by using tri[r][c] = tri[r-1][c]+tri[r-1][c-1];

public class Triangle {
public static void main(String [] args) {
int [][] tri = new int[10][];
for (int r=0; r<tri.length; r++) {
tri[r] = new int[r+1];
tri[r][0] = 1;
tri[r][r] = 1;
for (int c=1; c<r; c++) {
tri[r][c] = tri[r-1][c]+tri[r-1][c-1];
}
}
for (int r=0; r<tri.length; r++) {
for (int c=0; c<tri[r].length; c++) {
System.out.print(" "+tri[r][c]);
}
System.out.println("");
}
}
}



Related Topic C Program to Print Pascal Triangle
Floyd's Triangle in Java Program
Java code for Processing XML file
Java Program to Check Armstrong Number
C Program to Print Floyd's triangle
Java  

nScraps.com 2011   Privacy Policy  Terms of Service  Feedback