顺时针打印矩阵
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。(n*n的矩阵)
如有矩阵:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
打印出:1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13
思路:把打印分成几个圈,如果需要的圈数为ini那么ini应该从1到2*ini < n,每一圈分为四个部分来循环,有了这个思路代码就不难写出了
#include <stdio.h> #include <stdlib.h> #define MAX_N 5 /* length of matrix */ void regular_display (int *data, int num); void circle_display (int *data , int num); int main ( int argc, char *argv[] ) { int array[MAX_N][MAX_N]; int x, y; int i = 1; for ( x = 0; x < MAX_N; x ++ ) { for ( y = 0; y < MAX_N; y++ ) { array[x][y] = i++; } } regular_display ((int *) array, MAX_N); circle_display ((int *) array, MAX_N); return EXIT_SUCCESS; } /* ---------- end of function main ---------- */ void regular_display ( int *data, int num ) { int x, y; for ( x = 0; x < num; x += 1 ) { for ( y = 0; y < num; y += 1 ) printf ("%-7d", *(data + x * num + y)); puts (""); } puts("\n"); } /* ----- end of function regular_display ----- */ void circle_display ( int *data, int num) { int x, y; int init; for (init = 0; 2 * init < num; init++) { x = init; y = init; for (; y < num - init; y++) { printf ("%-7d", *(data + num * x + y)); } for (y--,x++; x < num - init; x++) { printf ("%-7d", *(data + num * x + y)); } for (x--, y--; y > init - 1; y--) { printf ("%-7d", *(data + num * x + y)); } for (y++, x--; x > init; x--) { printf ("%-7d", *(data + num * x + y)); } } puts (""); } /* ----- end of function circle_display ----- */
测试结果:
[leajon@arch matrix]$ ./matrix 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13