C016 A C program to check if the given matrix is magic square or not.

By | September 3, 2013

Let’s identify variables needed for this program.

In this program, we need to save matrices which consists Rows and Columns. To save this we need Two dimensional ARRAY.

Multi-dimensional Array is a nothing different than any Array but the only difference is that it has more than one dimension to it e.g. square has two dimension and cube has three dimension. The Dimension of array is decided by us in number of square brackets [] selected. If We select two dimension than we have to take two square brackets[][]. It has to be accessed with the help of index number ranging from 0 to n-1 and 0 to m-1. (e.g. num[n][m] will have num[0][0],num[0][1],num[2][2] so on.)

First few variables will be the one which will save the values of matrix with the choice of rows and columns entered by the user and it will be array A[MAX][MAX] will be in the form A[M][M] therefore we will need M will be needed as user decides the order of the square matrix. Here since we are taking order of the square matrix from the user and hence we can not keep the square brackets empty we will fill that value by maximum value (MAX). This MAX variable will be defined as a constant above the program.Next variable will be array SUM and TEMP will be for saving resultant right diagonal and left diagonal values respectively which will be compared. Next variable will be array SUM_COL[MAX] and SUM_ROW[MAX] will be for saving resultant sum of columns and sum of rows values respectively which will be compared later. other variables will be I and J which will be for FOR Loop so in all EIGHT variables and ONE constant selected.
The identified variables are int A[MAX][MAX],I,J,M,SUM,TEMP,SUM_COL[MAX],SUM_ROW[MAX] and identified constant is MAX.

[codesyntax lang=”c”]

#define MAX 10

int A[MAX][MAX],I,J,M,SUM=0,TEMP=0,SUM_COL[MAX],SUM_ROW[MAX];

[/codesyntax]

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

Best Loop for such kind of condition is FOR Loop the value of loop will start with 0 to M-1. Now here we need nested loop one loop inside the other. So that we can access all the elements with it. We will calculate sum of right diagonal and sum of left diagonal values by using single for loop. We will need First two nested loops for scanning and printing given array values of square matrix. Next two nested loop will be nested with three FOR loop for sum of rows array values and sum of columns array values of matrices respectively and save it empty arrays taken.

This let’s you understand nested loop

[codesyntax lang=”c”]

for(I=0;I<M;I++)
{
for(J=0;J<M;J++)
{
scanf(“%d”,&A[I][J]);
}
}

[/codesyntax]

MAGIC SQUARE is a square matrix which has same number of rows and same numbers of columns. since the number of row and number of column are same the number is called order of square matrix. When we add the values in any row or any column or right diagonal or left diagonal the sum of all should be the equal number. See the image below to understand.

Magic_Square_3X3

In the program, first calculate the sum of right diagonal (SUM) and sum of left diagonal (TEMP). Since the right diagonal has all the index values to be (0,0), (1,1),  and (2,2), hence we have only one for loop to execute the summation task.

[codesyntax lang=”c”]

for(I=0;I<M;I++)
     {
      SUM=SUM+A[I][I];
     }

[/codesyntax]

 

Next sum of left diagonal (TEMP)  Since the left diagonal has all the index values to be (2,0), (1,1),  and (0,2), hence we have only one for loop to execute the summation task. When we see the index values row decreases and column increases gradually.

[codesyntax lang=”c”]

for(I=0,J=M-1;I<M;I++,J--)
     {
      TEMP=TEMP+A[I][J];
     }

[/codesyntax]

To reduce execution time we can jump from the point we find values compared not equal to the end statement and display not a magic square message. If the two diagonal values are not equal (i.e. SUM == TEMP) jump there itself.

Condition for checking if a matrix is a magic square or not : In order to check magic square of a square matrix, sum of each row, sum of each column, and sum of right & left diagonal value, All the sum must be equal. Thus, if A is an m x m matrix, sum 0f right diagonal = sum 0f left diagonal = sum of each row = sum of each column.

