Skip to content

Instantly share code, notes, and snippets.

@bytecodeman bytecodeman/PascalTriangle.java Secret
Last active Nov 24, 2019

Embed
What would you like to do?
CSC-111 Two Dimensional Array Example
public class PascalTriangle {
public static void main(String args[]) {
int pt[][] = new int[10][10];
generateTriangle(pt);
printTriangle(pt);
}
private static void generateTriangle(int x[][]) {
for (int row = 0; row < x.length; row++) {
x[row][0] = 1;
x[row][row] = 1;
for (int col = 1; col < row; col++)
x[row][col] = x[row-1][col-1] + x[row-1][col];
}
}
private static void printTriangle(int x[][]) {
for (int row = 0; row < x.length; row++) {
for (int col = 0; col <= row; col++)
System.out.printf("%6d", x[row][col]);
System.out.println();
}
}
}
public class PascalTriangle2 {
public static void main(String args[]) {
int pt[][] = generateTriangle();
printTriangle(pt);
}
private static int[][] generateTriangle() {
int x[][] = new int[10][10];
for (int row = 0; row < x.length; row++) {
x[row][0] = 1;
x[row][row] = 1;
for (int col = 1; col < row; col++)
x[row][col] = x[row-1][col-1] + x[row-1][col];
}
return x;
}
private static void printTriangle(int x[][]) {
for (int row = 0; row < x.length; row++) {
for (int col = 0; col <= row; col++)
System.out.printf("%6d", x[row][col]);
System.out.println();
}
}
}
public class PascalTriangle3 {
public static void main(String args[]) {
int pt[][];
pt = initStructure(10);
generateTriangle(pt);
printTriangle(pt);
}
private static int[][] initStructure(int size) {
int x[][] = new int[size][];
for (int i = 0; i < size; i++)
x[i] = new int[i+1];
return x;
}
private static void generateTriangle(int x[][]) {
for (int row = 0; row < x.length; row++) {
x[row][0] = 1;
x[row][row] = 1;
for (int col = 1; col < row; col++)
x[row][col] = x[row-1][col-1] + x[row-1][col];
}
}
private static void printTriangle(int x[][]) {
for (int row = 0; row < x.length; row++) {
for (int col = 0; col <= row; col++)
System.out.printf("%6d", x[row][col]);
System.out.println();
}
}
}
public class TwoDArrayExample {
private static int[][] initMatrix(int numRows, int numCols) {
int x[][] = new int[numRows][numCols];
for (int i = 0; i < x.length; i++)
for (int j = 0; j < x[i].length; j++)
x[i][j] = (int) (100 * Math.random()) + 1;
return x;
}
private static void printMatrix(int[][] x) {
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++)
System.out.printf("%5d", x[i][j]);
System.out.println();
}
}
private static int biggest(int numbs[][]) {
int largest = numbs[0][0];
for (int i = 0; i < numbs.length; i++)
for (int j = 0; j < numbs[i].length; j++)
if (numbs[i][j] > largest)
largest = numbs[i][j];
return largest;
}
public static void main(String args[]) {
int x[][] = initMatrix(10, 8);
printMatrix(x);
System.out.printf("Biggest Number in Array = %d\n", biggest(x));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.