首页 > 解决方案 > 如何在 C 中以顺时针方式扫描多维数组?

问题描述

我正在解决的问题

我的一位学生找到了我,他们正在做一个个人项目,我们目前都在学习 C,我们一直在做基础项目来加深我们的知识。

作为一名数学讲师,我的编码知识是有限的。

有人可以帮我解决我们最近一直在处理的这个问题,并附上一些小评论。您的帮助将不胜感激。

PS附上问题的图片。

这是我设法编写的代码

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

/*QUESTION 1*/

/*Initialise Array*/
int
main (void)
{
  srand ((int) time (NULL));
  int Area_Zone[15][15], Area_Zone2[15][15], i, j, k, l;
  for (i = 0; i < 15; i++)
  {
    for (j = 0; j < 15; j++)
    /* Display the multidimensional array */
    {
      Area_Zone[i][j] = rand () % 3;
      printf ("%d\t", Area_Zone[i][j]);
    }
    printf ("\n");
  }
  for (i = 0; i < 1; i++)
  {
    for (j = 0; j < 1; j++)
      return 0;
  }
}
/*QUESTION 2*/

// C program to print the array in a
// spiral form-                       

//This is code I had to scripkiddie which seemed similar to my application
 
#include <stdio.h>
#include <chplot.h>
#include <math.h>

#define R 3
#define C 6
 
void ClockwisePrint(int m, int n, int a[R][C])
{
    int i, k = 0, l = 0;
 
    /*  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator
    */
 
    while (k < m && l < n) {
        /* Print the first row from the remaining rows */
        for (i = l; i < n; ++i) {
            printf("%d ", a[k][i]);
        }
        k++;
 
        /* Print the last column from the remaining columns
         */
        for (i = k; i < m; ++i) {
            printf("%d ", a[i][n - 1]);
        }
        n--;
 
        /* Print the last row from the remaining rows */
        if (k < m) {
            for (i = n - 1; i >= l; --i) {
                printf("%d ", a[m - 1][i]);
            }
            m--;
        }
 
        /* Print the first column from the remaining columns
         */
        if (l < n) {
            for (i = m - 1; i >= k; --i) {
                printf("%d ", a[i][l]);
            }
            l++;
        }
    }
}
 
/* Driver Code */
int main()
{
    int a[R][C] = { { 1, 2, 3, 4, 5, 6 },
                    { 7, 8, 9, 10, 11, 12 },
                    { 13, 14, 15, 16, 17, 18 } };
     
    // Function Call
    spiralPrint(R, C, a);
    return 0;
}

标签: cfor-loopmultidimensional-arrayscanf

解决方案


推荐阅读