majic square problem using 2d arrays

hey i wrote a code that checks if the input matrix in the text file is a majic square....the code is working bt when i input a a matrix which is 5 by 5 or higher
even if its a majic square it outputs -1 which states that its not a majic square......please help and thanx in advance

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
94
95
96
97
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>

using namespace std;
int matrix(vector<int>&data,int &mequation)
{
    int d=0;
    ifstream infile("input.txt");
    int arr[25][25];
    while(infile>>d)
    {
        data.push_back(d);
    }
    //////////////////////
    int counter=0;
    int asize=sqrt(data.size());
    //////////////////////////
    for(int i=0;i<asize;i++)
    {
        for(int j=0;j<asize;j++)
        {
            arr[i][j]=data.at(counter);
            counter++;
        }
    }
    //////////////////////////
    mequation=(asize*(pow(asize,2)+1))/2;
    int sumrow=0;
    int sumcol=0;
    int sumldiag=0;
    int sumfdiag=0;
    int flag1=0;
    int flag2=0;
    int flag3=0;
    int flag4=0;
    ///check rows
     for(int i=0;i<asize;i++)
    {
        sumrow=0;
        for(int j=0;j<asize;j++)
        {
            sumrow=sumrow+arr[i][j];
        }
        if(sumrow!=mequation)
            return 0;
    }
    ///check columns
    for(int i=0;i<asize;i++)
    {
        sumcol=0;
        for(int j=0;j<asize;j++)
        {
            sumcol=sumcol+arr[i][j];
        }
        if(sumcol!=mequation)
            return 0;
    }
    ///check first diagonal
    for(int i=0;i<asize;i++)
    {
        sumfdiag=sumfdiag+arr[i][i];
    }
    if(sumfdiag!=mequation)
        return 0;
    ///check last diagonal
    int element=0;
    for(int i=asize-1;i>=0;i--)
    {
        sumldiag=sumldiag+arr[element][i];
       element++;
    }
    if(sumldiag!=mequation)
        return 0;

    return 1;

}

int main()
{
   vector<int>data;

   int asize=sqrt(data.size());
   int mequation=(asize*(pow(asize,2)+1))/2;
   int flag=0;
   flag=matrix(data,mequation);
    if(flag)
    {
        cout<<mequation<<endl;
    }
    else
        cout<<"-1"<<endl;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.