97 lines
2.2 KiB
C
97 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdbool.h>
|
|
// Bonus Question
|
|
|
|
/* Find if all rows, columns, and diagonals in squares have equals sums.
|
|
* Will create an array to hold sums for each row, column, and diagonal. Arr length is (2 * length) + 2
|
|
* Then check if all sums in array are equal
|
|
*/
|
|
|
|
// Sum of each row in arr
|
|
int find_row_sum(const int arr[], int len) {
|
|
int sum = 0;
|
|
for(int i = 0; i < len; i++) {
|
|
sum+=arr[i];
|
|
}
|
|
return sum;
|
|
}
|
|
// Sum of each column in arr
|
|
int find_column_sum(int len, const int arr[len][len],int row) {
|
|
int sum = 0;
|
|
for(int i = 0; i < len; i++) {
|
|
sum+=arr[row][i];
|
|
}
|
|
return sum;
|
|
}
|
|
|
|
// Function to find diagonal sum from top left to bottom right
|
|
int find_diagonal_sum(int len, const int arr[len][len]) {
|
|
int sum = 0;
|
|
int j = 0;
|
|
for(int i = 0; i < len; i++) {
|
|
sum+= arr[i][j];
|
|
j++;
|
|
}
|
|
return sum;
|
|
}
|
|
// Function to find diagonal sum from bottom left to top right
|
|
int find_diagonal_sum_the_other_direction(int len, const int arr[len][len]) {
|
|
int sum = 0;
|
|
int j = len - 1;
|
|
for(int i = 0; i < len; i++) {
|
|
sum += arr[i][j];
|
|
j--;
|
|
}
|
|
return sum;
|
|
}
|
|
// Final function to check if all nums in sum are equal, aka is the square perfect
|
|
bool is_perfect_square(const int arr[], int len) {
|
|
bool is_perfect = true;
|
|
for(int i = 0; i < len - 1 && is_perfect; i++) {
|
|
if(arr[i] != arr[i+1])
|
|
is_perfect = false;
|
|
}
|
|
return is_perfect;
|
|
}
|
|
|
|
int main() {
|
|
int M; // Length of squares sides
|
|
printf("Enter square length: ");
|
|
scanf("%d", &M);
|
|
|
|
int square[M][M];
|
|
|
|
// Input values into matrix
|
|
for(int i = 0; i < M; i++) {
|
|
for(int j = 0; j < M; j++) {
|
|
printf("Enter matrix value %d, %d: ", i, j);
|
|
scanf("%d", &square[i][j]);
|
|
}
|
|
}
|
|
|
|
// The array that will hold our calculated sums
|
|
int sums[2*M + 2];
|
|
// Find sum for each row
|
|
for(int i = 0; i < M; i++) {
|
|
sums[i] = find_row_sum(square[i], M);
|
|
}
|
|
// Find sum for each column
|
|
for(int i = 0; i < M; i++) {
|
|
for (int j = M; j < 2 * M; j++) {
|
|
sums[j] = find_column_sum(M, square, i);
|
|
}
|
|
}
|
|
// Find first diagonal
|
|
sums[2*M] = find_diagonal_sum(M, square);
|
|
// Find second diagonal
|
|
sums[2*M+1] = find_diagonal_sum_the_other_direction(M, square);
|
|
//
|
|
if(is_perfect_square(sums, M)) {
|
|
printf("The matrix is a Magic Square");
|
|
}
|
|
else {
|
|
printf("The matrix is not a Magic Square");
|
|
}
|
|
|
|
return 0;
|
|
} |