Console outputs spiral numbers

Source: Internet
Author: User

First and finally

 

 

Make a spiral numeric output for the specified array size of the input:

Assume input 3 and output as follows:

1 2 3

8 9 4

7 6 5

 

 

In this order.

 

The implementation code is as follows:

1 # include <iostream>
2 # include <iomanip>
3 using namespace STD;
4
5 void inputgrid (int n, int * m)
6 {// n indicates the scale. M is a two-dimensional array pointer.
7 int ROW = 0, line = 0, flag = 0; // row, line indicates the number of rows or columns to be processed;
8 int I = 0, j =-1;
9 For (INT num = 1; num <= N * n ;)
10 {
11 if (! Flag)
12 {
13 // Line Processing
14 int addnum;
15 if (row % 2 = 0) addnum = 1; // go forward
16 else addnum =-1; // go back
17 int num_row = N-row;
18 while (num_row)
19 {// fill all the remaining blank columns of the row
20 num_row --;
21 J + = addnum;
22 * (m + n * I + J) = num;
23 num ++;
24}
25 row ++;
26 flag = 1;
27
28}
29 else
30 {
31 // column Processing
32 int addnum;
33 If (line % 2 = 0) addnum = 1; // go forward
34 else addnum =-1; // go back
35 int num_line = n-line-1;
36 while (num_line)
37 {// fill all the remaining blank items in this column
38 num_line --;
39 I + = addnum;
40 * (m + n * I + J) = num;
41 num ++;
42}
43 line ++;
44 flag = 0;
45}
46}
47/* For (INT I = 0; I <n * n; I ++)
48 {
49 * (m + I) = I;
50 }*/
51}
52
53 int main ()
54 {
55 int n = 1;
56 int * m, * TM;
57 while (n! =-1)
58 {
59 cout <"Enter the number of rounds: (enter-1 to exit )";
60 CIN> N;
61 If (n =-1)
62 Return 0;
63 m = (int *) malloc (N * n * sizeof (INT ));
64 inputgrid (n, m );
65 for (INT I = 0; I <n; I ++)
66 {
67 TM = m + n * I;
68 for (Int J = 0; j <n; j ++)
69 {
70 cout <SETW (3) <* (TM + J) <"";
71}
72 cout <"\ n ";
73}
74}
75 // return 0;
76}

 

 

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.