fork download
  1. #include <stdio.h>
  2.  
  3. #define N 5
  4.  
  5. int main(void) {
  6. int i,j,dim, val = 1;
  7. int matrix[N][N];
  8.  
  9. // perform spiral print
  10. for (dim = 0; dim < (N+1)/2; dim++)
  11. {
  12. // set initial i and go till the "last column"
  13. i = dim;
  14. for (j = dim; j < N - dim; j++)
  15. {
  16. matrix[i][j] = val++;
  17. }
  18.  
  19. // bring back i and j to the proper coordinate
  20. // and move down to the "last row"
  21. j--;i++;
  22. for (; i < N - dim; i++)
  23. {
  24. matrix[i][j] = val++;
  25. }
  26.  
  27. // bring back i and j to the proper coordinate
  28. // and move back to the "first column"
  29. i--;j--;
  30. for (; j >= dim; j--)
  31. {
  32. matrix[i][j] = val++;
  33. }
  34.  
  35. // bring back i and j to the proper coordinate
  36. // and move up to the "first row"
  37. j++;i--;
  38. for (; i > dim; i--)
  39. {
  40. matrix[i][j] = val++;
  41. }
  42. }
  43.  
  44. // init and print the matrix
  45. for (i=0; i < N; i++)
  46. {
  47. for (j=0; j< N; j++)
  48. {
  49. printf("%2d ", matrix[i][j]);
  50. }
  51. printf("\n");
  52. }
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
 1  2  3  4  5 
16 17 18 19  6 
15 24 25 20  7 
14 23 22 21  8 
13 12 11 10  9