fork download
  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. while (true)
  8. {
  9. Console.Write("Enter number of rows/columns: ");
  10. int input;
  11. bool isNumber = int.TryParse(Console.ReadLine(), out input);
  12.  
  13. if (!isNumber)
  14. {
  15. return;
  16. } int[,] array = new int[input, input];
  17.  
  18. int iterator = 0;
  19. int row = 0;
  20. int col = 0;
  21. int step = 1;
  22. for (int num = 1; num <= input * input; num++)
  23. {
  24. array[row, col] = num;
  25.  
  26. switch (step)
  27. {
  28. case 1:
  29. if (col == (input - iterator - 1))
  30. {
  31. row++;
  32. step++;
  33. }
  34. else
  35. {
  36. col++;
  37. }
  38. break;
  39.  
  40. case 2:
  41. if (row == (input - iterator - 1))
  42. {
  43. col--;
  44. step++;
  45. }
  46. else
  47. {
  48. row++;
  49. }
  50.  
  51. break;
  52.  
  53. case 3:
  54. if (col == (0 + iterator))
  55. {
  56. row--;
  57. step++;
  58. }
  59. else
  60. {
  61. col--;
  62. }
  63. break;
  64.  
  65. case 4:
  66. if (row == (1 + iterator))
  67. {
  68. col++;
  69. step = 1;
  70. iterator++;
  71. }
  72. else
  73. {
  74. row--;
  75. }
  76. break;
  77. }
  78. }
  79. ShowGrid(array);
  80. }
  81. }
  82.  
  83. public static void ShowGrid(int[,] array)
  84. {
  85. int rowLength = array.GetLength(0);
  86. int colLength = array.GetLength(1);
  87.  
  88. Console.WriteLine();
  89. for (int i = 0; i < rowLength; i++)
  90. {
  91. for (int j = 0; j < colLength; j++)
  92. {
  93. Console.Write(string.Format("{0}\t", array[i, j]));
  94. }
  95. Console.Write(Environment.NewLine + Environment.NewLine);
  96. }
  97. Console.WriteLine();
  98. }
  99. }
Success #stdin #stdout 0.01s 131648KB
stdin
 4
 5
 6
 quit
stdout
Enter number of rows/columns: 
1	2	3	4	

12	13	14	5	

11	16	15	6	

10	9	8	7	


Enter number of rows/columns: 
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	


Enter number of rows/columns: 
1	2	3	4	5	6	

20	21	22	23	24	7	

19	32	33	34	25	8	

18	31	36	35	26	9	

17	30	29	28	27	10	

16	15	14	13	12	11	


Enter number of rows/columns: