Here is a program to add and subtract two matrices.
//Start Of Program
import java.io.*;
class matrix
{
public static void main(String arg[]) throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int i,j,opt;
System.out.print("Enter the number of rows in both matrices: ");
i=Integer.parseInt(br.readLine());
System.out.println();
System.out.print("Enter the number of columns in both matrices: ");
j=Integer.parseInt(br.readLine());
int a[][]=new int[i][j];
int b[][]=new int[i][j];
int c[][]=new int[i][j];
System.out.println();
System.out.println("Enter the element of matrix 1:");
for(int p=0;p<i;p++)
{
System.out.println();
for(int q=0;q<j;q++)
{
System.out.println("Element "+(q+1)+" : ");
a[p][q]=Integer.parseInt(br.readLine());
}
}
System.out.println();
System.out.println("Enter the element of matrix 2:");
for(int p=0;p<i;p++)
{
for(int q=0;q<j;q++)
{
System.out.println("Element "+(q+1)+" : ");
b[p][q]=Integer.parseInt(br.readLine());
}
} System.out.println();
System.out.println("Your Matrix 1 Is:");
for(int p=0;p<i;p++)
{
System.out.println();
for(int q=0;q<j;q++)
{
System.out.print(" "+a[p][q]);
}
}
System.out.println();
System.out.println("Your Matrix 2 Is:");
for(int p=0;p<i;p++)
{
System.out.println();
for(int q=0;q<j;q++)
{
System.out.print(" "+b[p][q]);
}
}
do
{
System.out.println();
System.out.println();
System.out.println();
System.out.println(" Main Menu");
System.out.println(" 1.Add The Matrices");
System.out.println(" 2.Subtract The Matrices");
System.out.println(" 3.Exit");
opt=Integer.parseInt(br.readLine());
switch(opt)
{
case 1:
System.out.println("Sum of the two matrices is:");
for(int p=0;p<i;p++)
{
System.out.println();
for(int q=0;q<j;q++)
{
c[p][q]=a[p][q]+b[p][q];
System.out.print(" "+c[p][q]);
}
}
break;
case 2:
System.out.println("Subtraction of the matrix 2 from matrix 1 is:");
for(int p=0;p<i;p++)
{
System.out.println();
for(int q=0;q<j;q++)
{
c[p][q]=a[p][q]-b[p][q];
System.out.print(" "+c[p][q]);
}
}
break;
case 3:break;
}
}while(opt!=3);
}
}
//End Of Program
Please Comment and Follow.
No comments:
Post a Comment