c语言蛇形数组 。定义一函数,输入参数为整数 ,要求当 5 时,打印出如下格式的“蛇形矩阵”数据

定义一函数,输入参数为整数 ,要求当 5 时,打印出如下格式的“蛇形矩阵”数据

输入蛇形数组的维数:5
 1  2  6  7 15
 3  5  8 14 16
 4  9 13 17 22
10 12 18 21 23
11 19 20 24 25

#include<stdio.h>

int main() {
	int i, j, x, y, a[10][10], n, situation;
	int v = 0;  // 每个数的值
	printf("输入蛇形数组的维数:");
	scanf("%d", &n);
	for (i = 0; i <= 2 * n - 1; i++) {
		if (i % 2 == 1) {
			x = i - 1;
			y = 0;
			situation = -1;  
		} else {
			x = 0;
			y = i - 1;
			situation = 1; 
		}
		while (x >= 0 && y >= 0) {
			if (x < n && y < n) {
				v++;
				a[x][y] = v;
			}
			
			x += situation;
			y -= situation;
		}
	}
	// 开始打印
	for (i = 0; i < n; i++) {
		for (j = 0; j < n; j++) {
			printf("%2d ", a[i][j]);  
		}
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_62088638/article/details/134981621