0% found this document useful (0 votes)
11 views5 pages

Java Matrix Addition and Stack Operations

The document provides three Java programs: one for adding two square matrices based on user input, another for implementing a stack class with basic operations, and a third for an Employee class that allows salary raises. Each program includes a main method demonstrating its functionality with sample outputs. The examples illustrate user interactions and the results of the operations performed.

Uploaded by

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

Java Matrix Addition and Stack Operations

The document provides three Java programs: one for adding two square matrices based on user input, another for implementing a stack class with basic operations, and a third for an Employee class that allows salary raises. Each program includes a main method demonstrating its functionality with sample outputs. The examples illustrate user interactions and the results of the operations performed.

Uploaded by

vidhyapatil096
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

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

import [Link];

public class AddMatrices {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter order of the square matrix (N): ");


int N = [Link]();

int[][] A = new int[N][N];


int[][] B = new int[N][N];
int[][] C = new int[N][N];

[Link]("Enter elements of first matrix:");


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
A[i][j] = [Link]();
}
}

[Link]("Enter elements of second matrix:");


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
B[i][j] = [Link]();
}
}

// Add matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}

[Link]("Sum of matrices:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
[Link](C[i][j] + " ");
}
[Link]();
}

[Link]();
}
}
OUTPUT:

Enter order of the square matrix (N): 2


Enter elements of first matrix:
12
34

Enter elements of second matrix:


56
78

Sum of matrices:
68
10 12

2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop
a JAVA main method to illustrate Stack operations.

package StackOperation;
import [Link];

class Stack {
int[] stack = new int[10]; // Stack array of size 10
int top = -1; // Top of stack

// Push operation
void push(int value) {
if (top == 9) {
[Link]("Stack Overflow! Cannot push " + value);
} else {
top++;
stack[top] = value;
[Link](value + " pushed into stack");
}
}

// Pop operation
void pop() {
if (top == -1) {
[Link]("Stack Underflow! Nothing to pop");
} else {
[Link](stack[top] + " popped from stack");
top--;
}
}

// Display stack
void display() {
if (top == -1) {
[Link]("Stack is empty!");
} else {
[Link]("Stack elements: ");
for (int i = 0; i <= top; i++) {
[Link](stack[i] + " ");
}
[Link]();
}
}
}

public class StackOperation {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Stack s = new Stack();
int choice, value;

do {
[Link]("\n--- Stack Operations Menu ---");
[Link]("1. Push");
[Link]("2. Pop");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter value to push: ");
value = [Link]();
[Link](value);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting... Goodbye!");
break;
default:
[Link]("Invalid choice! Try again.");
}
} while (choice != 4);

[Link]();
}
}
OUTPUT:

10 pushed into stack


20 pushed into stack
30 pushed into stack
Stack elements: 10 20 30
30 popped from stack
Stack elements: 10 20

3. A class called Employee, which models an employee with an ID, name and salary, is
designed as the following class diagram. The method raise Salary (percent) increases
the salary by the given percentage. Develop the Employee class and suitable main
method for demonstration.

package Employee;
public class Employee {
private int id;
private String name;
private double salary;

public Employee(int id, String name, double salary) {


[Link] = id;
[Link] = name;
[Link] = salary;
}
public void raiseSalary(double percent) {
if (percent > 0) {
double raise = salary * (percent / 100);
salary += raise;
[Link](name + "'s salary raised by " + percent + "%. New salary: " + salary);
} else {
[Link]("Please provide a positive percentage for salary raise.");
}
}
public void displayInfo() {
[Link]("Employee ID: " + id);
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}

// Main method
public static void main(String[] args) {
// Creating an employee object
Employee emp = new Employee(1001, "John Doe", 50000);

// Displaying initial information


[Link]("Initial Information:");
[Link]();

// Raising salary by a given percentage


double raisePercentage = 10;
[Link](raisePercentage);

// Displaying updated information after the raise


[Link]("\nInformation after salary raise:");
[Link]();
}
}

OUTPUT:

Initial Information:
Employee ID: 1001
Name: John Doe
Salary: 50000.0
John Doe's salary raised by 10.0%. New salary: 55000.0

Information after salary raise:


