Answer to Question #288684 in C for Bryan

Question #288684

A c program to fill an N x N two-dimensional array, in a circular (Spiral) pattern. The numbers to be filled increments by 1.

1
Expert's answer
2022-01-19T10:36:07-0500
#include <iostream>


#define R 3
#define C 6


void spiralFill(int m, int n, int a[R][C])
{
    int i, k = 0, l = 0;
    int x = 0;


    while (k < m && l < n) {
        for (i = l; i < n; ++i) {
            a[k][i] = x++;
        }
        k++;


        for (i = k; i < m; ++i) {
            a[i][n - 1] = x++;
        }
        n--;


    
        if (k < m) {
            for (i = n - 1; i >= l; --i) {
                a[m - 1][i] = x++;
            }
            m--;
        }




        if (l < n) {
            for (i = m - 1; i >= k; --i) {
                a[i][l] = x++;
            }
            l++;
        }
    }
}


void print(int a[R][C])
{
    for (int i = 0; i != R; ++i)
    {
        for (int j = 0; j != C; ++j)
        {
            std::cout << a[i][j] << '\t';
        }
        std::cout << std::endl;
    }
}


int main()
{
    int a[R][C] = { { 1, 2, 3, 4, 5, 6 },
                    { 7, 8, 9, 10, 11, 12 },
                    { 13, 14, 15, 16, 17, 18 } };


    spiralFill(R, C, a);
    print(a);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS