This java
program adds two matrices. First, user enters elements of two matrices,
then addition of both matrices is performed using for loop. Finally sum of both
matrices is displayed on the screen.
Java Program to Add Two Matrices
import java.util.Scanner;
class AddMatrices
{
public static void main(String[] args) {
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int c[][] = new int[3][3];
int i, j;
Scanner read = new Scanner(System.in);
System.out.print("Enter the elements of matrix1: ");
for(i = 0; i<a.length; i++)
for (j = 0; j<a.length; j++) {
a[i][j] = read.nextInt();
}
System.out.print("\nEnter the elements of matrix2: ");
for(i = 0; i<b.length; i++)
for (j = 0; j<b.length; j++) {
b[i][j] = read.nextInt();
}
System.out.println("\nAdding matrix1 and matrix2...");
for(i = 0; i<b.length; i++)
for (j = 0; j<b.length; j++) {
c[i][j] = a[i][j] + b[i][j];
}
System.out.println("\nSum of matrix1 and matrix2 is:");
for(i = 0; i<c.length; i++){
for(j = 0; j<c.length; j++){
System.out.print(c[i][j]+ "\t");
}
System.out.println();
}
}
}
Output:
Enter the elements of matrix1: 1
2
3
4
5
6
7
8
9
Enter the elements of matrix2: 1
2
3
4
5
6
7
8
9
Adding matrix1 and matrix2...
Sum of matrix1 and matrix2 is:
2 4 6
8 10 12
14 16 18
0 comments:
Post a Comment