public class MatrixAddition { for (int j = 0; j < N; j++) { class Stack { program 2
public static void main(String[] args) { resultMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; } } int top;
if (args.length != 1) { return resultMatrix; int stack[]=new int[10];
System.out.println("Usage: java MatrixAddition <order N>"); // Function to print a matrix Stack() {
return;} private static void printMatrix(int[][] matrix) { top=-1;}
int N = Integer.parseInt(args[0]); for (int[] row : matrix) { void push(int item) {
if (N <= 0) { for (int value : row) { if (top==9) {
System.out.println("Please enter a positive integer for N."); System.out.print(value + " "); } System.out.println("Stack is full. Cannot push " + item); } else{
return; } System.out.println(); } stack[++top] = item } }
int[][] matrixA = generateMatrix(N); System.out.println(); } }} int pop() {
int[][] matrixB = generateMatrix(N); if (top<0) { System.out.println("Stack underflow. Cannot pop.");
System.out.println("Matrix A:"); return -1; // Assuming -1 is not a valid element in the stack }
printMatrix(matrixA); else {
System.out.println("Matrix B:"); return stack[top--]; }}
printMatrix(matrixB); void display()
int[][] resultMatrix = addMatrices(matrixA, matrixB); { if (top < 0) {
System.out.println("Sum of Matrix A and Matrix B:"); System.out.println("Stack is empty.");
printMatrix(resultMatrix); } else {
} System.out.print("Stack elements: ");
// Function to generate a random matrix of order N for (int i = 0; i <= top; i++) {
private static int[][] generateMatrix(int N) { System.out.print(stack[i] + " ");
int[][] matrix = new int[N][N]; }
for (int i = 0; i < N; i++) { System.out.println();
for (int j = 0; j < N; j++) { }
matrix[i][j] = i*3+j; // Random integer between 0 and 9 } }
return matrix; } }
// Function to add two matrices
private static int[][] addMatrices(int[][] matrixA, int[][] matrixB) { public class TestStack
int N = matrixA.length; {
int[][] resultMatrix = new int[N][N]; public static void main(String[] args)
for (int i = 0; i < N; i++) { {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
for(int i=0;i<10;i++) mystack1.push(i);
for(int i=0;i<10;i++) mystack2.push(i);
mystack1.display();
mystack2.display();
System.out.println("\n");
for(int i=0;i<10;i++)
System.out.print(mystack1.pop()+" ");
System.out.println("\n");
for(int i=0;i<10;i++)
System.out.print(mystack2.pop()+" ");