The method of realizing odd-order magic square in C language _c language

Source: Internet
Author: User

This paper illustrates the method of realizing the odd-order magic square in C language. Share to everyone for your reference. The implementation methods are as follows:

Copy Code code as follows:
#include "stdio.h"
#include "string.h"
#include "Stdlib.h"

#define N 5

void Main () {
int a[n][n]={0};
int i,j;
int k;

i = 0;
j = N/2;
A[0][j]=1;
for (k = 2; k <= n*n; k++) {
if (i = = 0 && J = = N-1) {//First, determine whether the first number is the top-right number, if the latter number directly below the previous number
i=i+1;
A[I][J] = k;
Continue
}
i = (i-1+n)%n;//computes the coordinates of the top right corner of the previous number
j = (j+1)%N;
if (A[i][j]!= 0) {//If there is an element in the upper-right corner of the previous number, the latter number is filled directly below the previous number
i = ((i+1)%n+1)%n;//Restore coordinates
j = (j-1+n)%N;
A[I][J] = k;
}else{//above conditions are not satisfied, the last number placed in the upper right corner of the previous number
A[I][J] = k;
}
}

for (i = 0; i < N; i++) {
for (j = 0; J < N; J + +) {
printf ("M", A[i][j]);
}
printf ("\ n");
}
}

The test data are as follows:

N = 3

8 1 6
3 5 7
4 9 2

I hope this article will help you with the C language program.

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.