Advertisement
Guest User

Untitled

a guest
Jul 26th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class MagicSquare {
  5. public:
  6. MagicSquare(int n)
  7. {
  8. num = n;
  9. magicSquare = new int* [num];
  10. for(int i = 0; i < num; i++)
  11. {
  12. magicSquare[i] = new int[num];
  13. }
  14. }
  15. void printMagicSquare(void)
  16. {
  17.  
  18. for(int row = 0; row < num; row++)
  19. {
  20. for(int col = 0; col < num; col++)
  21. {
  22. cout << "t" << magicSquare[row][col];
  23. }
  24. cout << endl;
  25. }
  26. }
  27. void getRowAndColumn(int& row, int& col, const int counter)
  28. {
  29. if(counter == 1) { col = num / 2; return;} // Initial condition to insert 0
  30. else if(row == 0 && (col == num / 2)) { row = num - 1; col++; return;}
  31. else if(col+1 == num && row == 0) { row++; return;}
  32. else if(col+1 == num) { col = 0; row--; return;}
  33. else if(row == 0) { row = num -1; col++; return;}
  34. else if((row!=0) && (col!=num-1) && magicSquare[row-1][col+1] != 0) { row++; return;}
  35. else { row--; col++; return;}
  36. }
  37. void computeMagicSquare(void)
  38. {
  39.  
  40. int counter = 1;
  41. int row = 0;
  42. int col = 0;
  43. while(counter <= num*num)
  44. {
  45. getRowAndColumn(row, col, counter);
  46. if(row < 0 || row >= num || col < 0 || col >= num) cout << "Error in calculating Row/Column" << endl << "Row = " << row << endl << "Column = " << col << endl;
  47. magicSquare[row][col] = counter++;
  48. }
  49. cout << "nPrinting magicSquare: " << num << "*" << num << endl;
  50. printMagicSquare();
  51. }
  52. private:
  53. int **magicSquare;
  54. int num;
  55. };
  56. int main()
  57. {
  58. int num = 0;
  59. cout << "Enter any odd number: ";
  60. cin >> num;
  61. if(num % 2 == 0) {
  62. cout << "Even number not supported!! " << endl;
  63. return 1;
  64. }
  65. MagicSquare mSq(num);
  66. mSq.computeMagicSquare();
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement