Java Program to add two matrices
Addition of two matrices in Java.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter no of rows");
int row= sc.nextInt();
System.out.println("enter no of cols");
int col=sc.nextInt();
double[][] first =new double[row][col];
double[][] second =new double[row][col];
double[][] rezult =new double[row][col];
System.out.println("Enter First Matrix ");
for (int i=0 ;i<row;i++){
for (int j =0; j<col;j++)
first[i][j]=sc.nextDouble();
}
System.out.println("print first matrix : ");
for (int i=0 ;i<row;i++) {
System.out.print("[");
for (int j = 0; j < col; j++) {
System.out.print(first[i][j] + " ");
}
System.out.println("]");
}
System.out.println("Enter second Matrix ");
for (int i=0 ;i<row;i++){
for (int j =0; j<col;j++)
second[i][j]=sc.nextDouble();
}
System.out.println("print second matrix : ");
for (int i=0 ;i<row;i++) {
System.out.print("[");
for (int j = 0; j < col; j++) {
System.out.print(second[i][j] + " ");
}
System.out.println("]");
}
System.out.println(" Rezult Matrix ");
for (int i=0 ;i<row;i++){
for (int j =0; j<col;j++)
rezult[i][j]=first[i][j]+second[i][j];
}
System.out.println("print first matrix : ");
for (int i=0 ;i<row;i++) {
System.out.print("[");
for (int j = 0; j < col; j++) {
System.out.print(rezult[i][j] + " ");
}
System.out.println("]");
}
}}
enter no of rows
2
enter no of cols
1
Enter First Matrix
4
5
print first matrix :
[4.0 ]
[5.0 ]
Enter second Matrix
5
6
print second matrix :
[5.0 ]
[6.0 ]
Rezult Matrix
print first matrix :
[9.0 ]
[11.0 ]
Process finished with exit code 0
No comments:
Post a Comment