2014-11-23 28 views
-3

最近,我遇到了一個問題,要求我編寫一個動態代碼,以zigzag模式打印n x n矩陣。請幫我用下面的代碼來獲得輸出。程序代碼之字形矩陣

輸出:

rows: 5 
cols: 5 

1 2 3 4 5 

10 9 8 7 6 

11 12 13 14 15 

20 19 18 17 16 

21 22 23 24 25 

,我到目前爲止已經試過的代碼是靜態的:

#include <stdio.h> 

int main(){ 

int arr[3][3]={1,2,3, 
     4,5,6, 
     7,8,9}; 

int i, j, k; 

for(i=0; i<3; i++){ 
    printf("%d",arr[0][i]); 
} 
    printf("\n"); 
for(j=2; j>=0; j--){ 
    printf("%d",arr[1][j]); 
} 
printf("\n"); 
for(k=0; k<3; k++){ 
    printf("%d",arr[2][k]); 
} 
printf("\n"); 
return 0; 

} 

現在,我希望同樣的事情與用戶說明行和列完成數組..

回答

2

這應該爲你工作:

#include <stdio.h> 

int main() { 

    int rows, columns; 
    int rowCount, columnCount, count = 0; 

    printf("Please enter rows and columns:\n>"); 
    scanf("%d %d", &rows, &columns); 


    for(rowCount = 0; rowCount < rows; rowCount++) { 

     for(columnCount = 1; columnCount <= columns; columnCount++) { 

      if(count % 2 == 0) 
       printf("%4d " , (columnCount+(rowCount*columns))); 
      else 
       printf("%4d " , ((rowCount+1)*columns)-columnCount+1);  

     } 
     count++; 
     printf("\n"); 
    } 


    return 0; 

} 

輸入:

5 5 

輸出:

1 2 3 4 5 
10 9 8 7 6 
11 12 13 14 15 
20 19 18 17 16 
21 22 23 24 25 
+0

非常感謝。你有很大的幫助.. – Android7 2014-11-25 07:37:51

+0

@ Android7歡迎您!祝你有個美好的一天:D – Rizier123 2014-11-25 07:38:23

+0

該程序對於5x5矩陣運行得非常好。但是當我嘗試運行3x3或4x4矩陣時,結果是不同的。它會跳過一些串聯的數字,同時以鋸齒形模式輸出矩陣。 – Android7 2014-11-25 07:56:19

0

簡單動態邏輯與ķ可變

#include <stdio.h> 

int main() { 

    int i,j,k=1,row,col; 

    printf("Enter row and col \n>"); 
    scanf("%d %d", &row, &col); 

    for (i = 1; i <=row; i++) 
     { 
      for (j = 1; j <=col; j++) 
      { 
       if(i%2==0) k--; 

       printf("%4d",k); // it have to be in center of both condition 

       if(i%2!=0) k++; 
      } 
      k=k+col; 
      printf("\n"); 

     } 
    return 0; 
} 

輸入:

7 7 

輸出:

1 2 3 4 5 6 7 
    14 13 12 11 10 9 8 
    15 16 17 18 19 20 21 
    28 27 26 25 24 23 22 
    29 30 31 32 33 34 35 
    42 41 40 39 38 37 36 
    43 44 45 46 47 48 49