Find sum of all the elements of matrix using Java


 

Find sum of all the elements of matrix using Java

A matrix is a rectangular array of numbers. In this section, you will learn how to find the sum of elements of the matrix using Core Java.

A matrix is a rectangular array of numbers. In this section, you will learn how to find the sum of elements of the matrix using Core Java.

Find sum of all the elements of matrix using Java

A matrix is a rectangular array of numbers. The numbers in the matrix are called its entries or its elements. A matrix with m rows and n columns is called m-by-n matrix or m × n matrix,where m and n are its dimensions. 

Description of code:

Through the following code, we have allowed the user to enter the number of rows and columns and the elements they wish to be in the matrix. These elements are stored into the two dimensional array. Now to determine the sum of all these elements, we have initialized a variable sum to 0 and create for loops to iterate throughout the array of matrix and add each element of the matrix to the variable sum. Finally, this variable get the sum of all the elements.

Here is the code:

import java.io.*;
import java.util.*;

public class matrix {
	public static void main(String[] args) throws IOException {
		int rows, cols;
		int sum = 0;
		int[][] matrix;
		Scanner input = new Scanner(System.in);
		System.out.print("Enter number of rows: ");
		rows = input.nextInt();
		System.out.print("Enter number of columns: ");
		cols = input.nextInt();
		matrix = new int[rows][cols];
		System.out.println("Enter elements for Matrix");
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				matrix[i][j] = input.nextInt();
			}
		}
		System.out.println("Matrix is: ");
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				sum = sum + matrix[i][j];
				System.out.print(matrix[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println("Sum of all elements is: " + sum);
	}
}

Output:

Enter number of rows: 3
Enter number of columns: 3
Enter elements for Matrix
1
2
3
4
5
6
7
8
9
Matrix is:
1  2  3
4  5  6
7  8  9
Sum of all elements is: 45

Ads