8. WRITE A C PROGRAM TO IMPLEMENT A MAGIC SQUARE OF SIZE N.
DEFN: A MAGIC SQUARE IS AN ARRANGEMENT OF NUMBERS
(USUALLY
INTEGERS) IN A
SQUARE GRID, WHERE
THE NUMBERS
IN EACH ROW, AND IN EACH COLUMN, AND THE NUMBERS THAT
RUN DIAGONALLY IN BOTH DIRECTIONS, ALL ADD UP TO THE
SAME NUMBER.
SOURCE CODE:
#include <stdio.h>
int main() {
int n,row,col,next_row,next_col,n,i,j,start;
int magic[99][99];
int max ;
printf("Enter size of magic square: ");
scanf("%d", &n);
start = (n / 2);
max = n * n;
magic[0][start] = 1;
for (i = 2, row = 0, col = start; i < max + 1; i++) {
if ((row - 1) < 0) {
next_row = n - 1;
}
else { next_row = row - 1; }
if ((col + 1) > (n - 1)) {
next_col = 0;
}
else { next_col = col + 1; }
if (magic[next_row][next_col] > 0) {
if (row > (n - 1)) {
next_row = 0;
}
else {
next_row = row + 1;
next_col = col;
}
}
row = next_row;
col = next_col;
magic[row][col] = i;
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%4d", magic[i][j]);
}
printf("\n");
}
return 0;
}
0 comments:
Post a Comment