fork download
  1. #include <stdio.h>
  2.  
  3. void spiral(int n,int m,int arr[][m])
  4. {
  5. int top = 0,
  6. right = m - 1,
  7. bottom = n - 1,
  8. left = 0,
  9. k;
  10.  
  11. while( top <= bottom && left <= right )
  12. {
  13. //print top row
  14. for ( k = left; k <= right; k++ )
  15. {
  16. printf("%d ",arr[top][k]);
  17. }
  18. ++top;
  19.  
  20. //print right column
  21. for( k = top; k <= bottom; k++ )
  22. {
  23. printf("%d ",arr[k][right]);
  24. }
  25. --right;
  26.  
  27. //print bottom row
  28. for( k = right; k >= left; k-- )
  29. {
  30. printf("%d ",arr[bottom][k]);
  31. }
  32. --bottom;
  33.  
  34. //print left column
  35. for( k = bottom; k >= top; k-- )
  36. // this was wrong ^^^^^^ in OP's code
  37. {
  38. printf("%d ",arr[k][left]);
  39. }
  40. ++left;
  41. }
  42. }
  43.  
  44. int main(void) {
  45. int rows = 4, cols = 5;
  46. int board[rows][cols];
  47.  
  48. printf("Original:\n");
  49. for ( int i = 0; i < rows; ++i ) {
  50. for ( int j = 0; j < cols; ++j ) {
  51. board[i][j] = 1 + i*cols + j;
  52. printf("%d ", board[i][j]);
  53. }
  54. printf("\n");
  55. }
  56. printf("\nSpiral printing:\n");
  57. spiral(rows,cols,board);
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 2112KB
stdin
Standard input is empty
stdout
Original:
1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 

Spiral printing:
1  2  3  4  5  10   15   20   19   18   17   16   11   6   7  8  9  14   13   12