// Find Sum of Rows and Columns present in Matrix
// OR
// Find Sum of Elements in Matrix
import java.io.*;
public class SumOfElementsInMatrix
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a[][];
// Read Rows and Columns of Matrix from User
System.out.print("Enter Number of Rows:: ");
int m = Integer.parseInt(br.readLine());
System.out.print("Enter Number of Columns:: ");
int n = Integer.parseInt(br.readLine());
a = new int[m][n];
int i, j, sum = 0;
// Read Matrix Elements from User
System.out.println("Enter Matrix Data::");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
System.out.print("Enter Element:: ");
a[i][j] = Integer.parseInt(br.readLine());
}
}
// Displaying Matrix
System.out.println("\nMatrix is::");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
System.out.print("\t" + a[i][j]);
}
System.out.println();
}
// Perform Sum of Elements
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum = sum + a[i][j];
System.out.println("\nSum of Elements In Matrix:: " + sum);
}
}
// OR
// Find Sum of Elements in Matrix
import java.io.*;
public class SumOfElementsInMatrix
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a[][];
// Read Rows and Columns of Matrix from User
System.out.print("Enter Number of Rows:: ");
int m = Integer.parseInt(br.readLine());
System.out.print("Enter Number of Columns:: ");
int n = Integer.parseInt(br.readLine());
a = new int[m][n];
int i, j, sum = 0;
// Read Matrix Elements from User
System.out.println("Enter Matrix Data::");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
System.out.print("Enter Element:: ");
a[i][j] = Integer.parseInt(br.readLine());
}
}
// Displaying Matrix
System.out.println("\nMatrix is::");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
System.out.print("\t" + a[i][j]);
}
System.out.println();
}
// Perform Sum of Elements
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum = sum + a[i][j];
System.out.println("\nSum of Elements In Matrix:: " + sum);
}
}
OUTPUT::
Enter Number of Rows:: 2
Enter Number of Columns:: 3
Enter Matrix Data::
Enter Element:: 1
Enter Element:: 2
Enter Element:: 3
Enter Element:: 4
Enter Element:: 5
Enter Element:: 6
Matrix is::
1 2 3
4 5 6
Sum of Elements In Matrix:: 21