Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to print a given matrix in spiral form with C

1 Answer

0 votes
#include <stdio.h>

#define COLS 4
#define ROWS 4

void PrintMatrixInSpiralForm(int matrix[][COLS]) {
    int top = 0, bottom = COLS - 1;
    int left = 0, right = ROWS - 1;

    while (1) {
        if (left > right) {
            break;
        }

        // top row
        for (int i = left; i <= right; i++) {
            printf("%d ", matrix[top][i]);
        }
        printf("\n");
        top++; // next row

        if (top > bottom) {
            break;
        }

        // right column
        for (int i = top; i <= bottom; i++) {
            printf("%d ", matrix[i][right]);
        }
        printf("\n");
        right--; // previous column

        if (left > right) {
            break;
        }

        // bottom row
        for (int i = right; i >= left; i--) {
            printf("%d ", matrix[bottom][i]);
        }
        printf("\n");
        bottom--; // previous row

        if (top > bottom) {
            break;
        }

        // left column
        for (int i = bottom; i >= top; i--) {
            printf("%d ", matrix[i][left]);
        }
        printf("\n");
        left++; // next column
    }
}

int main()
{
    int matrix[ROWS][COLS] = { { 1,   2,  3,  4 },
                               { 5,   6,  7,  8 },
                               { 9,  10, 11, 12 },
                               { 13, 14, 15, 16 } };

    PrintMatrixInSpiralForm(matrix);
}




/*
run:

1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10

*/

 



answered Sep 13, 2022 by avibootz
edited Sep 13, 2022 by avibootz

Related questions

1 answer 90 views
1 answer 72 views
1 answer 76 views
1 answer 75 views
1 answer 90 views
1 answer 100 views
1 answer 95 views
...