Click here to Skip to main content
11,920,377 members (37,343 online)
Click here to Skip to main content
Add your own
alternative version


36 bookmarked

Magic Square

, 8 Sep 2003
Rate this:
Please Sign up or sign in to vote.
Calculating Magic Square In Any Order Using Standard Template Library (STL)
<!-- Article image -->

Sample Image - Magic_Square.jpg

<!-- Add the rest of your HTML here -->


Magic square is an ancient mathematical problem that many people try to solve. May be you see it in some magazines or your teacher might have introduced it in a class.


A magic square is an arrangement of numbers from 1 to n2 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.

It is not hard to show that this sum must be  n [ ( n2 + 1) / 2 ]. If we use this formula for that example output which is below, for [5x5] matrix; 5 [ ( 52 + 1 ) / 2 ] = 65.

17 24 1 8 15 65
23 5 7 14 16 65
4 6 13 20 22 65
10 12 19 21 3 65
11 18 25 2 9 65
65 65 65 65 65 65

Now, I want to show you a way to calculating magic squares in any order by using your talented computer.

Siamese method

This method is useful for calculating magic squares with odd order. It begins by placing a 1 in any location (in the center square of the top row in the above example), then incrementally placing subsequent numbers in the square one unit above and to the right. The counting is wrapped around, so that falling off the top returns on the bottom and falling off the right returns on the left. When a square is encountered which is already filled, the next number is instead placed below the previous one and the method continues as before. The method, also called de la Loubere's method.

For example, if order of square is 5, we have:

void CalculateOddMagicSquare()
  int matrix[5][5];

  int nsqr = n * n;
  int i=0, j=n/2;     // start position

  for (int k=1; k<=nsqr; ++k) 
    matrix[i][j] = k;


    if (k%n == 0) 
      i += 2; 
      if (j==n) 
        j -= n;
      else if (i<0) 
        i += n;

Here is a very nice flash animation to show you how to fill square's cells. Thanks KIVANÇ HiKMET ANAR, for his flash.

Complete Work

Below is full source code of calculating magic squares in any order.

#include "stdafx.h"
#include <vector>

using namespace std;

void OddMagicSquare(vector<vector<int> > &matrix, int n);
void DoublyEvenMagicSquare(vector<vector<int> > &matrix, int n);
void SinglyEvenMagicSquare(vector<vector<int> > &matrix, int n);
void MagicSquare(vector<vector<int> > &matrix, int n);
void PrintMagicSquare(vector<vector<int> > &matrix, int n);

int main(int argc, char* argv[])
  int n;
  printf("Enter order of square: ");
  scanf("%d", &n);

  vector<vector<int> > matrix(n, vector<int> (n, 0));

  if (n<3)
    printf("\nError: n must be greater than 2\n\n");
    return -1;

  MagicSquare(matrix, n);  

  //Print results
  PrintMagicSquare(matrix, n);
  return 0;

void MagicSquare(vector<vector<int> > &matrix,int n)
  if (n%2==1)        //n is Odd
    OddMagicSquare(matrix, n);
  else          //n is even
    if (n%4==0)    //doubly even order
      DoublyEvenMagicSquare(matrix, n);
    else      //singly even order
      SinglyEvenMagicSquare(matrix, n);

void OddMagicSquare(vector<vector<int> > &matrix, int n)
  int nsqr = n * n;
  int i=0, j=n/2;     // start position

  for (int k=1; k<=nsqr; ++k) 
    matrix[i][j] = k;


    if (k%n == 0) 
      i += 2; 
      if (j==n) 
        j -= n;
      else if (i<0) 
        i += n;

void DoublyEvenMagicSquare(vector<vector<int> > &matrix, int n)
  vector<vector<int> > I(n, vector<int> (n, 0));
  vector<vector<int> > J(n, vector<int> (n, 0));

  int i, j;

  //prepare I, J
  int index=1;
  for (i=0; i<n; i++)
    for (j=0; j<n; j++)

  for (i=0; i<n; i++)
    for (j=0; j<n; j++)
      if (I[i][j]==J[i][j])

void SinglyEvenMagicSquare(vector<vector<int> > &matrix, int n)
  int p=n/2;

  vector<vector<int> > M(p, vector<int> (p, 0));
  MagicSquare(M, p);
  int i, j, k;

  for (i=0; i<p; i++)
    for (j=0; j<p; j++)

  if (n==2)

  vector<int> I(p, 0);
  vector<int> J;

  for (i=0; i<p; i++)

  for (i=1; i<=k; i++)

  for (i=n-k+2; i<=n; i++)

  int temp;
  for (i=1; i<=p; i++)
    for (j=1; j<=J.size(); j++)

  //j=1, i
  //i=k+1, k+1+p
  temp=matrix[i][j]; matrix[i][j]=matrix[i+p][j]; matrix[i+p][j]=temp;

  temp=matrix[i+p][j]; matrix[i+p][j]=matrix[i][j]; matrix[i][j]=temp;

void PrintMagicSquare(vector<vector<int> > &matrix, int n)
  for (int i=0; i<n; i++) 
    for (int j=0; j<n; j++)
      printf(" %3d", matrix[i][j]);






This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

