0% found this document useful (0 votes)
57 views1 page

Matrix Java

This Java program performs matrix addition by first taking input for the dimensions and elements of two matrices. It checks if the matrices have the same dimensions before proceeding with the addition, and then displays the resulting matrix. If the dimensions do not match, it informs the user that addition is not possible.

Uploaded by

Nagaraj Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views1 page

Matrix Java

This Java program performs matrix addition by first taking input for the dimensions and elements of two matrices. It checks if the matrices have the same dimensions before proceeding with the addition, and then displays the resulting matrix. If the dimensions do not match, it informs the user that addition is not possible.

Uploaded by

Nagaraj Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.util.

Scanner;
public class Matrix{
public static void main(String [] args){
int p,q,m,n,i,j;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the number of rows in the first matrix");
p=sc.nextInt();
System.out.print("Enter the number of colums in the first matrix");
q=sc.nextInt();
System.out.print("Enter the number of rows in the second matrix");
m=sc.nextInt();
System.out.print("Enter the number of rows in the second matrix");
n=sc.nextInt();

if (p==m&&q==n){
int a [][]=new int [p][q];
int b [][]=new int [m][n];
int c [][]=new int [p][n];

System.out.println("Enter all the elements of the first matrix");


for (i=0; i<p; i++){
for (j=0; j<q; j++){
a[i][j]=sc.nextInt();
}
}
System.out.println(" ");

System.out.println("Enter all the elements of the second matrix");


for (i=0; i<m; i++){
for (j=0; j<n; j++){
b[i][j]=sc.nextInt();
}
}
System.out.println(" ");

System.out.println("first matrix");
for (i=0; i<p; i++){
for (j=0; j<q; j++){
System.out.print(a[i][j]+" ");
}
System.out.println(" ");
}

System.out.println("second matrix");
for (i=0; i<m; i++){
for (j=0; j<n; j++){
System.out.print(b[i][j]+" ");
}
System.out.println(" ");
}

for (i=0; i<p; i++){


for (j=0; j<n; j++){
c[i][j]=a[i][j]+b[i][j];
}
}

System.out.println("matrix after addition");


for (i=0; i<p; i++){
for (j=0; j<n; j++){
System.out.print(c[i][j]+" ");
}
System.out.println(" ");
}
}
else{
System.out.println("matrix addition not possible, matrices must have same demins
sion");
System.out.println("try again");
}
}
}

You might also like