QUESTION-
Input Format:
Input contains a single positive odd integer N where N <=20.
Output Format:
The output contains the matrix that satisfies the given conditions. If the value of N is even, print "INVALID".
Input Sample 1:
5
Output Sample 1:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Input Sample 2:
8
Output Sample 2:
INVALID
GUYS IF YOU HAVE ANY DOUBT PLEASE ASK IN THE COMMENT SECTION.
THANK YOU.
For a given odd number N, find out the matrix that contains elements from 1 to N 2. This matrix should satisfy the following conditions :
- Each number can occur only once in the matrix.
- The sum of all the rows, columns and diagonals must be equal.
For example, If N=3 then matrix will be
8 1 6
3 5 7
4 9 2
Here in the above matrix, the sum of all the rows, columns and diagonals will be 15.
3 5 7
4 9 2
Here in the above matrix, the sum of all the rows, columns and diagonals will be 15.
Input Format:
Input contains a single positive odd integer N where N <=20.
Output Format:
The output contains the matrix that satisfies the given conditions. If the value of N is even, print "INVALID".
Input Sample 1:
5
Output Sample 1:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Input Sample 2:
8
Output Sample 2:
INVALID
CODE-
#include<stdio.h>
#include<string.h>
// A function to generate odd sized magic squares
void generateSquare(int n)
{
int magicSquare[n][n];
// set all slots as 0
memset(magicSquare, 0, sizeof(magicSquare));
// Initialize position for 1
int i = n/2;
int j = n-1;
// One by one put all values in magic square
for (int num=1; num <= n*n; )
{
if (i==-1 && j==n) //3rd condition
{
j = n-2;
i = 0;
}
else {
// 1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
// 1st condition helper if next number
// is goes to out of square's upper side
if (i < 0)
i=n-1;
}
if (magicSquare[i][j]) //2nd condition
{
j -= 2;
i++;
continue;
}
else magicSquare[i][j] = num++; //set number
j++; i--; //1st condition
}
// Print magic square
printf("The Magic Square for n=%d:\nSum of " "each row or column %d:\n\n", n, n*(n*n+1)/2);
for (i=n-1; i>=0; i--)
{
for (j=n-1; j>=0; j--)
printf("%3d ", magicSquare[j][i]);
printf("\n");
}
}
int main()
{
int n; // Works only when n is odd
scanf("%d",&n);
if(n%2==0)
printf("invalid");
else
generateSquare (n);
return 0;
}
GUYS IF YOU HAVE ANY DOUBT PLEASE ASK IN THE COMMENT SECTION.
THANK YOU.
No comments:
Post a Comment