Friday, 24 July 2015

C++ Program to Solve the Magic Squares Puzzle without using Recursion

Leave a Comment
The following C++ program, using iteration, finds the magic square for a given odd sized number. A magic square is an arrangement of numbers from 1 to n^2 in an [n x n] matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same.


Code:

#include<iostream>
using namespace std;

void magicsq(int, int [][10]);

int main( )
{
    int size;
    int a[10][10];

    cout<<"Enter the size: ";
    cin>>size;
    if (size % 2 == 0)
    {
        cout<<"Magic square works for an odd numbered size\n";
    }
    else
    {
        magicsq(size, a);
    }
    return 0;
}

void magicsq(int size, int a[][10])
{
    int sqr = size * size;
    int i = 0, j = size / 2, k;

    for (k = 1; k <= sqr; ++k)
    {
        a[i][j] = k;
        i--;
        j++;

        if (k % size == 0)
        {
            i += 2;
            --j;
        }
        else
        {
            if (j == size)
            {
                j -= size;
            }
            else if (i < 0)
            {
                i += size;
            }
        }
    }
    for (i = 0; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
            cout<< a[i][j];
        }
        cout<<endl;
    }
    cout<<endl;
}

Output:

If You Enjoyed This, Take 5 Seconds To Share It