Java USES a for loop to output the Yang hui triangle
- 2020-04-01 03:00:39
- OfStack
The idea is to create an integer two-dimensional array with 10 one-dimensional arrays. Use a double-layer loop to initialize the size of each second-level array in the outer loop. In the inner loop, the array elements on both sides are first assigned a value of 1, the other values are calculated by the formula, and then the array elements are output.
public class YanghuiTriangle {
public static void main(String[] args) {
int triangle[][]=new int[10][];//Create a two-dimensional array
//Traverses the first layer of a two-dimensional array
for (int i = 0; i < triangle.length; i++) {
triangle[i]=new int[i+1];//Initializes the size of the second level array
//Iterate through the second level array
for(int j=0;j<=i;j++){
//Assign the array elements on both sides to 1
if(i==0||j==0||j==i){
triangle[i][j]=1;
}else{//Other values are calculated by formula
triangle[i][j]=triangle[i-1][j]+triangle[i-1][j-1];
}
System.out.print(triangle[i][j]+"t"); //Output array element
}
System.out.println(); //A newline
}
}
}