打印杨辉三角
public static void main(String[] args) {
int[][] yangHui = new int[10][];
//2.给数组的元素赋值
for(int i = 0;i < yangHui.length;i++){
yangHui[i] = new int[i + 1];
//给首末元素赋值
yangHui[i][0] = yangHui[i][i] = 1;
//给每行的非首末元素赋值
for(int j = 1;j < yangHui[i].length - 1;j++){
yangHui[i][j] = yangHui[i-1][j-1] + yangHui[i-1][j];
}
}
//3.遍历二维数组
for(int i = 0;i < yangHui.length;i++){
for(int j = 0;j < yangHui[i].length;j++){
System.out.print(yangHui[i][j] + " ");
}
System.out.println();
}
}
打印回形数矩阵
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个数字");
int len = scanner.nextInt();
int[][] arr = new int[len][len];
int s = len * len;
/*
k = 1:向右 k = 2:向下 k = 3:向左 k = 4:向上
*/
int k = 1;
int i = 0,j = 0;
for (int m = 1;m <= s;m++){
if (k == 1){
if (j < len && arr[i][j] == 0){
arr[i][j++] = m;
}else {
k = 2;
i++;
j--;
m--;
}
}else if (k == 2){
if (i < len && arr[i][j] == 0){
arr[i++][j] = m;
}else {
k = 3;
i--;
j--;
m--;
}
}else if (k == 3){
if (j >= 0 && arr[i][j] == 0){
arr[i][j--] = m;
}else {
k = 4;
i--;
j++;
m--;
}
}else if (k == 4){
if (i >= 0 && arr[i][j] == 0){
arr[i--][j] = m;
}else {
k = 1;
i++;
j++;
m--;
}
}
}
for (int m = 0;m < arr.length;m++){
for (int n = 0;n < arr[m].length;n++){
System.out.print(arr[m][n]+"\t");
}
System.out.println();
}
}