0% found this document useful (0 votes)
58 views13 pages

Java Array and Matrix Operations Quiz

The document contains Java programs for various tasks including rearranging positive and negative numbers in an array, finding saddle points in a matrix, counting specific patterns in a string, and managing a bank system with depositors. Each program includes a description of the problem, the method to solve it, and the corresponding code implementation. The document is structured with clear sections for each question, including input and output examples.

Uploaded by

Vrindaa Sharma
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)
58 views13 pages

Java Array and Matrix Operations Quiz

The document contains Java programs for various tasks including rearranging positive and negative numbers in an array, finding saddle points in a matrix, counting specific patterns in a string, and managing a bank system with depositors. Each program includes a description of the problem, the method to solve it, and the corresponding code implementation. The document is structured with clear sections for each question, including input and output examples.

Uploaded by

Vrindaa Sharma
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

NAME: VRINDAA SHARMA

SEC: I2
[Link]: 127
Q6. The problem to rearrange positive and negative numbers in an array Method: This
approach moves all negative numbers to the beginning and positive numbers to the end but
changes the order of appearance of the elements of the array.
Steps:
1. Declare an array and input the array elements.
2. Start traversing the array and if the current element is negative, swap the current element
with the first positive element and continue traversing until all the elements have been
encountered.
3. Print the rearranged array.
Test case:
Input: 1-1 2-2 3-3
Output: -1-2-313 2
SOL:

import [Link].*;
public class ques_6 {
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
[Link]("enter array size: ");
int n = [Link]();
int arr[] = new int[n];
[Link]("enter elements: ");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
int j=0;
for(int i=0; i<n; i++) {
if(arr[i]<0){
if(i!=j){
swap(arr, i, j);
}
j++;
}
}
for(int i=0; i<n; i++){
[Link](arr[i]+" ");
}
}
public static void swap(int ar[], int a, int b){
int temp = ar[a];
ar[a] = ar[b];
ar[b] = temp;
}
}
OUTPUT:
NAME: VRINDAA SHARMA
SEC: I2
[Link]: 127Q7. Program to find the saddle point coordinates in a given matrix. A saddle
point is an element of the matrix, which is the minimum element in its row and the maximum
in its column.
For example, consider the matrix given below
Mat[3][3]
123
456
789 SOL:
import [Link];
public class ques_7 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int[][] matrix = new int[3][3];
[Link]("Enter the matrix elements:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = [Link]();
}
}
boolean found = false;
for (int i = 0; i < 3; i++) {
int minRowIndex = 0;
for (int j = 1; j < 3; j++) {
if (matrix[i][j] < matrix[i][minRowIndex]) {
minRowIndex = j;
}
}
boolean isSaddlePoint = true;
for (int k = 0; k < 3; k++) {
if (matrix[k][minRowIndex] > matrix[i][minRowIndex]) {
isSaddlePoint = false;
break;
}
}
if (isSaddlePoint) {
[Link]("Saddle Point found at (" + i + ", " + minRowIndex + ") with
value " + matrix[i][minRowIndex]);
found = true;
break;
}
}
if (!found) {
[Link]("No Saddle Point found.");
}
[Link]();
}
}

OUTPUT:
NAME: VRINDAA SHARMA
SEC: I2
[Link]: 127
Q8. Program to find all the patterns of 0(1+)0 in the given string. Given a string containing
0's and 1's, find the total number of 0(1+)0 patterns in the string and output it. 0(1+)0 - There
should be at least one '1' between the two 0's.
For example, consider the following string.
Input: 01101111010
Output: 3
Explanation:
01101111010 - count = 1
01101111010 - count = 2
01101111010-count = 3

