In the two-dimensional array learning of java basic grammar, we will come into contact with Yang Hui's triangle. Let's take a look at the realization process of Yang Hui's triangle.
/*
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
规律
1.第一行有1个元素,第n行有n行元素
2.每一行的第一个元素和最后一个元素都是1
3.从第三行开始,对于非第一个元素和最后一个元素的元素的值 arr[i][j]
arr[i][j] = arr[i-1][j] + arr[i-1][j-1]
*/
public class yanghui {
public static void main(String[] args) {
int[][] arr = new int[10][];
//遍历arr的每一个元素
for (int i = 0; i < arr.length; i++) {
//给每个一维数组开空间
arr[i] = new int[i + 1];
//遍历给每个一维数组赋值
for (int j = 0; j < arr[i].length; j++) {
//对应规律2
if(j == 0 || j == arr[i].length - 1){
arr[i][j] = 1;
}else {
//对应规律3
arr[i][j] = arr[i-1][j] + arr[i-1][j-1];
}
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
The 10-row Yang Hui triangle is as follows: