Java program to find the sum of all elements of a Matrix.

SUM OF ALL ELEMENTS OF MATRIX.




                                                              In this program we have calculated sum of all elements of matrix. We have used sum  variable that is initialize to value 0 . Then by using for loop we have added single matrix element and in this way we got our result.



JAVA CODE :) 




import java.util.Scanner;


public class Matrix


{


  public static void main(String[] args)


  {


    int m,n,i,j,sum=0;


    Scanner sc= new Scanner(System.in);


    System.out.print("Enter number of rows:");


    m=sc.nextInt();


    System.out.print("Enter number of columns:");


    n=sc.nextInt();


    System.out.println("Enter "+m*n+" elements of Matrix:");


    int a[][] = new int[m][n];


    for(i=0;i<m;i++)


    {


      for(j=0;j<n;j++)


      {


         a[i][j]=sc.nextInt();


      }


    }


    sc.close();


    System.out.println("You Entered matrix is:");


    for(i=0;i<m;i++)


    {


      for(j=0;j<n;j++)


      {


        System.out.print(+a[i][j]+"  ");


        sum=sum+a[i][j];


      }


      System.out.println();


   }


   System.out.print("Sum of all elements of Matrix is:"+sum);


}


}




INPUT && OUTPUT :) 



Post a Comment

0 Comments