首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在c中打印环形输出?

如何在c中打印环形输出?
EN

Stack Overflow用户
提问于 2015-02-22 15:00:50
回答 2查看 108关注 0票数 0

我有c程序问题来打印环形输出。

当用户输入数字5时,程序输出如下所示;

代码语言:javascript
复制
1     2      3     4    5
16    17    18    19    6
15    24    25    20    7
14    23    22    21    8
13    12    11    10    9

我使用以下逻辑,但我真的失败了,我不知道。

代码语言:javascript
复制
 int main()
    {
        int a[50],i,j=0,n,k;
        printf("Enter the number=");
        scanf("%d",&n);

        for(i=1;i<=n;i++)
        {

            if(i>n)
            {
                j=j+5;
            }
            else if(i>((2*n)-1))
            {
                j--;
            }
            else if(i>((3*n)-2))
            {
                j=j-5;
            }
            else if(i>(4*n-4))
            {
                j++;
            }
        }
    }

很抱歉问了整个程序逻辑,但是,我真的不知道,请帮助我……

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-22 15:11:26

这是你要找的东西

代码语言:javascript
复制
#include <stdio.h>

#define max 25

int main()
{
    int spiral[max][max] = {{0}}; // initializing array with 0
    int r, c, i = 0, j = -1, count = 1;

    printf("\nEnter the row and column for spiral matrix:\n");
    scanf("%d%d", &r, &c);

    while (count <= r * c)  // this loop executes till all the blocks of
    {
        // array r*c are filled with 0
        while (j < c - 1) // Filling the location from left to right
        {
            // with value of variable count
            if(spiral[i][j+1]!=0)  // Here we are checking if that location
                break;                 // is already occupied
            spiral[i][++j] = count++;
        }

        while (i < r - 1)    // Filling the location from top to bottom
        {
            if (spiral[i+1][j] != 0)
                break;
            spiral[++i][j] = count++;
        }

        while (j > 0)     // Filling the location from right to left
        {
            if(spiral[i][j-1] != 0)
                break;
            spiral[i][--j] = count++;
        }

        while (i > 0)       // Filling the column from bottom to top
        {
            if (spiral[i-1][j] != 0)
                break;
            spiral[--i][j] = count++;
        }
    }

    for (i = 0 ; i < r ; i++)
    {
        for (j = 0 ; j < c ; j++)
        {
            printf("%3d",spiral[i][j]); // print the matrix
        }
        printf("\n");
    }
    return 0;
}

参考是这里有更多的细节

票数 0
EN

Stack Overflow用户

发布于 2015-02-22 15:09:33

解决这个问题的一个简单方法是分配一个大小为N*N的数组,并将其填充到螺旋后面的一个直线前向循环中。然后,可以打印每一行的数组内容N个元素。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28659300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档