fork(1) download
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5. int magicsq[3][3] = {0}; // initializes magic square with all 0s
  6. // Algorithm of de la Loubere:
  7. int row = 0, col = 1; // start coordinates
  8. // assign start cell
  9. magicsq[row][col] = 1;
  10. for (int x = 2; x <= 9; ++x) {
  11. // compute up-right coordinates
  12. int rowT = row - 1; if (rowT < 0) rowT += 3;
  13. int colT = col + 1; if (colT >= 3) colT -= 3;
  14. // check whether cell not yet assigned
  15. if (magicsq[rowT][colT]) {
  16. // compute down coordinates
  17. if (++row >= 3) row -= 3;
  18. } else {
  19. // use up-right coordinates
  20. row = rowT; col = colT;
  21. }
  22. // assign next cell
  23. magicsq[row][col] = x;
  24. }
  25. // output of result:
  26. std::cout << "Magic Square:" << std::endl;
  27. for (row = 0; row < 3; ++row) {
  28. for (col = 0; col < 3; ++col) {
  29. std::cout << ' ' << magicsq[row][col];
  30. }
  31. std::cout << std::endl;
  32. }
  33. // check result:
  34. std::cout << "Row sums:";
  35. for (row = 0; row < 3; ++row) {
  36. int sum = 0;
  37. for (col = 0; col < 3; ++col) sum += magicsq[row][col];
  38. std::cout << ' ' << sum;
  39. }
  40. std::cout << std::endl;
  41. std::cout << "Column sums:";
  42. for (col = 0; col < 3; ++col) {
  43. int sum = 0;
  44. for (row = 0; row < 3; ++row) sum += magicsq[row][col];
  45. std::cout << ' ' << sum;
  46. }
  47. std::cout << std::endl;
  48. std::cout << "Diagonal sums: ";
  49. int sumM = 0, sumC = 0;
  50. for (row = 0; row < 3; ++row) {
  51. sumM += magicsq[row][row];
  52. sumC += magicsq[row][2 - row];
  53. }
  54. std::cout << ' ' << sumM << ' ' << sumC << std::endl;
  55. // done
  56. return 0;
  57. }
Success #stdin #stdout 0s 4460KB
stdin
Standard input is empty
stdout
Magic Square:
 8 1 6
 3 5 7
 4 9 2
Row sums: 15 15 15
Column sums: 15 15 15
Diagonal sums:  15 15