JAVA program to find the sum of all the elements of a matrix

JAVA program to find the sum of all the elements of a matrix

This JAVA program is to find the sum of all the elements of a matrix.

For example, for a 2 x 2 matrix, the sum of all elements of the matrix {1,2,3,4} will be equal to 10.

1     2

3    4

 Sum = 1+2+3+4 = 10

Logic

We just keep adding each element of the matrix and store it in the sum variable by using two for loops(to traverse all the elements of the matrix)

Dry Run of the Program

Take input mat[][] and store elements in mat{1,2}{3,4}

Take input ‘row’ and no of rows(row) as 2

Take input ‘col’ and no of columns(col) as 2

Initialize sum=0

1st iteration for(i=0;i<row;i++) i.e. for(i=0;0<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=0+mat[0][0] i.e. sum=0+1  i.e. sum=1

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=1+mat[0][1] i.e. sum=1+2  i.e. sum=3

2nd iteration for(i=1;i<row;i++) i.e. for(i=1;1<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=3+mat[1][0] i.e. sum=3+3  i.e. sum=6

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

sum=sum+mat[i][j];  i.e.  sum=6+mat[1][1] i.e. sum=6+4  i.e. sum=10

Now we break out of inner loop and then outer loop.

Hence the sum of all the elements of the matrix[1,2][3,4] would be sum=10

Program

import java.util.*;

class arr14
{  
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		
	        int i,j,row,col,sum=0;
		
		System.out.println("Enter the number of rows:");
		row = sc.nextInt();
		System.out.println("Enter the number of columns:");
		col = sc.nextInt();

		int[][] mat = new int[row][col];
 
    		System.out.println("Enter the elements of the matrix") ;
    		for(i=0;i<row;i++)
    		{ 
	    		for(j=0;j<col;j++)
	    		{ 
	        		mat[i][j] = sc.nextInt();
    			}
		}
		
    		System.out.println("The elements of the matrix") ;
    		for(i=0;i<row;i++)
    		{ 
	    		for(j=0;j<col;j++)
	    		{ 
	       	 		System.out.print(mat[i][j]+"\t");
    			}
      	 		System.out.println("");
		}

    		for(i=0;i<row;i++)
    		{ 
	    		for(j=0;j<col;j++)
	    		{ 
				sum = sum + mat[i][j];
    			}
		}
    		System.out.println("SUM of the elements of the matrix = "+sum) ;
 	}	
}

Output

Share Me!