2D array – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Fri, 12 Aug 2022 17:21:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg 2D array – Programmerbay https://programmerbay.com 32 32 Java program to Add Two Matrices Using Two Dimensional Array https://programmerbay.com/java-program-to-add-two-matrices/ https://programmerbay.com/java-program-to-add-two-matrices/#respond Thu, 11 Aug 2022 10:07:13 +0000 https://www.programmerbay.com/?p=2343 The program adds two matrices with the help of two-dimensional arrays. It is achieved by frequently adding an element of first array with an element at the same index of second array and the sum stores to new array. Given two matrices below :

Java program to add two matrices

Java program to Add Two Matrices Using Two Dimensional Array

It uses the Scanner Class to accept input from the user in both the matrices and then using a nested loop, addition is performed on those matrices are performed.

Program:

public class AddTwoMatrices {
    public static void main(String[] args) {
        Scanner ed = new Scanner(System.in);
        int row, col, i, j;
        System.out.println("Enter number of rows");
        row = ed.nextInt();
        System.out.println("Enter number of column");
        col = ed.nextInt();
        int[][] a = new int[row][col];
        int[][] b = new int[row][col];
        int[][] sum = new int[row][col];
        System.out.println("Enter first matrix");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                a[i][j] = ed.nextInt();
            }
        }
        System.out.println("Enter Second matrix");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                b[i][j] = ed.nextInt();
            }
        }
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                sum[i][j] = b[i][j] + a[i][j];
            }
        }
        System.out.println("Sum of two matrices");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                System.out.print(sum[i][j]+" ");
            }
            System.out.print("\n");
        }
    }
}

Output:

Enter number of rows
2
Enter number of column
3
Enter first matrix
8
5
3
2
1
4
Enter Second matrix
5
3
2
1
5
6
7
Sum of two matrices
13 8 5 
3 6 10 

 

Explanation :

  1. It accepts the size of the matrix ( row and column ) and also the values of the matrix as input from the user for the
  2. By traversing, every element of first array added to the corresponding element of another array
  3. Lastly, Printing the array on the output screen.

]]>
https://programmerbay.com/java-program-to-add-two-matrices/feed/ 0