Asterisk Triangle
Print a triangle composed of asterisks using Java.
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
for(int j = 5; j >= i; j--) {
System.out.print(" ");
}
for(int j = 1; j <= i; j++) {
System.out.print("*");
}
for(int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
The first nested loop outputs the spaces before the triangle. The second nested loop prints the left half of the triangle (including the middle column when j <= i). The third nested loop prints the right half (excluding the first row because j < i).
Pascal's Triangle
Printing Pascal's triangle is similar to printing an asterisk triangle. You need to understand the basic algorithm: the numbers on the left and right edges are always 1 (except the first row). Staritng from the third row, each interior number is the sum of the number above it and the number above and to the left. This can be easily implemented with a 2D array: arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
public static void main(String[] args) {
int[][] arr = new int[5][5];
for (int i = 0; i < arr.length; i++) {
for(int j = arr.length; j >= i; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Output example (a 5-row Pascal's triangle) is shown in the image.