As follows:
First we look at the picture up and down is symmetrical, we first to print the upper part,
1. Use a For loop to do the outer loop control the number of columns printed
for (int i =0;i<10;i++) {//Print 10 columns
} 2. Also use 2 for loop to print the inner space and * for (int j = 0;j<10-j;j++) {//Print space, no line break System.out.print ("")} When a space is printed without wrapping, then printing * can only be placed back face for (int k = 0;k<2*i;k++) {//print "*" System.out.print ("*") The complete code is as follows: for (int i=1;i<10;i++) { for (int j = 1; j<10-i;j++) {//Print space System.out.prin T (""); } for (int k = 1;k<2*i;k++) {//print "*" System.out.print ("*"); } System.out.println ();//print a line after wrapping} This code is printed as follows:
3.接下来写下半角,思路和上半角一样,只是循环的条件变了而已 直接上代码: for(int i=1;i<10;i++) { for(int k = 0;k<i;k++) { System.out.print(" "); } for(int j = 1;j<18-2*i;j++) { System.out.print("*"); } System.out.println(); } :
ok,现在只要将代码拼接就可以了。 完整代码如下: public class PascalTriangle {public static void main(String[] args) { for(int i=1;i<10;i++) { for(int j = 1 ;j<10-i;j++) { System.out.print(" "); } for(int k = 1;k<2*i;k++) { System.out.print("*"); } System.out.println(); } for(int i=1;i<10;i++) { for(int k = 0;k<i;k++) { System.out.print(" "); } for(int j = 1;j<18-2*i;j++) { System.out.print("*"); } System.out.println();}
}
}
The main idea of this topic is to use the loop to print space and *, and then use the conditions to limit the number.
Java algorithm print Yang Hui triangle