Replace Diagonals based on Diagonals Sum
Replace Diagonals based on Diagonals Sum
Problem Statement:
The program must accept an matrix of size NxN as the input. The program must replace all the diagonal elements of the matrix based on the following conditions.
- If the sum of the main diagonal elements is equal to the sum of opposite diagonal elements then all the diagonal elements must be replaced by 0.
- If the sum of the main diagoal elements is not equal to the sum of opposite diagonal elements then all the diagonal elements must be replaced by 1.
Finally, the program must print the modified matrix as the output.
Boundary Condition(s):
2 <= N <= 50
1 <+ Matrix element value <=10^7
Input Format:
The first line contains the value of N.
The next N line each contain N integers each separated by space(s).
Output Format:
The first N lines each contain N integers of the modified matrix separated by a space.
Example Input/Output 1:
Input:
4
1 5 9 4
3 5 2 8
7 4 1 9
3 5 4 6
Output:
0 5 9 0
3 0 0 8
7 0 0 9
0 5 4 0
Explanation:
The sum of the main diagonal elements is 13 (1 + 5 + 1 + 6).
The sum of the opposite diagonal elements is 13 (4 + 2 + 4 + 3).
Here the sum of the main diagonal elements is equal to the sum of the opposite diagonal elements.
So all the diagonal elements are replaced by 0.
Finally, the modified matrix is printed as the output.
Example Input/Output 2:
Input:
3
2 4 7
5 8 2
1 4 5
Output:
1 4 1
5 1 2
1 4 1
Note: Max Execution Time Limit: 4000 millisecs
Solution:
Programming Language: C Language
#include <stdio.h> #include <stdlib.h> int main() { int n;scanf("%d",&n); int a[n][n]; int x=0,y=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ scanf("%d",&a[i][j]); if(i==j){ x+=a[i][j]; }else if(i+j==n-1){ y+=a[i][j]; } } } int val=(x!=y); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j || i+j==n-1){ printf("%d ",val); }else{ printf("%d ",a[i][j]); } } printf("\n"); } }
//Published by PKJCODERS
(Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.)
Comments