codescracker


java

Java Program to Add Two Matrices



« Previous Program Next Program »


Add Two Matrices

To add two matrices in Java Programming, you have to ask to the user to enter the elements of both the 3*3 matrix, now start adding the two matrix to form a new/third matrix which is the addition result of the two given matrix. After adding the two matrices, display the third matrix which is the result of the addition of the two matrices.

Java Programming Code to Add Two Matrices

Following Java Program add two 3*3 matrices to form the third matrix :

/* Java Program Example - Add Two Matrices */
		
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int i, j;
       int mat1[][] = new int[3][3];
       int mat2[][] = new int[3][3];
       int mat3[][] = new int[3][3];
       Scanner scan = new Scanner(System.in);
	   
       System.out.print("Enter Matrix 1 Elements : ");
       for(i=0; i<3; i++)
       {
           for(j=0; j<3; j++)
           {
               mat1[i][j] = scan.nextInt();
           }
       }
	   
       System.out.print("Enter Matrix 2 Elements : ");
       for(i=0; i<3; i++)
       {
           for(j=0; j<3; j++)
           {
               mat2[i][j] = scan.nextInt();
           }
       }
	   
       System.out.print("Adding both Matrix to form the Third Matrix...\n");
       for(i=0; i<3; i++)
       {
           for(j=0; j<3; j++)
           {
               mat3[i][j] = mat1[i][j] + mat2[i][j];
           }
       }
	   
       System.out.print("The Two Matrix Added Successfully..!!\n");
	   
       System.out.print("The New Matrix will be :\n");
       for(i=0; i<3; i++)
       {
           for(j=0; j<3; j++)
           {
               System.out.print(mat3[i][j]+ " ");
           }
           System.out.println();
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program add two matrix

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test