Search This Blog

Spiral Matrix Program in C - Zoho Interview Question - C Program to Read a Matrix in Spiral Order

A spiral matrix is a matrix (two dimensional array) in which the elements are stored in spiral manner. The order of accessing elements in the spiral matrix resembles a spiral. Actually it is a normal NxN two dimensional array. But instead of accessing elements row-wise or column-wise, we access them in spiral order. i.e, in a 3x3 matrix the order of retrieval of elements is spiral order is as follows:

(0,0)  (0,1)   (0,2)  (1,2)   (2,2)   (2,1)   (2,0)   (1,0)   (1,1)

The following picture shows a 4x4 spiral matrix:
4x4 spiral matrix using two dimensional array - C Program for spiral matrix
A 4x4 Spiral matrix

Zoho, an IT company, asked an interview question which was to write a program to read a matrix spirally. In this post, we will answer this interview question  by zoho corporation. The only difference between spiral matrix and normal matrix is the order in which we store elements to matrix or access elements in matrix. The following is the C program to read a spiral matrix.

#include<stdio.h>
void main()
{
int a[10][10],o,cellcount,cc=0,c=0,i=0,j=0,g=1;
printf("\nEnter the order of spiral matrix: ");
scanf("%d",&o);
cellcount=o;
printf("\nEnter the elements:\n");
while(c<o*o)
    {
    cc=0;
    for(;cc<cellcount;j=j+g,cc++)
        scanf("%d",&a[i][j]);
    j=j-g;
    c+=cc;
    cc=0;
    i=i+g;
    cellcount--;
    if(c>=o*o)
        break;
    for(;cc<cellcount;i=i+g,cc++)
        scanf("%d",&a[i][j]);
    c+=cc;
    i=i-g;
    j=j-g;
    g*=-1;
    }
printf("\nThe spiral matrix is:");
for(i=0;i<o;i++)
    {
    printf("\n");
    for(j=0;j<o;j++)
        printf("%d\t",a[i][j]);
    }
}
The above program reads the matrix in spiral fashion and the displays the matrix in normal way. You can use this code not only to read and store the elements in matrix spirally but also to access the elements in the matrix in spiral order.

Related Posts:

C Compiler for Android Phones
C Program to Validate Sudoku - Check Correctness of Sudoku
C Program to Display Pascal's Triangle
C Program to Burst Consecutive Repetition of Numbers in Array
C Program to Display Strings Crossed
Tricky Interview Question - C Program to Rearrange an Array Without Using any Other Arrays
C Program to Convert Between Decimal, Binary, Hexadecimal and Octal Number Systems
C Program to Find Inverse of a Matrix
C Program to Find Largest Integer Formed Using Digits of Given Number
C Program to Count GrandChildren - Interview Question
How to get Random Number in C
C Program to Implement Circular Linked List
C Program to Swap Numbers with Bitwise Operators
C Program for Subtraction Without Using Minus Operator
C Program to Swap Numbers without Temporary Variable

1 comment:

iampk said...

Nice approach. Thank you