編程題-實現蛇形輸出

實現如下的蛇形輸出:

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 


具體代碼實現:

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3. int main()  
  4. {  
  5. int n;  
  6. int x,y,round;  
  7. //a[x][y],x是二維數組的第一個下標,y是二維數組的第二個下標,  
  8. //round是轉的圈數,從0開始。  
  9. int count = 1;//從1開始計數  
  10. printf("Please input a number:\n");  
  11. scanf("%d",&n);//用戶輸入n的值  
  12. int (*a)[n] = calloc(n * n,sizeof(int));//創建n*n的矩陣  
  13. for(round = 0; round < n / 2; round++)  
  14. {  
  15.     x = round;  
  16.     for(y = round; y < n - round; y++)  
  17.     {  
  18.         a[x][y] = count;  
  19.         count++;  
  20.     }  
  21.     //print  1,2,3,4,5  
  22.     y = n - round - 1;  
  23.     for(x = round + 1; x < n - round - 1; x++)  
  24.     {  
  25.         a[x][y] = count;  
  26.         count++;  
  27.     }  
  28.     //print 6,7,8  
  29.     x = n - round - 1;  
  30.     for(y = n - round - 1; y >= round; y--)  
  31.     {  
  32.         a[x][y] = count;  
  33.         count++;  
  34.     }  
  35.     //print 13,12,11,10,9  
  36.     y = round;  
  37.     for(x = n - round - 2; x > round; x--)  
  38.     {  
  39.         a[x][y] = count;  
  40.         count++;  
  41.     }  
  42.     //print 16,15,14  
  43. }  
  44.   if(n % 2 == 1)  
  45. {  
  46.     a[n / 2][n / 2] = n * n;  
  47. }  
  48. for(x = 0 ; x < n; x++)  
  49. {  
  50.     for(y = 0; y < n; y++)  
  51.     {  
  52.         printf(" %d ",a[x][y]);  
  53.     }  
  54.     printf("\n");  
  55. }  
  56. free(a);  
  57. return 0;  
  58. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章