Answer to Question #215986 in C for Hemambar

Question #215986
write a C program to count the number of non zero elements in a two dimensional matrix using function with 2D array as an argument
Sample input:
input matrix: 12 17 0
100 0 1
5 4 0
Sample output:
No of non zero elements:6
1
Expert's answer
2021-07-13T13:36:12-0400
#include <stdio.h>
#include <stdlib.h>


#define M 3
#define N 3


int countNumberNonZeroElement(int* matrix){
	int nonezero=0;
	int i=0;
	int j=0;
	for(i=0;i<M;i++)
	{
		for(j=0;j<N;j++)
		{
			if((matrix + i*N)[j]!=0){
				nonezero++;
			}
		}
	}
	return nonezero;
}




int main() {
	int nonezero;
    int* matrix = (int*)malloc(M * N * sizeof(int));
    int r,c;
	int number;
 
    // assign values to the allocated memory
    for ( r = 0; r < M; r++){
        for ( c = 0; c < N; c++) {
			scanf("%d",&number);
            *(matrix + r*N + c) = number;
        }
    }
	nonezero=countNumberNonZeroElement(matrix);
	printf("\nNo of non zero elements: %d\n\n",nonezero);


    // deallocate memory
    free(matrix);


	getchar();
	getchar();
	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