Q2) Write a function that calculates the sum of even elements in the right-diago
ID: 3709242 • Letter: Q
Question
Q2) Write a function that calculates the sum of even elements in the right-diagonal and the left diagonal. Then prints the results and print the elements of matrix A in the main. The following is the matrix: int A[4114]22, 23, 78, 28 }, 44, 65, 77, 18}, 132,23, 20, 13}, 15,25, 10, 15} I; The sum of the even elements in the right diagonal-28 The sum of the even elements in the left diagonal-42 void sumEven(int A[I[4], int &right;, int &left;, int size); Note to distinguish the diagonals: Left diagonal elements are à Aij where i-j Right diagonal elements à Aij where i+j = size-1Explanation / Answer
To find out the sum of the even elements in right and left diagonals there is no need of sending the middle two arguments. Here I using only two arguments in the sumEven() function.
#include <stdio.h>
#define SIZE 4
/* Calculate sum of the even elements in right and left diagonals */
void sumEven(int A[][SIZE], int size)
{
/* Indexes to traverse Array elements */
int i = 0;
int j = 0;
/* To store the sum */
int sum = 0;
/* Calculate sum of even element in right diagonal */
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if ((A[i][j] % 2) == 0) {
if ((i + j) == (size - 1))
sum += A[i][j];
}
}
}
printf("The sum of the even elements in the right diagonal = %d ", sum);
sum = 0;
/* Calculate sum of even element in left diagonal */
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if ((A[i][j] % 2) == 0) {
if (i == j)
sum += A[i][j];
}
}
}
printf("The sum of the even elements in the left diagonal = %d ", sum);
}
int main()
{
/* Array Initialization */
int A[SIZE][SIZE] = {
{22, 23, 78, 28},
{44, 65, 77, 18},
{32, 23, 20, 13},
{15, 25, 10, 15}
};
/* Indexes to traverse Array */
int i = 0;
int j = 0;
sumEven(A, SIZE);
printf("Array elements: ");
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("%d ", A[i][j]);
}
printf(" ");
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.