Clockwise output of a Matrix

Source: Internet
Author: User

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 ):


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.