Java Program To Addition Of Two Matrices

01. Example:

import java.util.Scanner;

class addTwoMatrices {
    public static void main(String args[]) {
        
		int m, n, c, d;
        
		Scanner input = new Scanner(System.in);
        System.out.print("Enter Matrix Rows And Columns: ");
        m = input.nextInt();
        n = input.nextInt();
		
        int first[][] = new int[m][n];
        int second[][] = new int[m][n];
        int sum[][] = new int[m][n];
        
		System.out.print("Enter The First Matrix Elements: ");
        
		for (c = 0; c < m; c++)
            for (d = 0; d < n; d++)
                first[c][d] = input.nextInt();
        System.out.print("Enter The Second Matrix Elements: ");
        
		for (c = 0; c < m; c++)
            for (d = 0; d < n; d++)
                second[c][d] = input.nextInt();
        
		for (c = 0; c < m; c++)
            for (d = 0; d < n; d++)
                sum[c][d] = first[c][d] + second[c][d];
        
		System.out.println("nSum Of Both Matrices");
		
        for (c = 0; c < m; c++) {
            for (d = 0; d < n; d++)
                System.out.print(sum[c][d] + "t");
            System.out.println();

        }
    }
}

Output:

Enter Matrix Rows And Columns: 2 2
Enter The First Matrix Elements: 1 2 3 4
Enter The Second Matrix Elements: 1 2 3 4
Sum Of Both Matrices
2	4	
6	8

Leave a comment