Employee ID: 1001
Name: John Doe
Salary: 55000.0

Common questions

Powered by AI

The provided JAVA programs can serve as educational tools by illustrating essential concepts of data structures and OOP. The Stack class introduces basic stack operations and helps students learn about LIFO (last-in-first-out) data structures, demonstrating practical applications of array-based stacks. The AddMatrices class enforces working with 2D arrays and matrix arithmetic, highlighting loops and data manipulation. The Employee class showcases OOP principles, such as encapsulation, object creation, and method functionality. These programs provide hands-on coding examples that can be expanded or modified to deepen understanding of JAVA programming concepts .

To improve error handling for better robustness in the JAVA programs, input validation should be incorporated. In the AddMatrices program, exceptions should be caught for mismatched input types and invalid matrix dimensions. Similarly, for the Stack class, better handling of stack overflow and underflow conditions could be implemented by throwing custom exceptions rather than just printing messages. Additionally, for any invalid user input in the menu choices, the program could be enhanced to repetitively prompt the user until valid input is entered. By using try-catch blocks and input validation methods, the programs could better guard against errors and guide users effectively .

The main method in the Employee class is designed to create an instance of the Employee with predefined attributes (ID, name, salary) and then demonstrates the functionalities of the class methods. It displays the employee's initial information using the displayInfo method, applies a salary increase using the raiseSalary method, and then displays the updated information. This approach not only tests the functionality of individual methods but also provides a clear demonstration of how the class can be used in a practical scenario .

Using command line input for matrix operations has the advantage of simplicity and direct interaction with the user in small programs. It enables quick and straightforward reading of matrix dimensions and elements directly from user input. However, it also has limitations, such as lack of scalability for large matrix sizes, limited user interaction, and no error handling for invalid inputs. The AddMatrices program handles basic input and processes matrix data but doesn't provide checks for invalid or unexpected input data, which can lead to runtime errors .

The Stack class implements three main methods: push, pop, and display. The push method adds an integer to the top of the stack if it's not full, otherwise it reports a stack overflow. The pop method removes and returns the integer from the top of the stack if it's not empty, otherwise it reports a stack underflow. The display method prints all the elements in the stack from bottom to top, indicating that the stack is not empty. This implementation allows basic stack operations such as adding, removing, and viewing elements .

Encapsulation in the Employee class is achieved by defining the class attributes (id, name, salary) as private, restricting direct access from outside the class. The class provides public methods like raiseSalary and displayInfo to manipulate and access these attributes indirectly. This design ensures that the internal state of an employee object is protected and can only be altered through the methods provided, enforcing data integrity and reducing potential misuse or errors when interacting with the object .

The challenges in implementing a matrix addition program include correctly reading input data, ensuring matrices have suitable dimensions for addition, and performing element-wise addition accurately. The AddMatrices class addresses these challenges by first ensuring that the matrices are square and of the same order, which is crucial for addition. It uses systematic loops to read matrix elements from the user and performs accurate element-wise addition by iterating through each matrix element. This reduces potential input errors and ensures correct results .

The raiseSalary method in the Employee class is significant as it allows dynamic adjustment of an employee's salary by a given percentage. This method first checks if the percentage is positive. It calculates the raise amount based on the current salary and the provided percentage, then adds this amount to the current salary, effectively modifying the employee's state by increasing their salary. This ability to adjust salary is crucial for reflecting performance-based salary increments in typical payroll systems .

The AddMatrices JAVA program demonstrates matrix addition by first reading the order N of the square matrix from the user. It then initializes three matrices A, B, and C of size N×N. The program prompts the user to input the elements for matrix A and B. It then performs matrix addition by iterating through each element, adding corresponding elements of matrices A and B, and storing the result in matrix C. Finally, it outputs the resultant matrix C showing the sum of matrices A and B .

To modify the Stack class to handle generic data types, you can use JAVA generics. Change the stack array to hold `T` type data, where `T` is a type parameter for generics. Define the Stack class with the type parameter (e.g., `class Stack<T>`), and replace all instances of `int` in the stack array and methods with `T`. This approach allows the stack to store any object type, enhancing flexibility and reusability without altering the underlying logic for stack operations .

You might also like