Write a C++ program that takes the input (or initializes randomly) in 2-dimensional square matrix of odd rows and columns. Your
program should calculate the sum of all values except the center value. Store the sum in center element of array. The program must then
display the resultant array. The program must work for all odd number square matrices. Do not write code for fixed size matrix.
#include <iostream>
using namespace std;
int main()
{
int n, sm = 0;
cin >> n;
int arr[n][n];
for(int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
if (!(i == j && i == n/2)) {
sm += arr[i][j];
}
}
}
arr[n/2][n/2] = sm;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << arr[i][j] << ' ';
}
cout << '\n';
}
return 0;
}
Comments
Leave a comment