Java Programs

TheFestFever.com

Our aim is to connect students from campuses all over Delhi by making them aware of all Technical, Cultural, Management fests, workshops, Seminars organized by every college in Delhi.

Join Us Now

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

Addition.java

import java.util.Scanner;

public class Addition
{
	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();	
			}
		}
		
		//Addition 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("Sum 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.