Created
February 28, 2013 19:35
-
-
Save Rhomboid/5059413 to your computer and use it in GitHub Desktop.
Magic square checker
This file contains 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 <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#define SQUARE_SIZE 4 | |
bool all_same(int *values, size_t num) | |
{ | |
int v = values[0]; | |
for(size_t i = 1; i < num; i++) | |
if(values[i] != v) | |
return false; | |
return true; | |
} | |
bool is_square(int data[][SQUARE_SIZE]) | |
{ | |
struct { | |
int rows[SQUARE_SIZE]; | |
int cols[SQUARE_SIZE]; | |
int diag[2]; | |
} sums = {{0}, {0}, {0}}; | |
for(size_t r = 0; r < SQUARE_SIZE; r++) { | |
for(size_t c = 0; c < SQUARE_SIZE; c++) { | |
int val = data[r][c]; | |
sums.rows[r] += val; | |
sums.cols[c] += val; | |
if(r == c) | |
sums.diag[0] += val; | |
else if(r == SQUARE_SIZE - 1 - c) | |
sums.diag[1] += val; | |
} | |
} | |
return all_same((int *)&sums, SQUARE_SIZE * 2 + 2); | |
} | |
int main(void) | |
{ | |
int data[SQUARE_SIZE][SQUARE_SIZE]; | |
for(size_t r = 0; r < SQUARE_SIZE; r++) { | |
for(size_t c = 0; c < SQUARE_SIZE; c++) { | |
printf("Enter value for row %zu, col %zu: ", r + 1, c + 1); | |
if(scanf("%d", &data[r][c]) != 1) { | |
puts("invalid input"); | |
exit(1); | |
} | |
} | |
} | |
if(is_square(data)) | |
puts("\n\nThis is a magic square."); | |
else | |
puts("\n\nNot a magic square."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment