Program to check if the given matrix is magic square or not
Program to check if the given matrix is magic square or not
1 |
/*Program to takes the the data of a 3x3 matrix and check if the given matrix is magic square or not*/ |
2 |
#include <stdio.h> |
3 |
#include <conio.h> |
4 |
int num[3][3]; |
5 |
int sum[8]; |
6 |
int r,c,i; |
7 |
|
8 |
/*Function to take the value in matrix from user*/ |
9 |
void read_matrix() |
10 |
{ |
11 |
for(r=0;r<3; r++) |
12 |
{ |
13 |
for(c=0;c<3; c++) |
14 |
{ |
15 |
printf("Enter value for %d %d::",r,c); |
16 |
scanf("%d",&num[r][c]); |
17 |
} |
18 |
} |
19 |
} |
20 |
|
21 |
/*Function to print matrix and get the sum of rows,cols and diaglons*/ |
22 |
void print_calc_rows_cols() |
23 |
{ |
24 |
int sum_row,sum_col,ctr=0; |
25 |
|
26 |
/*Print the Matrix and get the sum of rows*/ |
27 |
for(r=0;r<3; r++) |
28 |
{ |
29 |
sum_row=0; |
30 |
for(c=0;c<3; c++) |
31 |
{ |
32 |
printf("\t%d",num[r][c]); |
33 |
sum_row=sum_row+num[r][c]; |
34 |
} |
35 |
sum[ctr]=sum_row; |
36 |
ctr++; |
37 |
printf(":: %d",sum_row); |
38 |
printf("\n"); |
39 |
} |
40 |
printf("\t::\t::\t::\n"); |
41 |
|
42 |
/*Get the sum of columns*/ |
43 |
for(c=0;c<3;c++) |
44 |
{ |
45 |
sum_col=0; |
46 |
for(r=0;r<3;r++) |
47 |
sum_col=sum_col+num[r][c]; |
48 |
|
49 |
sum[ctr]=sum_col; |
50 |
ctr++; |
51 |
printf("\t%d",sum_col); |
52 |
} |
53 |
printf("\n"); |
54 |
|
55 |
/*Get the sum of diagnols*/ |
56 |
sum[6]=num[0][0]+num[1][1]+num[2][2]; |
57 |
sum[7]=num[0][2]+num[1][1]+num[2][0]; |
58 |
|
59 |
} |
60 |
|
61 |
/*Function to Check the sum of rows,cols and diagnols*/ |
62 |
char check_matrix() |
63 |
{ |
64 |
char c; |
65 |
for(i=0;i<3; i++) |
66 |
{ |
67 |
if(sum[i]==sum[i+1]) |
68 |
c='y'; |
69 |
else |
70 |
{ |
71 |
c='n'; |
72 |
break; |
73 |
} |
74 |
} |
75 |
return c; |
76 |
} |
77 |
|
78 |
void main() |
79 |
{ |
80 |
char c; |
81 |
clrscr(); |
82 |
read_matrix(); |
83 |
print_calc_rows_cols(); |
84 |
c=check_matrix(); |
85 |
|
86 |
|
87 |
/*Print the result*/ |
88 |
if(c=='y') |
89 |
printf("\nThis Matrix is a Magic Square"); |
90 |
else |
91 |
printf("\nThis Matrix is Not a Magic Square"); |
92 |
|
93 |
getch(); |
94 |
} |