Question: Output a matrix (N * n) clockwise ).
Assume that a matrix is:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Then the output of the program should be: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
The answer to this question has also been collected on the Internet. There is no clever way, so the following is a code output in a clockwise manner (prepared by yourself and tested ):
# Include <stdio. h> # define N5 // matrix dimension void clockwise_matrix (INT matrix [] [N]) {int starta = 0, startc = 0, Enda = N-1, ENDC = N-1; int array, column, I; while (1) {for (I = 0; startc + I <= ENDC; I ++) {// incrementally increase printf ("% 3d", matrix [starta] [startc + I]);} If (starta <ENDA) {// this judgment is used to process for (I = 1; starta + I <= ENDA; I ++) when only one row is left in the remaining part of the matrix) {// vertically incrementing printf ("% 3d", matrix [starta + I] [ENDC]);} for (I = 1; ENDC-I> = startc; I ++) {// horizontal decline printf ("% 3d", matrix [ENDA] [ENDC-I]) ;}for (I = 1; Enda-I> starta; I ++) {// vertically decreasing printf ("% 3d", matrix [Enda-I] [startc]) ;}} starta ++; startc ++; ENDA --; ENDC --; If (starta> ENDA) {break ;}} int main () {int I, j; int matrix [N] [N]; for (I = 0; I <n; I ++) // assign a value to the test array for (j = 0; j <n; j ++) {matrix [I] [J] = I * n + J;} printf ("the test matrix is: \ n "); // print out the test array for (I = 0; I <n; I ++) {for (j = 0; j <n; j ++) {printf ("% 3d", matrix [I] [J]);} printf ("\ n");} printf ("\ n"); clockwise_matrix (matrix ); printf ("\ n"); Return 0 ;}
The following is the result of running the program in Ubuntu. (The dimension in the program can be modified. I tested it myself ~ 7 ):