0% found this document useful (0 votes)
83 views

Coding On Magic Square

This document discusses coding a magic square in C. It includes the code to initialize a 2D array to represent the magic square, populate it with numbers from 1 to n^2 in a specific pattern according to the rules of a magic square, and print out the completed magic square along with the sum of each row and column. The code uses loops and conditional statements to handle edge cases when placing values and ensure the magic square rules are followed.

Uploaded by

tanuj_sharma1991
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Coding On Magic Square

This document discusses coding a magic square in C. It includes the code to initialize a 2D array to represent the magic square, populate it with numbers from 1 to n^2 in a specific pattern according to the rules of a magic square, and print out the completed magic square along with the sum of each row and column. The code uses loops and conditional statements to handle edge cases when placing values and ensure the magic square rules are followed.

Uploaded by

tanuj_sharma1991
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 5

CODING ON MAGIC SQUARE

BY PAYAL GUPTA AND NEHA ARORA

MAGIC SQUARE
#include<stdio.h> #include<string.h> void main() { int kute=0; int ms[100][100],n,i,j,num; while (scanf(%d,&n)==1) {

if(!n%2) { printf(Enter an odd number 1-99\n); continue; }


memset(ms,0,sizeof(ms));//set all element to 0 as well false num=1;i=n/2;j=n-1;//1st step while(1) { if(num>n*n)break;

if(i==-1&&j==n){j=n-2;i=0;}//3rd condition else { if(j==n)j=0;//1st condition helper if next number is goes to out of box right side if(i<0)i=n-1;//1st condition helper if next number is goes to out of box upper side } if(ms[i][j]){j--;j--;i++;continue;}//2nd condition else ms[i][j]=num++;//set number

j++,i--;//1st condition } //print magic square printf("The Magic Square for %d:\nSum of each row or column %d:\n\n",n,(n*n*n+n)/2);
for(i=0;i<n;i++) { for(j=0,num=0;j<n;j++) { printf("%2d ",ms[i][j]); num+=ms[i][j]; } printf(" %d\n\n",num); } getch(); }

You might also like