/* A matrix demo for the Pascal Triangle Dan Warner 9/7/2000 */ import java.awt.*; import java.applet.Applet; public class PascalTriangle extends Applet { int[][] pascalTri = new int[12][]; public void init() { //populate matrix for (int i = 0; i < pascalTri.length; i++) { pascalTri[i] = new int[i+1]; //create sub-array pascalTri[i][0] = 1; for (int j = 1; j < (pascalTri[i].length - 1); j++) { pascalTri[i][j] = pascalTri[i-1][j-1] + pascalTri[i-1][j]; } pascalTri[i][i] = 1; } repaint(); } public void paint( Graphics g ) { String line; // Color the background g.setColor(Color.cyan); g.fillRect(0, 0, 430, 250); // Draw the title g.setColor(Color.red); Font myFont = new Font("Helvetica", Font.BOLD, 24); g.setFont(myFont); g.drawString( "Pascal's Triangle", 40, 25 ); // Display the matrix myFont = new Font("Courier", Font.PLAIN, 14); g.setFont(myFont); for (int i = 0; i < pascalTri.length; i++) { line = " "; for (int j = 0; j < pascalTri[i].length; j++) { if (pascalTri[i][j] < 10) { line += " " + pascalTri[i][j]; } else if (pascalTri[i][j] < 100) { line += " " + pascalTri[i][j]; } else { line += " " + pascalTri[i][j]; } } g.drawString( line, 10, 50+i*15 ); } } }