Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Name: spiralprinting.c
- Copyright:
- Author: Mr.Kindle
- Date: 25-11-22 00:30
- Description: A matrix is dynamically allocated and its value is being printed spirally in clock-vise direction.
- */
- #include<stdio.h>
- #include<malloc.h>
- void print_spiral(int *array, int row,int col);
- int main()
- { int i,j,row,col;
- int * array;
- srand(time(0));//for random generation of numbers
- printf("\nEnter row and col of matrix: ");
- scanf("%d %d",&row,&col);
- /*dynamically allocating the space for matrix*/
- array = calloc(row * col, sizeof(int));
- printf("\nAutomatically generated matrix of dimension %d * %d is following: \n",row,col);
- for(i=0;i<row;i++)
- for(j=0;j<col;j++)
- array[i*col + j] = rand()%20 + 1;
- /*DISPLAY array*/
- for(i=0;i<row;i++)
- {
- for(j=0;j<col;j++)
- printf("%-2d ",array[i* col + j]);
- printf("\n");
- }
- printf("\nSpiral printing of the matrix is: \n");
- print_spiral(array,row,col);
- free(array);
- return 0;
- }//main
- void print_spiral(int *array, int row, int col)
- {
- int r = row, c = col;//so that row and col doesnot changed
- /*since array is dynamically allocated so in order to access its element 'col' value required so cannot
- change it hence taking 'c' and assigning 'col' value to it and making all changes in 'c'*/
- int rownow = 0, colnow = 0,i;
- /*each time while loop iterated the value of 'r' and 'c' decreased by '1' and the value of 'rownow' and
- 'colnow' incresed by '1'. Hence the difference between 'c' and 'colnow' or 'r' and'rownow' decrease by 2*/
- while(rownow < r && colnow < c)
- {
- /*print the first row from left to right*/
- for(i = colnow; i< c; i++)
- printf("%d ",array[rownow * col + i]);
- rownow++; r--;
- /*print the last column from top to bottom*/
- for(i=rownow;i<=r;i++)
- printf("%d ",array[i * col+ (c - 1)]);
- c--;
- /*print the last row from right to left*/
- for(i=c-1;i>=colnow;i--)
- printf("%d ",array[r * col + i]);
- /*print the first column from bottom to top*/
- //if(rown > colnow)
- for(i=r-1;i>=rownow;i--)
- printf("%d ",array[i * col + colnow]);
- colnow++;
- }
- }//end of print_spiral
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement