Header Ads

22 - WAP to Print Magic Square [Matrix Form] in C

This Program prints the Magic Square by considering the position of the '1' placed to a certain row or a column.

#include <stdio.h>
#include <stdlib.h>
int main()
{
 //Declaring array and variables
 int square[3][3], row, col, idx, jdx, sum = 0, num = 1;
 char ch;
 do
 {
  //Reading position for 1 from user
  printf("Enter the position of 1 for a 3x3 Magic Square.\nEnter the position for 1\nRow = ");
  scanf("%d", &row);
  printf(" Column = ");
  scanf("%d", &col);
  getchar();
  //filling all the places with zero
  for (idx = 0; idx < 3; idx++)
  {
   for (jdx = 0; jdx < 3; jdx++)
   {
    square[idx][jdx] = 0;
   }
  }
  square[row][col] = 1;

  if (row < 3 && col < 3)
  {
   row--;
   col++;
   for (idx = 0; idx < 8; idx++)
   {
    //Conditions to check if the row and column is inside the box or it is crossed
    if (row < 0)
    {
     row = 2;
    }
    if (col > 2)
    {
     col = 0;
    }
    //Checking if the cell contains zero of what
    if (square[row][col] == 0)
    {
     square[row][col] = ++num;
    }
    else
    {
     //if a non zero value is present then Moving to the cell below the current cell
     row += 2;
     col--;
     //checking Boundary conditions
     if (row > 2)
     {
      row = 0;
     }
     if (col < 0)
     {
      col = 2;
     }
     //Checking if the cell is empty or not
     if (square[row][col] == 0)
     {
      square[row][col] = ++num;
     }
     else
     {
      //Moving to the cell below the current cell
      row++;
      if (row > 2)
      {
       row = 0;
      }
      square[row][col] = ++num;
     }
    }
    //Shifting to right top cell
    row--;
    col++;
   }

   //Loop to print the values with horizontal Sum
   for (idx = 0; idx < 3; idx++)
   {
    for (jdx = 0; jdx < 3; jdx++)
    {
     printf("%d\t", square[idx][jdx]);
     sum = sum + square[idx][jdx];
    }
    printf("%10d\n", sum);
    sum = 0;
   }
   printf("-------------------\n");
   for (idx = 0; idx < 3; idx++)
   {
    for (jdx = 0; jdx < 3; jdx++)
    {
     sum =sum + square[jdx][idx];
    }
    printf("%d\t", sum);
    sum = 0;
   }
  }
  else
  {
   printf ("\nSorry! Invalid Entry.\n");
  }
  printf("\n");
  //enter y to continue
  printf("\nTo Continue press ['Y'/'n'] : ");
 } while ((ch = getchar()) && (ch == 'y' || ch == 'Y'));
 return 0;
}

Program Output: 

 

No comments