Problem statement :-Write a program to add two matrices
package Loops;import java.util.Scanner;
public class whileloop {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the no of rows and coloumns :");
int rows=sc.nextInt();
int cols=sc.nextInt();
int A[][]=new int[rows][cols];
int B[][]=new int[rows][cols];
int C[][]=new int[rows][cols];
System.out.println("enter the matrice A");
for(int i=0;i<rows;i++) {
for(int j=0;j<cols;j++) {
A[i][j]=sc.nextInt();
}
}
System.out.println("enter the matrice B");
for(int i=0;i<rows;i++) {
for(int j=0;j<cols;j++) {
B[i][j]=sc.nextInt();
}
}
for(int i=0;i<rows;i++) {
for(int j=0;j<cols;j++) {
C[i][j]=A[i][j]+B[i][j];
}
}
System.out.println("Result matrice C is: ");
for(int i=0;i<rows;i++) {
for(int j=0;j<cols;j++) {
System.out.print(C[i][j]+" ");
System.out.println();
}
}
System.out.println();
}
}
output:-
enter the no of rows and coloumns :
3 2
enter the matrix A
4 2
3 4
5 6
enter the matrix B
3 5
8 7
9 1
Result matrice C is:
7 7
11 11
14 7
Comments
Post a Comment