 ## Super friendly code & developer communities

A place for coders and developers to share, learn and grow together.

# Java Programming | Sum of Matrices using 2d arrays

This is a tutorial for sum of matrices using 2d arrays in java. The program is given below that takes two matrices from user and adds them and prints it. The program is extendable. Go enjoy the program. Lets begin...

Program for sum of matrices using 2d arrays in java.

``````
//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class MatrixSum {
//void main
public static void main (String[] args)
{
//declare int
int i,j,a[][] = new int,b[][]= new int;

//Declare input as scanner
Scanner input = new Scanner(System.in);

//Take input for matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.println("Enter Number :");
a[i][j] = input.nextInt();
}
}

//Take input for other matrix
System.out.println("Enter Other Matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.println("Enter Number :");
b[i][j] = input.nextInt();
}
}

System.out.println("Sum :-");
//print the sum matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print(a[i][j]+b[i][j]+" ");
System.out.print("\n");
}
}
}
``````

Output

Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Number :
4
Enter Number :
5
Enter Number :
6
Enter Number :
7
Enter Number :
8
Enter Number :
9
Enter Other Matrix
Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Number :
4
Enter Number :
5
Enter Number :
6
Enter Number :
7
Enter Number :
8
Enter Number :
9
Sum :-
2 4 6
8 10 12
14 16 18

How does it work
1. You enter the number.
2. The number is saved in respective array for first matrix.
3. The number is saved in respective array for second matrix.
4. Then numbers are added and printed to form of matrix.

Extending it
The program can be extended by using more numbers and making the matrix more bigger. You can also do the same program to subtract the matrices. Go ahead. Extend it.

Explanation.
1. Import the Scanner.
2. Declare the class as public
3. Add the void main function
4. Declare input as Scanner.