-
Notifications
You must be signed in to change notification settings - Fork 0
/
24.cpp
93 lines (69 loc) · 1.66 KB
/
24.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
@Author: Amritanshu Sikdar
Session: 2018-'19
Repository: https://github.com/amritanshusikdar/CS30PracticalQuestion
*/
// Check for magic square
#include<iostream.h>
#include<conio.h>
#define false 0
#define true 1
int isMagic(int[3][3]);
int allDifferentNumbers(int[3][3]);
void main()
{
clrscr();
int i, j, square[3][3], magic;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
cout << "A[" << i << "][" << j << "]: ";
cin >> square[i][j];
}
}
magic = isMagic(square);
if(magic)
cout << "It is a magic square!";
else
cout << "It ain't a magic square!";
getch();
}
int isMagic(int square[3][3])
{
int i, j, diagSum=0, rowSum=0, colSum=0;
if (allDifferentNumbers(square))
{
for(i=0; i<3; i++)
diagSum += square[i][i];
for(i=0; i<3; i++)
{
rowSum = 0;
colSum = 0;
for(j=0; j<3; j++)
{
rowSum += square[i][j];
colSum += square[j][i];
}
if(diagSum != rowSum || diagSum != colSum)
return false;
}
} else return false;
return true;
}
int allDifferentNumbers(int square[3][3])
{
// Checking for repetition of numbers
int i, j, k=1, numberCheck[9] = {0,0,0,0,0,0,0,0,0}; // setting initial value to false
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
k = square[i][j]-1;
if(numberCheck[k])
return false;
numberCheck[k] = true;
}
}
return true;
}