Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 26: Write a Java program to calculate the subtraction of two matrices entered by the user.

Subtraction.java

import java.util.Scanner;

public class Subtraction
{
	public static void main(String[] args)
	{
		int row;
		int col;
		Scanner s = new Scanner(System.in);
		
		System.out.println("Enter the size of the square matrix");
		row=s.nextInt();
		col=s.nextInt();

		//Input Elements in matrix-1.
		int a[][] = new int[row][col];
		System.out.println("Enter elements of first matrix");

		for(int i=0; i < row; i++)
		{
			for(int j=0;j < col;j++)
			{
				System.out.print("Enter "+i+j+" element: ");
				a[i][j]=s.nextInt();	
			}
		}
		
		//Input Elements in matrix-2.
		int b[][] = new int[row][col];
		System.out.println("Enter elements of second matrix");

		for(int i=0; i < row; i++)
		{
			for(int j=0;j < col;j++)
			{
				System.out.print("Enter "+i+j+" element: ");
				b[i][j]=s.nextInt();	
			}
		}
		
		//Subtraction of the matrix-1 and matrix-2.
		int c[][] = new int[row][col];

		for(int i=0; i < row; i++)
		{
			for(int j=0;j < col;j++)
			{
				c[i][j] = a[i][j]-b[i][j];	
			}
		}
		
		//Displaying the resultant matrix.
		System.out.println("Difference of two matrices");
		for(int i=0; i < row; i++)
		{
			for(int j=0;j < col;j++)
			{
				System.out.print(c[i][j]+" ");
			}
			System.out.println();
		}
	}
}


If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.