SOL:
import [Link].*;
public class ques_8{
public static int pat(String ab) {
int count = 0;
for (int i = 0; i < [Link]() - 1; i++) {
if ([Link](i) == '0') {
int j = i + 1;
while (j < [Link]() && [Link](j) == '1') {
j++;
}
if (j > i + 1 && j < [Link]() && [Link](j) == '0') {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the string: ");
String in = [Link]();
[Link]();
int res = pat(in);
[Link]("Input: " + in);
[Link]("Output: " + res);
}
}

OUTPUT:
NAME: VRINDAA SHARMA
SEC: I2
[Link]: 127
Q9. Write a java program to create a class named 'Bank ' with the following data members:
Name of depositor Address of depositor Account Number Balance in account Class 'Bank'
has a method for each of the following:
1 - Generate a unique account number for each depositor For first depositor, account number
will be 1001, for second depositor it will be 1002 and so on
2 - Display information and balance of depositor
3 - Deposit more amount in balance of any depositor
4 - Withdraw some amount from balance deposited
5 - Change address of depositor After creating the class, do the following operations
1 - Enter the information (name, address, account number, balance) of the depositors.
Number of depositors is to be entered by user.
2 - Print the information of any depositor.
3 - Add some amount to the account of any depositor and then display final information of
that depositor
4 - Remove some amount from the account of any depositor and then display final
information of that depositor
5 - Change the address of any depositor and then display the final information of that
depositor
6 - Randomly repeat these processes for some other bank accounts

SOL:

import [Link];
class Bank {
private static int accountCounter = 1000;
private String name;
private String address;
private int accountNumber;
private double balance;
public Bank(String name, String address, double balance) {
[Link] = name;
[Link] = address;
[Link] = ++accountCounter;
[Link] = balance;
}
public int getAccountNumber() {
return accountNumber;
}
public void displayInfo() {
[Link]("\nAccount Number: " + accountNumber);
[Link]("Name: " + name);
[Link]("Address: " + address);
[Link]("Balance: " + balance);
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Amount deposited successfully.");
} else {
[Link]("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Amount withdrawn successfully.");
} else {
[Link]("Invalid withdrawal amount or insufficient balance.");
}
}
public void changeAddress(String newAddress) {
[Link] = newAddress;
[Link]("Address updated successfully.");
}
}
public class ques_9 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter number of depositors: ");
int numDepositors = [Link]();
[Link]();
Bank[] accounts = new Bank[numDepositors];
for (int i = 0; i < numDepositors; i++) {
[Link]("\nEnter details for depositor " + (i + 1));
[Link]("Name: ");
String name = [Link]();
[Link]("Address: ");
String address = [Link]();
[Link]("Initial Balance: ");
double balance = [Link]();
[Link]();
accounts[i] = new Bank(name, address, balance);
[Link]("Account created successfully! Account Number: " +
accounts[i].getAccountNumber());
}
while (true) {
[Link]("\nSelect an option:");
[Link]("1. Display depositor info");
[Link]("2. Deposit amount");
[Link]("3. Withdraw amount");
[Link]("4. Change address");
[Link]("5. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
if (choice == 5) {
[Link]("Exiting program.");
break;
}
[Link]("Enter account number: ");
int accNum = [Link]();
[Link]();
Bank selectedAccount = null;
for (int i = 0; i < numDepositors; i++) {
if (accounts[i].getAccountNumber() == accNum) {
selectedAccount = accounts[i];
break;
}
}
if (selectedAccount == null) {
[Link]("Account not found!");
continue;
}
switch (choice) {
case 1:
[Link]();
break;
case 2:
[Link]("Enter amount to deposit: ");
double depositAmount = [Link]();
[Link](depositAmount);
[Link]();
break;
case 3:
[Link]("Enter amount to withdraw: ");
double withdrawAmount = [Link]();
[Link](withdrawAmount);
[Link]();
break;
case 4:
[Link]("Enter new address: ");
String newAddress = [Link]();
[Link](newAddress);
[Link]();
break;
default:
[Link]("Invalid choice! Try again.");
}
}
[Link]();
}
}
OUTPUT:

Common questions

Powered by AI

Scanners in Java efficiently facilitate user input, as evident in the examples provided. They allow reading and parsing different data types from standard input, streamlining the process of acquiring necessary variables such as array sizes, matrix elements, or account details. This feature is crucial in interactive programs, improving usability by dynamically reading inputs and performing operations based on user instructions .

The approach in Source 1 involves traversing the array, and when a negative number is encountered, it is swapped with the first positive number encountered earlier. This ensures that all negative numbers are moved to the beginning of the array, while positive numbers are moved to the end. However, this method does alter the order of appearance of the array elements, meaning the original sequence of appearance of numbers is not preserved .

Possible user interaction issues include limited error handling and input validation, which could lead to runtime errors or unreliable data if unexpected user input is provided. The current examples await correct data types without checks against outliers or misinputs, necessitating additional validations and exception handling mechanisms to enhance robustness and user experience, especially in interactive banking applications and computations .

The 0(1+)0 pattern requires at least one '1' between two '0's in a string of 0's and 1's. The pattern count is calculated by iterating through the string, identifying '0's, and checking subsequent characters to ensure they are '1's until another '0' is found. Each occurrence of such a sequence increments the count, as detailed in the provided code snippet, which thoroughly checks each possible substring to ensure all qualifying patterns are counted .

To identify a saddle point in a matrix, traverse each row to find the minimum element. Then, check if this element is the largest in its respective column. If both conditions are met, the element is a saddle point. In the example provided, each row’s minimum is compared to other elements in its column to validate if it’s also the column’s maximum. If no such element is found, it is concluded that there is no saddle point .

Modularity is achieved through the division of tasks into discrete methods that handle specific functionalities. For example, the array rearrangement approach utilizes a 'swap' method. Similarly, the 'Bank' class delineates different operations like 'deposit' and 'withdraw' into separate methods, maintaining clean and manageable code. This modularity allows individual components to be developed, tested, and maintained independently, enhancing code reusability and readability .

Both algorithms use direct iteration over elements (nested loops), which results in time complexity concerns. For pattern recognition in strings, the worst-case scenario involves O(n) time complexity, where n is the string length, due to each character along with subsequent checks until '0' is found after '1's. In the matrix, the saddle point search also demonstrates a time complexity of O(n^2) due to iterating over rows and confirming conditions against columns. While these methods are straightforward, they aren't optimized for larger datasets, indicating potential inefficiency .

The array rearrangement method inverts the order of appearance for negative and positive numbers, thus lacking stability if original order must be preserved. For identifying saddle points, the algorithm can only accurately process square matrices and struggles with larger or non-standard dimensions due to its straightforward nature. Furthermore, both methods exhibit limitations in scalability, hampering performance on larger datasets .

The 'Bank' class implementation leverages object-oriented programming principles. Key techniques include encapsulation, where data members like name, address, and balance are accessed through public methods. Each account is uniquely identified by an auto-incremented account number. Methods handle functionalities such as displaying information, deposit, withdrawal, and updating addresses, showcasing polymorphism through method overloading and structured control flow to execute repeated operations on multiple accounts .

The 'Bank' class assigns a unique account number to each depositor by incrementing a static counter starting from 1000 with each new object instantiation. This strategy ensures that each Bank object is uniquely identifiable, which is critical for operations like deposits, withdrawals, and information updates, helping in managing database integrity and avoiding conflicts in multi-user environments .

You might also like