0% found this document useful (0 votes)
5 views

1Matrixaddition

Uploaded by

N M Shishir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

1Matrixaddition

Uploaded by

N M Shishir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

Scanner;

public class MatrixAddition {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);

System.out.println("Usage: java MatrixAddition <order_N>");

// Read the size of the matrix (order N)


int N = in.nextInt();

// Validate the size of the matrix


if (N <= 0) {
System.out.println("Matrix order must be a positive integer.");
return;
}

// Create two matrices of order N


int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];

// Fill the matrices with some sample values


fillMatrix(matrix1, 1);
fillMatrix(matrix2, 2);

// Print the matrices


System.out.println("Matrix 1:");
printMatrix(matrix1);

System.out.println("\nMatrix 2:");
printMatrix(matrix2);

// Add the matrices


int[][] resultMatrix = addMatrices(matrix1, matrix2);

// Print the result matrix


System.out.println("\nResultant Matrix (Matrix1 + Matrix2):");
printMatrix(resultMatrix);
}

// Helper method to fill a matrix with sequential values


private static void fillMatrix(int[][] matrix, int startValue) {
int value = startValue;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = value++;
}
}
}

// Helper method to add two matrices


private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int N = matrix1.length;
int[][] resultMatrix = new int[N][N];

for (int i = 0; i < N; i++) {


for (int j = 0; j < N; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

return resultMatrix;
}

// Helper method to print a matrix


private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + "\t");
}
System.out.println();
}
}
}

You might also like