輸入一個n,然後在螢幕上打印出NxN 的矩陣!
阿新 • • 發佈:2019-02-08
/* Function: printCube Description: generate the Cube in array and print it Input: [array]: the array for store Cube's data ( enough to store the data, minimum array[n][n] ) [n]: the Cube size ( n > 0 ) Output: Return: Others: if( n == 3 ) cube is: { 1 2 3 8 9 4 7 6 5 } */ void printCube( int array[][N], int n ) { assert( 0 < n ); // i, j: index for array; // min, max: border index for assignment Cube data // m: data for Cube, add one every step; int i, j, min, max, m; /* generate Cube data in array */ for( m = 1, min = 0, max = n - 1; max > min; max--, min++ ) { for( i = min, j = min; j < max; j++ ) array[i][j] = m++; // first step: generate row data form left to right ( min to max-1 ) for( ; i < max; i++ ) array[i][j] = m++; // second step: generate column data from top to bottom ( min to max-1 ) for( ; j > min; j-- ) array[i][j] = m++; // third step: generate row data from right to left ( max to min+1 ) for( ; i > min; i-- ) array[i][j] = m++; // fourth step: generate column data from bottom to top ( max to min+1 ) } if( min == max ) array[min][max] = m++; /* print Cube */ for( i = 0; i < n; i++ ) { for( j = 0; j < n; j++ ) { printf(" %4d ", array[i][j]); } printf("\n"); } }