Sunday, 17 September 2017

A Magic Square For Order Of An Odd Number Using C++

A Magic Square of order N is an arrangement of N x N numbers, usually distinct integers, in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to N x N. 

The constant sum in every row, column and diagonal is called the magic constant or magic sum, M. The Magic Constant of a normal magic square depends only on n and has the following value: M = N(N^2+1)/2;

Here we demonstrate a program to draw magic-square for order of an odd number. You can change the value of N in the code to print for a different number.

Source Code:
#include <stdio.h>
#include <iostream>
int main()
{
       //Define odd number for a Magic Square
       const int n = 5;
       //Take procedure only for odd number
       if (n % 2)
       {
              // Show Order and Magic Sum;
              std::cout << "Odd Number Magic Square: " << n << " x " << n << "\n";
              std::cout << "It`s Magic Sum is: " << n*(n*n + 1) / 2 << "\n\n";
              //Take a 2d array
              int magic[n][n];
              int row = 0, col = n / 2, i, square = n * n;   
              //Calc the elements
              for (i = 1; i <= square; i++)
              {
                     magic[row][col] = i;
                     if (i % n == 0) row++;
                     else
                     {
                           if (row == 0) row = n - 1;
                           else row--;
                           if (col == (n - 1))  col = 0;
                           else col++;
                     }
              }
              //Show the result
              for (size_t i = 0; i < n; i++)
              {
                     for (size_t j = 0; j < n; j++)
                           std::cout << magic[i][j] << "\t";
                     std::cout << "\n";
              }
       }
       getchar();
       return 0;
}

Output: