Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java Program to Add Two M*N Matrix From User Input

In this tutorial, we will learn how to add two M*N matrices from user input. But before moving forward, if you are not familiar with the concepts of the array, then do check the article Arrays in Java.

Below is the pictorial representation for the same.

Input:

Enter the number of rows in the first matrix: 3

Enter the number of columns in the first matrix: 3

Enter the number of rows in the second matrix: 3

Enter the number of rows in the second matrix: 3

Enter all the elements of the first matrix: 1 2 3 4 5 6 7 8 9

Enter all the elements of the second matrix: 9 8 7 6 5 4 3 2 1

Output:

First Matrix:

1 2 3

4 5 6

7 8 9

Second Matrix:

9 8 7

6 5 4

3 2 1

Resultant Matrix:

10 10 10

10 10 10

10 10 10

Program 1: Add an M*N Matrix from User Input

In this program, we will perform matrix addition. The addition of matrix is only possible when the given matrices are of the same size i.e, the number of rows and columns of both the matrices should be the same.

Algorithm

  1. Start
  2. Declare variables for matrix size
  3. Initialize the number of rows and columns for the first matrix.
  4. Initialize the number of rows and columns for the second matrix.
  5. Check whether the size of both the matrices is equal or not.
  6. If equal, ask the user to initialize the two matrices.
  7. After initializing, print the two matrices.
  8. Create a new Matrix to store the sum of the two matrices.
  9. Traverse each element of the two matrices and add them.
  10. Store this sum in the new matrix at the corresponding index.
  11. Return the resultant matrix.
  12. Print the resultant matrix.
  13. If the sizes of both the matrices are not equal then print a message to try again.
  14. Stop.

Below is the code for the same in Java language.

/*Java Program to add two matrix*/
import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
        int p, q, m, n;    //Declare matrix size
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows in the first matrix:");
        p = sc.nextInt();    //Initialize first matrix size
        System.out.print("Enter the number of columns in the first matrix:");
        q = sc.nextInt();   //Initialize first matrix size
        System.out.print("Enter the number of rows in the second matrix:");
        m = sc.nextInt();   //Initialize second matrix size
        System.out.print("Enter the number of columns in the second matrix:");
        n = sc.nextInt();   //Initialize second matrix size
        if (p == m && q == n) 
        {
            int a[][] = new int[p][q];    //Declare first matrix
            int b[][] = new int[m][n];    //Declare second matrix
            int c[][] = new int[m][n];    //Declare third matrix
            //Initialize the first matrix
            System.out.println("Enter all the elements of first matrix:");
            for (int i = 0; i < p; i++) 
            {
                for (int j = 0; j < q; j++) 
                {
                    a[i][j] = sc.nextInt();
                }
            }
            System.out.println("");
            //Initialize the second matrix
            System.out.println("Enter all the elements of second matrix:");
            for (int i = 0; i < m; i++) 
            {
                for (int j = 0; j < n; j++) 
                {
                    b[i][j] = sc.nextInt();
                }
            }
            System.out.println("");
            //Print the first matrix
            System.out.println("First Matrix:");
            for (int i = 0; i < p; i++) 
            {
                for (int j = 0; j < q; j++) 
                {
                    System.out.print(a[i][j]+" ");
                }
                System.out.println("");
            }
            //Print the second matrix
            System.out.println("Second Matrix:");
            for (int i = 0; i < m; i++) 
            {
                for (int j = 0; j < n; j++) 
                {
                    System.out.print(b[i][j]+" ");
                }
                System.out.println("");
            }
            //Loop to add matrix elements
            for (int i = 0; i < p; i++) 
            {
                for (int j = 0; j < n; j++) 
                {
                    for (int k = 0; k < q; k++) 
                    {
                        c[i][j] = a[i][j] + b[i][j];
                    }
                }
            }
            //Print the resultant matrix
            System.out.println("Matrix after addition:");
            for (int i = 0; i < p; i++) 
            {
                for (int j = 0; j < n; j++) 
                {
                    System.out.print(c[i][j]+" ");
                }
                System.out.println("");
            }
        }
        else
        {
            System.out.println("Addition not possible");
            System.out.println("Try Again");
        }
    }
}


Enter the number of rows in the first matrix:3
Enter number of columns in the first matrix: 3
Enter the number of rows in the second matrix:3
Enter the number of columns in the second matrix:3
Enter all the elements of the first matrix: 1 2 3 4 5 6 7 8 9

Enter all the elements of the second matrix: 9 8 7 6 5 4 3 2 1

First Matrix:
1 2 3
4 5 6
7 8 9
Second Matrix:
9 8 7
6 5 4
3 2 1
Matrix after addition:
10 10 10
10 10 10
10 10 10

Program 2: Add an M*N Matrix from User Input

In this program, we will add two matrices. When two matrices of order m*n and m*n are given, the resultant matrix produced will be of the order m*n. A point to be noted here is that to perform matrix addition the matrices should be of the same order.

Algorithm

  1. Start
  2. Declare variables for matrix size
  3. Initialize the number of rows and columns for the first matrix.
  4. Initialize the number of rows and columns for the second matrix.
  5. Check whether the size of both the matrices is equal or not.
  6. If equal, ask the user to initialize the two matrices.
  7. After initializing, print the two matrices.
  8. Create a new Matrix to store the sum of the two matrices
  9. Call a method that will return their sum.
  10. Traverse each element of the two matrices and add them.
  11. Store this sum in the new matrix at the corresponding index.
  12. Return the resultant matrix.
  13. Print the resultant matrix.
  14. If the sizes of both the matrices are not equal then print a message to try again.
  15. Stop.

Below is the code for the same in Java language.

/*Java Program to add two matrix*/
import java.util.Scanner;
public class Main
{
    // To print a Matrix
    static void printMatrix(int M[][],int m,int n)
    {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++)
                System.out.print(M[i][j] + " "); 
            System.out.println();
        }
    } 
    //To add the two matrices and store in matrix c
    static int[][] add(int a[][], int b[][], int m,int n)
    {
        int i, j;
        int c[][] = new int[m][m]; 
        for (i = 0; i < m; i++)
            for (j = 0; j < n; j++)
                c[i][j] = a[i][j] + b[i][j]; 
        return c;
    }
    public static void main(String[] args) 
    {
        int p, q, m, n;    //Declare matrix size
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows in the first matrix:");
        p = sc.nextInt();    //Initialize first matrix size
        System.out.print("Enter the number of columns in the first matrix:");
        q = sc.nextInt();   //Initialize the first matrix size
        System.out.print("Enter the number of rows in second matrix:");
        m = sc.nextInt();   //Initialize second matrix size
        System.out.print("Enter the number of columns in the second matrix:");
        n = sc.nextInt();   //Initialize the second matrix size
        if (p == m && q == n) 
        {
            int a[][] = new int[p][q];    //Declare first matrix
            int b[][] = new int[m][n];    //Declare second matrix            
            //Initialize the first matrix
            System.out.println("Enter all the elements of first matrix:");
            for (int i = 0; i < p; i++) 
            {
                for (int j = 0; j < q; j++) 
                {
                    a[i][j] = sc.nextInt();
                }
            }
            System.out.println("");            
            //Initialize the second matrix
            System.out.println("Enter all the elements of second matrix:");
            for (int i = 0; i < m; i++) 
            {
                for (int j = 0; j < n; j++) 
                {
                    b[i][j] = sc.nextInt();
                }
            }            
            // Print the result
            System.out.println("First Matrix:");
            printMatrix(a, m, n);            
            // Print the second matrix
            System.out.println("Second Matrix:");
            printMatrix(b, m, n);
            int c[][] = add(a, b, m,n); 
        // Print the result
        System.out.println("Resultant Matrix:");
        printMatrix(c, m, n);            
        }
        else
        {
            System.out.println("Addition not possible");
            System.out.println("Try Again");
        }
    }
}


Enter the number of rows in the first matrix:3
Enter the number of columns in the first matrix:3
Enter the number of rows in the second matrix:3
Enter the number of columns in the second matrix:3
Enter all the elements of the first matrix: 6 7 8 5 4 3 2 2 9
Enter all the elements of the second matrix: 9 8 7 6 7 8 9 9 2
First Matrix:
6 7 8
5 4 3
2 2 9
Second Matrix:
9 8 7
6 7 8
9 9 2
Resultant Matrix:
15 15 15
11 11 11
11 11 11