C + + implementation: The spiral Matrix Instance code _c language

Source: Internet
Author: User
Tags int size

It is observed that the subscript of the matrix has such a rule: a row increments after column B increases then the C line decreases and then the D column decreases, but the corresponding value is gradually increased. So there are 4 loops to implement, and it's worth noting that you don't overwrite previous values when assigning values. So here you choose the same color section assignment, the code is as follows:

Copy Code code as follows:

#include <iostream>
#include <iomanip>

using namespace Std;

Output Helix matrix
void Matrix ()
const int size = 10; Matrix size
int Matrix[size][size] = {0};

int row = 0;
int col = 0;

    int start = 1;//start value
    int temp = size;
    for (int count = 0; count < SIZE/2 count++)//size order matrices can draw Size/2 loops
&nb sp;       for (; col < temp-1; col++)//A row assignment
             Matrix[row][col] = start++;
        for (; row < temp-1; row++)//b row Assignment
             Matrix[row][col] = start++;
        for (col = temp-1 col > count; col--)//C row Assignment
   &n bsp;        Matrix[row][col] = start++;
        for (row = temp-1 row > count; row--)//D row Assignment
   &n bsp;        Matrix[row][col] = start++;

Go to the next lap
start = 1; This is 1 because it's going to be 1 more when you change the loop.

if (0!= size% 2)///if size is odd then there will be a number of the last one to traverse.
Matrix[row][col+1] = start + 1;

Output array
for (int i = 0; i < size; i++)
for (int j = 0; J < size; J + +)
cout << SETW (5) << matrix[i][j];
cout << Endl;

int main (int argc, char **argv)
Matrix ();
return 0;

The results are as follows (odd, even):

Related Article

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.