Write a C program to count the number of non-zero elements and sum of upper triangular
in a two-dimensional matrix using function. [Hint function should accept 2D array as
argument.]
#include <stdio.h>
#define N 5
int NumNonZeroElements(int M[N][N]) {
int i, j, count=0;
for (i=0; i<N; i++) {
for (j=0; j<N; j++) {
if (M[i][j]) {
count++;
}
}
}
return count;
}
int SumUpperTriangle(int M[N][N]) {
int i, j, sum=0;
for (i=0; i<N; i++) {
for (j=i; j<N; j++) {
sum += M[i][j];
}
}
return sum;
}
int main() {
int M[N][N] = { {1, 2, 3, 4, 5},
{0, 1, 0, 1, 0},
{2, 0, 2, 0, 2},
{3},
{0, 0, 0, 0, 4}};
int count, sum;
count = NumNonZeroElements(M);
printf("Number of non-zero elements is %d\n", count);
sum = SumUpperTriangle(M);
printf("Sum of upper triangle matrix is %d\n", sum);
return 0;
}
Comments
Leave a comment