Canna

Thursday, 27 September 2018

Magic Square

  • Problem Description

    A magic square is an arrangement of numbers (usually integers) in a square grid, where the numbers in each row, and in each column, and the numbers in the forward and backward main diagonals, all add up to the same number


    Input Format:

    The input consists of (n*n+1) integers. The first integer corresponds to the number of rows/columns in the matrix. The remaining integers correspond to the elements in the matrix. The elements are read in rowwise order, first row first, then second row and so on. Assume that the maximum value of m and n is 5.


    Output Format:
    Print yes if it is a magic square. Print no if it is not a magic square
  • Test Case 1

    Input (stdin)
    4 9 2
    
    3 5 7
    
    8 1 6
    
    
    Expected Output
    Yes
  • Test Case 2

    Input (stdin)
    4 9 2
    
    3 5 7
    
    8 1 1
    
    
    Expected Output
    No
  • Program
  • #include <stdio.h>
    int main()
    {
      int size=3;
      int a[3][3];
      int row,column=0;
      int sum,sum1,sum2;
      int flag=0;
      for(row=0;row<size;row++)
      {
        for(column=0;column<size;column++)
          scanf("%d",&a[row][column]);
      }
      sum=0;
      for(row=0;row<size;row++)
      {
        for(column=0;column<size;column++)
        {
          if(row==column)
            sum=sum+a[row][column];
        }
      }
      for(column=0;column<size;column++)
      {
        sum1=0;
        for(column=0;column<size;column++)
        {
          sum1=sum1+a[row][column];
        }
        if(sum==sum1)
          flag=1;
        else
        {
          flag=0;
          break;
        }
      }
      for(row=0;row<size;row++)
      {
        sum2=0;
        for(column=0;column<size;column++)
        {
          sum2=sum2+a[column][row];
        }
        if(sum==sum2)
          flag=1;
        else
        {
          flag=0;
          break;
        }
      }
      if(flag==1)
        printf("Yes");
      else
        printf("No");
     return 0;
    }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.