In this tutorial you will learn about the Java Program to Add Two Matrix Using Multi-dimensional Arrays and its application with practical example.
Java Program to Add Two Matrices Using Multi-dimensional Arrays
In this tutorial, we will learn to create a Java program that will Add Two Matrix Using Multi-dimensional Arrays using Java programming.
Prerequisites:-
Before starting with the tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
Program to Add Two Matrices Using Multi-dimensional Arrays
In this program, First, we will take two matrices in input from the user using looping statements for the program. Then secondly, we will add the two matrices using the for loops into a third matrix. At last, we will print the added matrix to the user using the system. Out method.
Algorithm:-
With the help of this program, we can Add Two Matrices Using Multi-dimensional Arrays
Program:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
public class Add2Matrix{ //Body of the main function public static void main(String args[]){ //Declaring the reuired variabled for the program. int i,j; //creating two matrices for the program int x[][]={{1,2,3},{4,5,6},{7,8,9}}; int y[][]={{8,8,9},{7,6,6},{5,3,4}}; //creating another matrix to store the sum of two matrices int sum[][]=new int[3][3]; //3 rows and 3 columns //Printing the matrix 1 System.out.println("Matrix 1"); for( i=0;i<3;i++){ for( j=0;j<3;j++){ System.out.print(x[i][j]+" "); } System.out.println();//new line } //Printing the matrix 2 System.out.println("Matrix 2"); for( i=0;i<3;i++){ for( j=0;j<3;j++){ System.out.print(y[i][j]+" "); } System.out.println();//new line } //Printing the added matrix System.out.println("Added matrix"); //adding and printing addition of 2 matrices for( i=0;i<3;i++){ for( j=0;j<3;j++){ sum[i][j]=x[i][j]+y[i][j]; System.out.print(sum[i][j]+" "); } System.out.println();//new line } }} |
Output:-
In the above program, we have first initialized the required variable.
- x[][] = it will hold the integer value.
- y[][] = it will hold the integer value.
- sum[][] = it will hold the integer value.
- i= it will hold the integer value.
- j= it will hold the integer value.
Printing the first matrix to the user.
Printing the second matrix to the user.
Adding the two matrices into 1 and printing the added matrix to the user.