Consider a square matrix A of size nxn and an integer x which is an element of A. find the row number R and column number C of X in A, and calculate the sum R and C. If the sum is even, find the sum of the digits of all even numbers in the matrix, and if the sum is odd then find the sum of digits of all odd numbers in matrix
#include <iostream> // standart C++ library for input and output stream
using namespace std; // including namespace std
int calculate_sum_digits(int x) { // function that returns sum of digits of number x
int answer = 0;
while (x >= 0) {
answer += x % 10; // add the left digit of x
x /= 10; // delete the left digit of x
}
return answer;
}
int main() {
int n, x;
cin >> n >> x;
int A[n][n];
int even_sum = 0, odd_sum = 0;
int R = -1, C = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
if (A[i][j] % 2 == 0)
even_sum += calculate_sum_digits(A[i][j]); // add the sum of digits if A[i][j] is even
else
odd_sum += calculate_sum_digits(A[i][j]); // same but if A[i][j] is odd
if (A[i][j] == x) {
R = i;
C = j; // found element x
}
}
}
if (R == -1 && C == -1) {
cout << "No element x in matrix A, exiting program..."; // there is no element x in A
exit(0);
}
if ((R + C) % 2 == 0) { // if R + C is even
cout << even_sum; // print sum of digits of even numbers in A
} else {
cout << odd_sum; // print sum of digits of odd numbers in A
}
}
Comments
Leave a comment