Saturday, 25 July 2015

Java Program to count number of 0's and 1's in n*n matrix




Given a matrix which contains only 0's and 1's .We need to count the number of occurrences of zeroes and ones in it.Its a very simple program but we get confused when it is asked by someone else and we start looking for complex solutions.


Hers is the implementation:-



 import java.util.Scanner;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class SampleMatrix {  
      public static void main(String args[]) {  
           int m, n,i,j;  
           int sum=0;  
           Scanner in = new Scanner(System.in);  
           System.out.println("Enter the number of rows and columns of matrix");  
           m = in.nextInt();  
           n = in.nextInt();  
           int first[][] = new int[m][n];  
           System.out.println("Enter the elements of first matrix");  
           for (i = 0; i < m; i++)  
                for (j = 0; j < n; j++)  
                     first[i][j] = in.nextInt();  
           for (i = 0; i < m; i++)  
                for (j = 0; j < n; j++)  
                     sum = sum+first[i][j] ;   
           System.out.println(" Count of number of 1's in the matrix:-"+sum);  
           System.out.println(" Count of number of 0's in the matrix:-"+(m*n-sum));  
      }  
 }  


No comments:

Post a Comment