MagicSquare

    0

    1

    Mahendra Kumar

    matrixDSA

    To verify whether the given matrix(square) is a magic square or not. Magic Square of size 3

    2 7 6 9 5 1 4 3 8 Sum in each row & each column = 3*(32+1)/2 = 15

    Magic Square of size 5

    9 3 22 16 15 2 21 20 14 8 25 19 13 7 1 18 12 6 5 24 11 10 4 23 17 Sum in each row & each column = 5*(52+1)/2 = 65

    Magic Square of size 7

    20 12 4 45 37 29 28 11 3 44 36 35 27 19 2 43 42 34 26 18 10 49 41 33 25 17 9 1 40 32 24 16 8 7 48 31 23 15 14 6 47 39 22 21 13 5 46 38 30 Sum in each row & each column = 7*(72+1)/2 = 175

    #include <bits/stdc++.h>
    using namespace std;
    void generateSquare(int n)
    {
        int magicSquare[n][n];
        memset(magicSquare, 0, sizeof(magicSquare));
        int i = n / 2;
        int j = n - 1;
        // One by one put all values in magic square
        for (int num = 1; num <= n * n;) {
            if (i == -1 && j == n) // 3rd condition
            {
                j = n - 2;
                i = 0;
            }
            else {
                // 1st condition helper if next number
                // goes to out of square's right side
                if (j == n)
                    j = 0;
                // 1st condition helper if next number
                // is goes to out of square's upper side
                if (i < 0)
                    i = n - 1;
            }
            if (magicSquare[i][j]) // 2nd condition
            {
                j -= 2;
                i++;
                continue;
            }
            else
                magicSquare[i][j] = num++; // set number
            j++;
            i--; // 1st condition
        }
        // Print magic square
        cout << "The Magic Square for n=" << n
             << ":\nSum of "
                "each row or column "
             << n * (n * n + 1) / 2 << ":\n\n";
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++)
                cout << setw(4) << magicSquare[i][j] << " ";
            cout << endl;
        }
    }
    int main()
    {
      int n;
      cout<<"Enter an odd number:";
      cin>>n;
      generateSquare(n);
      return 0;
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.