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

Os Module4

Uploaded by

naikmeghana369
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Os Module4

Uploaded by

naikmeghana369
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Object-Oriented Programming with JAVA (BCS306A)

Lab Programs

1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).

package oopswjava;

import java.util.Scanner;

public class MatrixAddition {


public static void main(String[] args)
{
Scanner s = new Scanner (System.in);
int p = Integer.parseInt(args[0]);
int q = Integer.parseInt(args[1]);
int m = Integer.parseInt(args[2]);
int n = Integer.parseInt(args[3]);

System.out.println("Number of rows in first matrix:" +p);


System.out.println("Number of columns in first matrix:"+q);
System.out.println("Number of rows in second matrix:"+m);
System.out.println("Number of columns in second matrix:"+n);

if (p == m && q == n)
{
int a[][] = new int[p][q];
int b[][] = new int[m][n];
int c[][] = new int[m][n];
System.out.println("Enter all the "+p*q+ " elements of first matrix:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
a[i][j] = s.nextInt();
}
}
System.out.println("Enter all the "+m*n+" elements of second matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = s.nextInt();
}
}
System.out.println("First Matrix:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println("");
}
System.out.println("Second Matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println("");
}
for (int i = 0; i < p; i++)
{
for (int j = 0; j < n; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("Matrix after addition:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println("");
}
}
else
{
System.out.println("Addition would not be possible as the order of the matrices does not
match");
}
s.close();
}
}

Output:

Run 1:

Program arguments: 3 2 3 4

Number of rows in first matrix:3


Number of columns in first matrix:2
Number of rows in second matrix:3
Number of columns in second matrix:4
Addition would not be possible as the order of the matrices does not match

Run 2:

Program arguments: 3 3 3 3

Number of rows in first matrix:3


Number of columns in first matrix:3
Number of rows in second matrix:3
Number of columns in second matrix:3
Enter all the 9 elements of first matrix:
123456789
Enter all the 9 elements of second matrix:
987654321
First Matrix:
123
456
789
Second Matrix:
987
654
321
Matrix after addition:
10 10 10
10 10 10
10 10 10

You might also like