Header Ads

Monday 26 December 2022

Write a Java program for Matrix Addition. Make necessary assumptions.

 Write a Java program for Matrix Addition. Make necessary assumptions.

Topic: Matrix Addition in Java Program

Here is a Java program that performs matrix addition:

Program Code:

import java.util.Scanner; public class MatrixAddition { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of rows and columns of the matrices:"); int rows = sc.nextInt(); int cols = sc.nextInt(); // Assume that the matrices are square matrices (same number of rows and columns) int[][] matrix1 = new int[rows][cols]; int[][] matrix2 = new int[rows][cols]; int[][] resultMatrix = new int[rows][cols]; System.out.println("Enter the elements of the first matrix:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix1[i][j] = sc.nextInt(); } } System.out.println("Enter the elements of the second matrix:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix2[i][j] = sc.nextInt(); } } // Perform matrix addition for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } System.out.println("The result of the matrix addition is:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(resultMatrix[i][j] + " "); } System.out.println(); } } }

This program prompts the user to enter the number of rows and columns for the matrices, and then asks the user to enter the elements of the two matrices. The program then performs matrix addition and prints the result to the console

Note that this program assumes that the matrices being added are square matrices (i.e., they have the same number of rows and columns). If you want to handle matrices with different numbers of rows and columns, you can modify the program to check for this and handle it appropriately.
IGNOU MCS-206 PGDCA SOLVED ASSIGNMENT QUESTION 2023

0 comments:

Post a Comment