Friday, February 3, 2017

Find the total number of 1 and 0 from any matrix in C language

Find the total number of 1 and 0 from any matrix in C language:

#include<stdio.h>

int main(){



    int mat[4][4] = {{1, 0, 0, 1},

                     {0, 1, 1, 0},

                     {0, 1, 1, 0},

                     {1, 0, 0, 1}

                    };

    int i, j, k, total1 = 0, total0 = 0;





    for(i = 0; i < 4; i++){

        for(j = 0; j < 4; j++){

            if(mat[i][j] == 0){

                total0 += 1;

            }else{

                total1 += 1;

            }

        }

    }



    printf("Total Number of 1 is: %d\n", total1);

    printf("Total Number of 0 is: %d\n", total0);

}


In this code, we find the total number of 1 and 0 from the given 4*4 matrix.
Step to write the code:

    int mat[4][4] = {{1, 0, 0, 1},

                     {0, 1, 1, 0},

                     {0, 1, 1, 0},

                     {1, 0, 0, 1}

                    };

In this line we've initialize the matrix.
And then set some imnitial value for totaling our number of 1 and number of 0's.
int i, j, k, total1 = 0, total0 = 0;

Then,
    for(i = 0; i < 4; i++){

        for(j = 0; j < 4; j++){

            if(mat[i][j] == 0){

                total0 += 1;

            }else{

                total1 += 1;

            }

        }

    }
In this line, we have a for loop which will run upto 4 or user choices input as you wish. Since it was a 4*4 matrix so, we provably need 2 for loops upto 4. One is for row and other columns. Then,
           if(mat[i][j] == 0){

                total0 += 1;

            }
In this line we get the value at any location from the matrix and if we get any 0 then we increase our total0 variable as 1 else increase total1 variable as 1.

That's the simple code, If you face any problem in this code, comment please. I'm ready to answer you.





No comments:

Post a Comment