给定一个大小为nxn的数组,程序必须以蛇形模式打印数组的元素,而不对它们的原始位置进行任何更改

Input: arr[]= 100 99 98 97 93 94 95 96 92 91 90 89 85 86 87 88 Output: 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85
该程序将遍历矩阵的每一行,并检查奇偶行。
如果行是偶数行,它将从左到右打印该行的元素
如果行是奇数行,它将从右到左打印该行的元素
START
Step 1 -> create header files for declaring rows and column let’s say of size 4x4
Step 2 -> declare initial variables i and j and array[][] with elements
Step 3 -> Loop For i=0 and i<M and i++
IF i%2==0
Loop For j=0 and j<N and j++
Print arr[i][j]
End
End
Else
Loop For j=N-1 and j>=0 and j—
Print arr[i][j]
End
End
STOP演示
#include<stdio.h>
#define M 4
#define N 4
int main() {
int i,j;
int arr[M][N] = {
{ 100, 99, 98, 97 },
{ 93, 94, 95, 96 },
{ 92, 91, 90, 89 },
{ 85, 86, 87, 88 }
};
for (i = 0; i < M; i++) { //for rows
if (i % 2 == 0) {
for (j = 0; j < N; j++) // for column
printf("%d ",arr[i][j]);
} else{
for (j = N - 1; j >= 0; j--)
printf("%d ",arr[i][j]);
}
}
return 0;
}如果我们运行上面的程序,它将生成以下输出
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85
以上就是在C编程中以蛇形模式打印矩阵的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号