Created
December 6, 2011 22:20
-
-
Save asarver/1440301 to your computer and use it in GitHub Desktop.
Magic Square in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdbool.h> | |
| int main(void){ | |
| int dim; | |
| printf("This program creates a magic square of a specified size.\n"); | |
| printf("The size must be an odd number between 1 and 99.\n"); | |
| printf("Enter the size of the magic square here: "); | |
| scanf("%d", &dim); | |
| while(dim % 2 == 0 || dim <= 0 || dim > 99){ | |
| printf("Invalid entry, please enter another number here: "); | |
| scanf("%d", &dim); | |
| } | |
| int pos1, pos2, newPos1, newPos2, num; | |
| int magic[dim][dim]; | |
| int i, j; | |
| for (i = 0; i < dim; i++) { | |
| for (j = 0; j < dim; j++) { | |
| magic[i][j] = 0; | |
| } | |
| } | |
| num = 2; | |
| magic[0][dim/2] = 1; | |
| pos1 = 0; | |
| pos2 = dim/2; | |
| while (num <= dim*dim) { | |
| newPos1 = 0; | |
| newPos2 = 0; | |
| if (pos1 - 1 < 0){ | |
| newPos1 = dim - 1; | |
| } else { | |
| newPos1 = pos1 - 1; | |
| } | |
| if (pos2 + 1 >= dim){ | |
| newPos2 = 0; | |
| } else { | |
| newPos2 = pos2 + 1; | |
| } | |
| if (magic[newPos1][newPos2] == 0) { | |
| pos1 = newPos1; | |
| pos2 = newPos2; | |
| } else { | |
| if (pos1 + 1 >= dim) { | |
| pos1 = 0; | |
| } else { | |
| pos1 = pos1 + 1; | |
| } | |
| } | |
| magic[pos1][pos2] = num; | |
| num++; | |
| } | |
| for (i = 0; i < dim; i++){ | |
| for(j = 0; j < dim; j++){ | |
| printf("%d ", magic[i][j]); | |
| if(j == dim - 1){ | |
| printf("\n"); | |
| } | |
| } | |
| } | |
| int sum[dim], summationOne, summationTwo, diagnolSum, diagnolTwo; | |
| summationOne = 0; | |
| summationTwo = 0; | |
| diagnolSum = 0; | |
| diagnolTwo = 0; | |
| for (i = 0; i < dim; i++) { | |
| for (j = 0; j < dim; j++) { | |
| summationOne += magic[i][j]; | |
| summationTwo += magic[j][i]; | |
| } | |
| diagnolSum += magic[i][i]; | |
| if (summationOne != summationTwo) { | |
| printf("Incorrect."); | |
| } | |
| sum[i] = summationOne; | |
| summationOne = 0; | |
| summationTwo = 0; | |
| } | |
| j = dim - 1; | |
| for (i = 0; i < dim; i++) { | |
| diagnolTwo += magic[i][j]; | |
| j--; | |
| } | |
| for (i = 0; i < dim; i++) { | |
| if (sum[i] != diagnolSum || sum[i] != diagnolTwo) { | |
| printf("Incorrect"); | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment