在C编程中以蛇形模式打印矩阵

来自:互联网
时间:2023-09-06
阅读:

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

在C编程中以蛇形模式打印矩阵

示例

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编程中以蛇形模式打印矩阵的详细内容

返回顶部
顶部