[codesyntax lang=”c”]

  if(SUM==TEMP)
  {
    {
       \\code for calculating sum of columns
    }
    for(I=0;I<M;I++)
    {
        \\code to check and compare each value of sum of columns with sum of diagonal and jump to LABEL if not equal
    }
    for(J=0;J<M;J++)
    {
        \\code for calculating sum of rows
    }
    for(J=0;J<M;J++)
    {
        \\code to check and compare each value of sum of rows with sum of diagonal and jump to LABEL if not equal
    }
    printf("\nTHE GIVEN MATRIX IS A MAGIC SQUARE");
     }
  else
  {
       LABEL :printf("\nTHE GIVEN MATRIX IS NOT A MAGIC SQUARE");
  }

[/codesyntax]

Calculate sum of each column the variable J should be inside and save it in array SUM_COL[M].

[codesyntax lang=”c”]

for(I=0;I<M;I++)
    {
        SUM_COL[I]=0;
        for(J=0;J<M;J++)
        {
              SUM_COL[I]=SUM_COL[I]+A[I][J];
        }
    }

[/codesyntax]

 

Calculate sum of each row the variable I should be inside and save it in array SUM_ROW[M].

[codesyntax lang=”c”]

for(J=0;J<M;J++)
    {
        SUM_ROW[J]=0;
        for(I=0;I<M;I++)
        {
              SUM_ROW[J]=SUM_ROW[J]+A[I][J];
        }
    }

[/codesyntax]

 

Checking of sum of right diagonal SUM with the sum of each row in SUM_ROW[] array and jump if not equal. And same to be done with column.

[codesyntax lang=”c”]

for(J=0;J<M;J++)
    {
        if(SUM != SUM_ROW[J])
                goto LABEL;
    }

[/codesyntax]

 

Print the Numbers of Given Array in the Matrix form by using Tab (\t) and New Line (\n) character in the nested Loop at the start of the program.

[codesyntax lang=”c”]

for(I=0;I<M;I++)
{
for(J=0;J<M;J++)
{
printf(“%d\t”,A[I][J]);
}
printf(“\n”);
}

[/codesyntax]

C program code :

[codesyntax lang=”c” lines=”normal”]

#include<stdio.h>
#define MAX 10
void main()
{
     int A[MAX][MAX],I,J,M,SUM=0,TEMP=0,SUM_COL[MAX],SUM_ROW[MAX];
     clrscr();
     printf("ENTER ORDER OF A SQUARE MATRIX  : \n");
     printf("ENTER ORDER M (LESS THAN 10) :");
     scanf("%d",&M);
     printf("ENTER %d X %d MATRIX A VALUES\n",M,M);
     for(I=0;I<M;I++)
     {
    for(J=0;J<M;J++)
    {
        scanf("%d",&A[I][J]);
    }
     }
     printf("\nTHE GIVEN %d X %d MATRIX VALUES ARE :\n",M,M);
     for(I=0;I<M;I++)
     {
    for(J=0;J<M;J++)
    {
        printf("%d\t",A[I][J]);
    }
    printf("\n");
     }
     for(I=0;I<M;I++)
     {
      SUM=SUM+A[I][I];
     }
     for(I=0,J=M-1;I<M;I++,J--)
     {
      TEMP=TEMP+A[I][J];
     }
     if(SUM==TEMP)
     {
    for(I=0;I<M;I++)
    {
        SUM_COL[I]=0;
        for(J=0;J<M;J++)
        {
              SUM_COL[I]=SUM_COL[I]+A[I][J];
        }
    }
    for(I=0;I<M;I++)
    {
        if(SUM != SUM_COL[I])
              goto LABEL;
    }
    for(J=0;J<M;J++)
    {
        SUM_ROW[J]=0;
        for(I=0;I<M;I++)
        {
              SUM_ROW[J]=SUM_ROW[J]+A[I][J];
        }
    }
    for(J=0;J<M;J++)
    {
        if(SUM != SUM_ROW[J])
                goto LABEL;
    }
    printf("\nTHE GIVEN MATRIX IS A MAGIC SQUARE");
     }
     else
     {
       LABEL :printf("\nTHE GIVEN MATRIX IS NOT A MAGIC SQUARE");
     }
     getch();
}

[/codesyntax]

Note:- whenever you have large number of inputs to be entered, we can use space instead of enter button all the time. You can see have its done in Output screen.

SCREEN SHOTS:-

C_program_Matrix_Magic_Square

C_program_Matrix_Magic_Square_Output

 

Note:- To understand program for sequence in detail Please SEARCH numerically example: C001, C002, etc.

Leave a Reply