给定一个大小为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编程中以蛇形模式打印矩阵的详细内容
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)