C Program to Traverse Matrix Helically

Write C Program to Traverse Matrix Helically

// C Program to Traverse Matrix Helically

#include <stdio.h>
#include <math.h>

int main()
{
	int A[3][3] = {{1, 2, 0}, {4, 0, 6}, {7, 8, 0} };

	int top, bottom, left, right, dir, i, j;
	int row = sizeof(A) / sizeof(A[0]);
	int column = sizeof(A[0]) / sizeof(A[0][0]);

	printf("Matrix A :--> \n");
	for(i = 0;i < 3; i++)
	{
		for( j = 0; j < 3; j++)
		{
			printf("%d  ", A[i][j]);
		}
		printf("\n");
	}


	top = 0;
	bottom = row - 1;
	left = 0;
	right = column - 1;
	dir = 0;


	printf("\n\nPrinting Matrix Helically :--> ");
	while(top <= bottom && left <= right)
	{
		if(dir == 0)         //for moving right
		{
			for(i = left;i <= right;i++)
				printf("%d ", A[top][i]);
			top++;

		}
		else if(dir == 1)   //for moving down
		{
				for(i = top;i <= bottom; i++)
					printf("%d ", A[i][right]);
				right--;

		}
		else if(dir == 2)		//for moving left
		{
				for(i = right;i >=  left; i--)
					printf("%d ", A[bottom][i]);
				bottom--;

		}

        else if(dir == 3)		//for moving up
		{
				for(i = bottom;i >= top; i--)
					printf("%d ", A[i][left]);
				left++;

		}
		dir = (dir + 1 ) % 4;
		printf(" ");

    }
    return 0;
}

Output:

Matrix A :-->
1  2  0
4  0  6
7  8  0


Printing Matrix Helically :--> 1 2 0  6 0  8 7  4  0

≪ Previous | Next ≫