0% found this document useful (0 votes)
12 views2 pages

Lab1 Program

Java

Uploaded by

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

Lab1 Program

Java

Uploaded by

nimranazia18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, 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) {


if (args.length != 1) {
System.out.println("Please provide the value of N as a command line argument.");
return;
}

int N = Integer.parseInt(args[0]);
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
Scanner scanner = new Scanner(System.in);
// Populate matrix1 and matrix2 with random values for demonstration
// You can modify this part to input values from the user or any other source
// For simplicity, we use random values between 1 and 10

/* //Reading matrix using random


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix1[i][j] = (int) (Math.random() * 10) + 1;
matrix2[i][j] = (int) (Math.random() * 10) + 1;
}
}*/

// Reading the Matrix-1


System.out.println("Enter the Elements of Matrix 1:");

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


for (int j = 0; j < N; j++) {
//matrix1[i][j] = (int) (Math.random() * 10) + 1;
//matrix2[i][j] = (int) (Math.random() * 10) + 1;
matrix1[i][j]=scanner.nextInt();
}
}

// Reading the Matrix-2


System.out.println("Enter the Elements of Matrix 2:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
//matrix1[i][j] = (int) (Math.random() * 10) + 1;
//matrix2[i][j] = (int) (Math.random() * 10) + 1;
matrix2[i][j]=scanner.nextInt();
}
}

// Perform matrix addition


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

// Display the matrices and their sum


System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("Matrix 2:");
printMatrix(matrix2);
System.out.println("Sum of the matrices:");
printMatrix(result);
}

// Helper method to print a matrix


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

You might also like