A. Riazi
CEO Misbah3Com
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
I was born in Shiraz, a very beautiful famous city in Iran. I started programming when I was 12 years old with GWBASIC. Since now, I worked with various programming languages from Basic, Foxpro, C/C++, Visual Basic, Pascal to MATLAB and now Visual C++.
I graduated from Iran University of Science & Technology in Communication Eng., and now work as a system programmer for a telecommunication industry.
I wrote several programs and drivers for Synthesizers, Power Amplifiers, GPIB, GPS devices, Radio cards, Data Acqusition cards and so many related devices.
I'm author of several books like Learning C (primary and advanced), Learning Visual Basic, API application for VB, Teach Yourself Object Oriented Programming (OOP) and etc.
I'm winner of January, May, August 2003 and April 2005 best article of month competetion, my articles are:

You can see list of my articles, by clicking here

You may also be interested in...

Comments and Discussions

QuestionWhat's wrong with my Magic Square program? Pin
Trevon Harris21-Feb-15 21:25
memberTrevon Harris21-Feb-15 21:25 
Generalthank you...... Pin
aravindanne24-Jan-12 6:24
memberaravindanne24-Jan-12 6:24 
Questiona more general algorithm for generating magic squares Pin
ashishkumar3666-Nov-11 13:15
memberashishkumar3666-Nov-11 13:15 
what you've done is a good example of coding a well-known algorithm. the code is reasonably concise.

the downside is that your program will only generate a limited number of magic squares, i.e, only those that can be generated using the known algorithms for odd, even and doubly-even orders.

now, the number of possible magic squares increases dramatically with order. for eg., order 4 has 880 possible magic squares, 5 has 275305224 and 6 has approximately 1.7745×10^19. so, there are many magic squares your program will never generate. i have written a program in java that generates a magic square for every order, without using the known algorithms (apart from certain bits without which it might take a billion years to finish).

my program produces results for orders upto 9 well under 1 second in each case. order 10 sometimes fails because of the random and brute-force elements in my algorithm. i am working on improving its performance for double-digit and greater orders. i'll post the code once i'm stuck for ideas.

it will be great if you can contribute to the algorithm with any insight you might have about the construction of magic squares. i will discuss my algorithm in greater detail if you're interested.
Questionprogram of magic square Pin
Member 820125830-Aug-11 16:58
memberMember 820125830-Aug-11 16:58 
Questionmagic square program Pin
sheila mejos30-Aug-11 16:09
membersheila mejos30-Aug-11 16:09 
Questiondomino problem Pin
SOLR@C21-May-11 16:59
memberSOLR@C21-May-11 16:59 
Generalhelp me Pin
mashmal11-Apr-11 12:47
membermashmal11-Apr-11 12:47 
Generalhelp me please to expand my knowledge in programming.. Pin
nycshoes0317-Jul-09 18:12
membernycshoes0317-Jul-09 18:12 
Generalmagic square Pin
samantha0315-Jul-09 20:56
membersamantha0315-Jul-09 20:56 
Questionhelp me plzz Pin
dongky19864-Feb-09 2:41
memberdongky19864-Feb-09 2:41 
Questionproblem Pin
Member 47188233-Sep-08 9:54
memberMember 47188233-Sep-08 9:54 
GeneralHelp_Magic Square Pin
00713-Jan-08 5:45
member00713-Jan-08 5:45 
QuestionCan anyone help with this program [modified] Pin
Well Alright 200411-Jun-07 15:14
memberWell Alright 200411-Jun-07 15:14 
QuestionSolvin a Magic Saquare in other method Pin
Nizar Hawat6-Jan-07 12:45
memberNizar Hawat6-Jan-07 12:45 
GeneralHeLP me to solve this probLem, pLease! Pin
winche9-May-06 3:12
memberwinche9-May-06 3:12 
Generalhelp Pin
Shay00730-Mar-06 20:55
memberShay00730-Mar-06 20:55 
GeneralMagic Square Flaw Pin
bugDanny26-Sep-05 4:56
memberbugDanny26-Sep-05 4:56 
GeneralRe: Magic Square Flaw Pin
A. Riazi26-Sep-05 5:10
memberA. Riazi26-Sep-05 5:10 
GeneralRe: Magic Square Flaw Pin
bugDanny26-Sep-05 5:18
memberbugDanny26-Sep-05 5:18 
Generalhi prof Pin
Anonymous24-Sep-05 18:24
sussAnonymous24-Sep-05 18:24 
GeneralComplete Distributed Solution Pin
MagicSquareJoe22-Jul-04 18:22
memberMagicSquareJoe22-Jul-04 18:22 
GeneralYour Complete Work Pin
Anonymous15-Nov-03 15:55
sussAnonymous15-Nov-03 15:55 
GeneralRe: Your Complete Work Pin
Anthony_Yio21-Dec-03 22:32
memberAnthony_Yio21-Dec-03 22:32 
GeneralRe: Your Complete Work Pin
Giles13-Sep-04 3:53
memberGiles13-Sep-04 3:53 
GeneralRe: Your Complete Work Pin
Anonymous18-Sep-04 15:49
sussAnonymous18-Sep-04 15:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151120.1 | Last Updated 9 Sep 2003
Article Copyright 2003 by A. Riazi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid