Write A Program In Java To Add Two 3*3 Matrices

0

Write A Program In Java To Add Two 3*3 Matrices

Write A Program In Java To Add Two 3*3 Matrices

In this program, we will create a java program to to add two 3*3 matrices.


For this program we will create two matrix with help of multi dimensional array and the sum of all data element which available in given two matrix are stored in another matrix named "sum".


we will also use for loop to perform addition of each data element in stored in matrix as well as we use for loop to print our result lets see the program.


PROGRAM

public class MatrixAddition
{
    public static void main(String[] args)
    {
        int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
        int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };

        int[][] sum = new int[3][3];

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                sum[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        System.out.println("Matrix 1:");
        printMatrix(matrix1);
        System.out.println("Matrix 2:");
        printMatrix(matrix2);
        System.out.println("Sum:");
        printMatrix(sum);
    }

    public static void printMatrix(int[][] matrix)
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
    }
}


OUTPUT

Matrix 1: 1 2 3 4 5 6 7 8 9 Matrix 2: 9 8 7 6 5 4 3 2 1 Sum: 10 10 10 10 10 10 10 10 10


Explanation

In this program, we first define two 3x3 matrices (matrix1 and matrix2) and initialize them with some values. We then create a new 3x3 matrix (sum) to hold the result of the addition.


We use a nested for loop to iterate over each element of the matrices and add the corresponding elements together to get the sum matrix. Finally, we print out all three matrices using the printMatrix method. 


❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Post a Comment

0Comments
Post a Comment (0)