# How can C output an N-order matrix with increasing return type (primary algorithm)

Keywords: C++

First of all, when it comes to the output matrix, no matter what level of people will think it is the most convenient to use arrays, so what is explained here is the implementation of using multidimensional arrays.

The first is the variable definition required by the algorithm

```int i,j,n,sum;
printf("Please enter the column length of the matrix:\n");
scanf("%d",&n);
int juzhen[n][n];
memset(juzhen,0,sizeof(juzhen));
sum=1;```

The second is the core algorithm. The core of this program is how to write the elements into the defined array. To realize the data increment of the return type, it is necessary to use different methods to input the data increasing in different directions;

Also, we should pay attention to the definition of array, which starts from the subscript 0 to fill in the elements (of course, it is OK to start from the element with subscript 1, this method is similar and will not be explained);

In addition, when changing the direction of input, it should be noted that the array elements that have been input data in the previous direction can no longer be input, so use the if statement to distinguish whether the data has been filled (here, you need to set all the arrays to zero in advance, and use the memset function, which requires the header file string.h).

Four directions of input for statement implementation are defined here

```for(i=0;i<n/2;i++)
{
for(j=0;j<n-1;j++)//Towards the right
{
if(juzhen[i][j]==0)
juzhen[i][j]=sum++;
}
for(j=i;j<n-1;j++)//down
{
if(juzhen[j][n-1-i]==0)
juzhen[j][n-1-i]=sum++;
}
for(j=n-i-1;j>i;j--)//Towards the left
{
if(juzhen[n-1-i][j]==0)
juzhen[n-1-i][j]=sum++;
}
for(j=n-1-i;j>i;j--)//Upward
{
if(juzhen[j][i]==0)
juzhen[j][i]=sum++;
}```

Finally, when the N-order matrix is an even order matrix, there is no central element of the matrix, but the odd order matrix has. The statement is as follows

```        if(n%2==1)
juzhen[(n-1)/2][(n-1)/2]=sum++;```

Finally, output the array

``` for(i=0;i<=n-1;i++)
for(j=0;j<=n-1;j++)
{
printf("%4d",juzhen[i][j]);
if(j==n-1)
printf("\n");
}```
```The complete source code is as follows
```

#include<string.h>```

#include<stdio.h>

int main()
{
int i,j,n,sum;
printf("please enter the row and column length of the matrix: \ n");
scanf("%d",&n);
int juzhen[n][n];
memset(juzhen,0,sizeof(juzhen));
sum=1;

```for(i=0;i<n/2;i++)
{
for(j=0;j<n-1;j++)//Towards the right
{
if(juzhen[i][j]==0)
juzhen[i][j]=sum++;
}
for(j=i;j<n-1;j++)//down
{
if(juzhen[j][n-1-i]==0)
juzhen[j][n-1-i]=sum++;
}
for(j=n-i-1;j>i;j--)//Towards the left
{
if(juzhen[n-1-i][j]==0)
juzhen[n-1-i][j]=sum++;
}
for(j=n-1-i;j>i;j--)//Upward
{
if(juzhen[j][i]==0)
juzhen[j][i]=sum++;
}

}
if(n%2==1)
juzhen[(n-1)/2][(n-1)/2]=sum++;

for(i=0;i<=n-1;i++)
for(j=0;j<=n-1;j++)
{
printf("%4d",juzhen[i][j]);
if(j==n-1)
printf("\n");
}```

}

Posted by Phire on Mon, 02 Dec 2019 08:45:32 -0800