Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- class MagicSquare {
- public:
- MagicSquare(int n)
- {
- num = n;
- magicSquare = new int* [num];
- for(int i = 0; i < num; i++)
- {
- magicSquare[i] = new int[num];
- }
- }
- void printMagicSquare(void)
- {
- for(int row = 0; row < num; row++)
- {
- for(int col = 0; col < num; col++)
- {
- cout << "t" << magicSquare[row][col];
- }
- cout << endl;
- }
- }
- void getRowAndColumn(int& row, int& col, const int counter)
- {
- if(counter == 1) { col = num / 2; return;} // Initial condition to insert 0
- else if(row == 0 && (col == num / 2)) { row = num - 1; col++; return;}
- else if(col+1 == num && row == 0) { row++; return;}
- else if(col+1 == num) { col = 0; row--; return;}
- else if(row == 0) { row = num -1; col++; return;}
- else if((row!=0) && (col!=num-1) && magicSquare[row-1][col+1] != 0) { row++; return;}
- else { row--; col++; return;}
- }
- void computeMagicSquare(void)
- {
- int counter = 1;
- int row = 0;
- int col = 0;
- while(counter <= num*num)
- {
- getRowAndColumn(row, col, counter);
- if(row < 0 || row >= num || col < 0 || col >= num) cout << "Error in calculating Row/Column" << endl << "Row = " << row << endl << "Column = " << col << endl;
- magicSquare[row][col] = counter++;
- }
- cout << "nPrinting magicSquare: " << num << "*" << num << endl;
- printMagicSquare();
- }
- private:
- int **magicSquare;
- int num;
- };
- int main()
- {
- int num = 0;
- cout << "Enter any odd number: ";
- cin >> num;
- if(num % 2 == 0) {
- cout << "Even number not supported!! " << endl;
- return 1;
- }
- MagicSquare mSq(num);
- mSq.computeMagicSquare();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement