Hello, i am new in this forum as you can see, i hope someone can help me out with this little problem, i have coded a magic square program in c++, it is working 90%.
The magic square is 4x4 and only accepts numbers between 1 and 16.
What is failing here is that it cannot accept repeated numbers. I cannot overcome this problem, and i am running out of ideas i hope someone can help me out and explain to me what i need to do.
The programa detects if the number has been already inserted or not, and it prompts the user for a different number, but when prompt to enter a different number if the user inserts another number that has already been inserted before the program accepts it and continues.
Thanks in advance for your help.
PS: The couts was written originally in Portuguese, i have translated the couts and comments.
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
|
#include <iostream>
using namespace std;
int main() {
int magic[4][4]={0};
int cont=1, lin, col, lin1=0, col1=0, linesum=0, columnsum=0, inicialsum=0, ismagic=1, diagonalsum1=0, diagonalsum2=0;
//preenche o quadrado mágico
cout << "Fill your magic square!!" << endl;
for(lin=0;lin<4;lin++) {
for(col=0;col<4;col++) {
cout << ":::: Magic Square only accepts values between 1 and 16::::" << endl;
do {
cout << "Insert value for line " << lin+1 << " :: Column " << col+1 << ": " << endl;
cin >> magic[lin][col];
if(lin+col>0) {
for(lin1=3; lin1>=0;lin1--) {
for(col1=3;col1>=0;col1--){
if(magic[lin1][col1] == magic[lin][col] && lin1+col1 != lin+col) {
cout << "This has been added already!";
cout << "Please insert a different number: ";
cin >> magic[lin][col];
}
}
}
}
}while(magic[lin][col] <1 || magic[lin][col] >16);
}
}
//sum of 1st column
for(lin=0;lin<4;lin++) {
inicialsum+=magic[lin][0];
}
//sum of all column
for(col=0;col<4;col++) {
columnsum=0;
for(lin=0;lin<4;lin++) {
columnsum+=magic[lin][0];
}
if(columnsum != inicialsum)
ismagic=0;
}
cout << "sum of columns = " << columnsum << endl;
//line sum
for(lin=0;lin<4;lin++) {
linesum=0;
for(col=0;col<4;col++) {
linesum+=magic[lin][col];
}
if(linesum != inicialsum)
ismagic=0;
}
cout << "sum if lines = " << linesum << endl;
//sum of 1st diagonal
for(lin=0;lin<4;lin++) {
for(col=0;col<4;col++) {
if(lin==col) {
diagonalsum1+=magic[lin][col];
}
}
}
if(diagonalsum1 != inicialsum)
ismagic=0;
cout << "sum of 1st diagonal = " << diagonalsum1 << endl;
//sum of 2nd diagonal
col=4;
for(lin=0;lin<4;lin++) {
col--;
diagonalsum2+=magic[lin][col];
}
if(diagonalsum2 != inicialsum)
ismagic=0;
cout << "sum of 2nd diagonal = " << diagonalsum2 << endl;
if(ismagic==1)
cout << "Great! It is a magic square" << endl;
else
cout << "Not a magic square" << endl;
system("pause");
return 0;
}
|