Answer to Question #286647 in C for Aumma

Question #286647

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.]




1
Expert's answer
2022-01-11T09:44:22-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS