fork(4) download
  1. #include<iostream>
  2. #include<iomanip>
  3. #include <cstring>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int n;
  9.  
  10. // cout<< "Please enter an odd integer: ";
  11. cin>>n;
  12.  
  13. int MagicSquare[n][n];
  14.  
  15.  
  16. int newRow,
  17. newCol;
  18. memset(MagicSquare, 0, sizeof(MagicSquare));
  19. // Set the indices for the middle of the bottom i
  20. int i =0 ;
  21. int j= n / 2;
  22.  
  23. // Fill each element of the array using the magic array
  24. for ( int value = 1; value <= n*n; value++ )
  25. {
  26. MagicSquare[i][j] = value;
  27. // Find the next cell, wrapping around if necessary.
  28. newRow = (i + 1) % n;
  29. newCol = (j + 1) % n;
  30. // If the cell is empty, remember those indices for the
  31. // next assignment.
  32. if ( MagicSquare[newRow][newCol] == 0 )
  33. {
  34. i = newRow;
  35. j = newCol;
  36. }
  37. else
  38. {
  39. // The cell was full. Use the cell above the previous one.
  40. i = (i - 1 + n) % n;
  41. }
  42.  
  43. }
  44.  
  45.  
  46. for(int x=0; x<n; x++)
  47. {
  48. for(int y=0; y<n; y++)
  49. cout << MagicSquare[x][y]<<" ";
  50. cout << endl;
  51. }
  52. }
  53.  
Success #stdin #stdout 0s 3472KB
stdin
3
stdout
8 1 6 
4 9 2 
3 5 7