0% found this document useful (0 votes)
2 views51 pages

Computer Project ISC

The document outlines a computer science project by Tanish Gupta, detailing various programming tasks and algorithms in Java, including average salary calculation, bank transaction simulation, product discount application, and more. Each section includes coding examples, variable listings, and algorithms for implementation. The project emphasizes object-oriented programming concepts such as encapsulation, getters, setters, and object methods.

Uploaded by

tanishgupta967
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)
2 views51 pages

Computer Project ISC

The document outlines a computer science project by Tanish Gupta, detailing various programming tasks and algorithms in Java, including average salary calculation, bank transaction simulation, product discount application, and more. Each section includes coding examples, variable listings, and algorithms for implementation. The project emphasizes object-oriented programming concepts such as encapsulation, getters, setters, and object methods.

Uploaded by

tanishgupta967
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/ 51

COMPUTER SCIENCE PROJECT

NAME : TANISH GUPTA


CLASS : XII
SECTION : A
ROLL NO. : 44
ADMISSION NO. : 147/2017
SESSION : 2025-26
CONTENT

SRL TOPIC PAGE


NO NO.
.
1 Average Salary Calculation and Professor Update Using Object
2 Bank Transaction Simulation Using Object Passing
3 Product Discount Application Using Getters, Setters, and
Object Methods in Java
4 Bank Account Details Using Encapsulation and User Input in
Java
5 Desktop Configuration and RAM Upgrade Using Encapsulation
with User Input
6 Reversing Each Word of a Sentence in Java
7 Display Words That Start and End with a Vowel from a
Sentence
8 Check and Convert a String to Palindrome by appending the
reverse
9 Generate All Non-Repeating Three-Letter Combinations of a
Word
10 Replace Each Consonant with Previous Letter, Adjusting for
Vowels and replace with next letter if previous is a vowel.
11 Frequency Analysis of Words in Uppercase Paragraph (Max 3
Sentences)
12 Merge two sorted 1D arrays in descending order using Bubble
Sort without repetition
13 To calculate the largest gap between sorted elements in 1D
array
14 Matrix Multiplication of Two n x n Matrices
15 Circular Filling of a Square Matrix with Natural Numbers
16 To Sort a Square Matrix and print sum of principal diagonal
elements
17 Mirror Image of a m x n 2D Matrix
CLASS, FUNCTION
AND ENCAPSULATION
Program 1: Average Salary Calculation and Professor Update Using Object
Passing
Coding
import java.util.Scanner;
// Class representing a bank account
class Account {
private int accNo;
private double balance;
Account(int accNo, double balance) {
this.accNo = accNo;
this.balance = balance;
}
void deposit(double amt) {
balance += amt;
}
void withdraw(double amt) {
if (amt <= balance) {
balance -= amt;
} else {
System.out.println("Insufficient balance in Account " + accNo);
}
}
public double getBalance() {
return balance;
}
public void display() {
System.out.println("Account No: " + accNo + ", Balance: " + balance);
}
}
// Class representing a Bank that handles accounts
class Bank {
void transfer(Account from, Account to, double amount) {
from.withdraw(amount);
to.deposit(amount);
}
void showAccountDetails(Account a) {
a.display();
}
}
// Main class
public class BankTransactionDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input for Account 1
System.out.println("Enter Account Number and Initial Balance for Account 1:");
int accNo1 = sc.nextInt();
double bal1 = sc.nextDouble();
Account acc1 = new Account(accNo1, bal1);
// Input for Account 2
System.out.println("Enter Account Number and Initial Balance for Account 2:");
int accNo2 = sc.nextInt();
double bal2 = sc.nextDouble();
Account acc2 = new Account(accNo2, bal2);
Bank bank = new Bank();
// Display initial balances
System.out.println("\nBefore Transaction:");
bank.showAccountDetails(acc1);
bank.showAccountDetails(acc2);
// Transaction: Transfer money
System.out.print("\nEnter amount to transfer from Account 1 to Account 2: ");
double amount = sc.nextDouble();

bank.transfer(acc1, acc2, amount);


// Display after transaction
System.out.println("\nAfter Transaction:");
bank.showAccountDetails(acc1);
bank.showAccountDetails(acc2);
sc.close();
}
}
Variable Listing
Variable Name Data Type Description
id int ID of a Professor object
salary double Salary of a Professor object
prof Professor Object of class Professor used inside the Department
dept Departmen Object of class Department used inside the University
t
p1, p2 Professor Professor objects created based on user input
avgProf Professor Professor object created using average of p1 and p2
d1, d2 Departmen Department objects holding professors
t
u1, u2 University University objects containing departments
extractedSalary double Extracted salary from a professor using a static method
id1, id2 int IDs entered by the user for two professors
salary1, salary2 double Salaries entered by the user for two professors
sc Scanner Scanner object for taking input from the user

Algorithm
Step 1: Start the program by importing the Scanner class to allow user input.
Step 2: Create a Scanner object named sc for reading values from the keyboard.
Step 3: Prompt the user to enter the ID and salary for the first professor, and store the input
in variables id1 and salary1.
Step 4: Create a Professor object p1 using id1 and salary1.
Step 5: Prompt the user to enter the ID and salary for the second professor, and store the
input in variables id2 and salary2.
Step 6: Create a Professor object p2 using id2 and salary2.
Step 7: Create two Department objects d1 and d2, passing p1 and p2 respectively to their
constructors.
Step 8: Create two University objects u1 and u2, passing d1 and d2 respectively to their
constructors.
Step 9: Display the original information of both universities by calling their show() method.
Step 10: Call the updateSalary() method on p1 and pass p2 to it, so that the salary of p1 is
updated to the salary of p2.
Step 11: Call the averageWith() method on p1 and pass p2 as an argument. Store the
returned Professor object in avgProf.
Step 12: Call the replaceProfessor() method on d1 and pass avgProf to replace the professor
in that department.
Step 13: Update university u1 by calling updateDepartment() and passing the updated
department d1.
Step 14: Display the updated university data using u1.show().
Step 15: Call the static method extractSalary() from the University class, passing u1 as an
argument, and store the returned value in extractedSalary.
Step 16: Display the extracted salary value.
Step 17: Close the Scanner object to end input reading.
Step 18: End the program.
Input

Output
Program 2: Bank Transaction Simulation Using Object Passing
Coding

import java.util.Scanner;
// Class representing a bank account
class Account {
private int accNo;
private double balance;
Account(int accNo, double balance) {
this.accNo = accNo;
this.balance = balance;
}
void deposit(double amt) {
balance += amt;
}
void withdraw(double amt) {
if (amt <= balance) {
balance -= amt;
} else {
System.out.println("Insufficient balance in Account " + accNo);
}
}
public double getBalance() {
return balance;
}
public void display() {
System.out.println("Account No: " + accNo + ", Balance: " + balance);
}
}
// Class representing a Bank that handles accounts
class Bank {
void transfer(Account from, Account to, double amount) {
from.withdraw(amount);
to.deposit(amount);
}
void showAccountDetails(Account a) {
a.display();
}
}
// Main class
public class BankTransactionDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input for Account 1
System.out.println("Enter Account Number and Initial Balance for Account 1:");
int accNo1 = sc.nextInt();
double bal1 = sc.nextDouble();
Account acc1 = new Account(accNo1, bal1);
// Input for Account 2
System.out.println("Enter Account Number and Initial Balance for Account 2:");
int accNo2 = sc.nextInt();
double bal2 = sc.nextDouble();
Account acc2 = new Account(accNo2, bal2);
Bank bank = new Bank();
// Display initial balances
System.out.println("\nBefore Transaction:");
bank.showAccountDetails(acc1);
bank.showAccountDetails(acc2);
// Transaction: Transfer money
System.out.print("\nEnter amount to transfer from Account 1 to Account 2: ");
double amount = sc.nextDouble();
bank.transfer(acc1, acc2, amount);
// Display after transaction
System.out.println("\nAfter Transaction:");
bank.showAccountDetails(acc1);
bank.showAccountDetails(acc2);
sc.close();
}
}
Variable Listing

Variable Name Data Type Description


accNo int Account number of a bank account
balance double Current balance of the account
acc1, acc2 Account Account objects created based on user input
bal1, bal2 double User input for initial balances of the accounts
accNo1, int User input for account numbers
accNo2
amount double Amount to transfer between accounts
bank Bank Object used to perform transactions and display
sc Scanner Object for reading user input from the keyboard

Algorithm
Step 1: Start the program by creating a Scanner object to read user input.
Step 2: Prompt the user to enter the account number and initial balance for the first
account. Store the values in accNo1 and bal1.
Step 3: Create an Account object acc1 using the input values.
Step 4: Repeat the same process to get details for the second account and create acc2.
Step 5: Create a Bank object named bank.
Step 6: Display the details of both accounts using the showAccountDetails() method.
Step 7: Ask the user to enter the amount to transfer from acc1 to acc2.
Step 8: Call the transfer() method from the Bank class, passing both account objects and the
transfer amount.
Step 9: After the transaction, again display the details of both accounts to show the updated
balances.
Step 10: Close the Scanner object and end the program.

Input & Output


Program 3: Product Discount Application Using Getters, Setters, and Object
Methods in Java
Coding

import java.util.Scanner;
class Product {
private String productName;
private String productCode;
private double price;
// Getter and Setter for productName
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
// Getter and Setter for productCode
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
// Getter and Setter for price
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
// Method to apply discount
public void applyDiscount(double percentage) {
if (percentage > 0 && percentage <= 100) {
price = price - (price * percentage / 100);
} else {
System.out.println("Invalid discount percentage.");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Product p = new Product();
// Input from user
System.out.print("Enter Product Name: ");
p.setProductName(sc.nextLine());
System.out.print("Enter Product Code: ");
p.setProductCode(sc.nextLine());
System.out.print("Enter Product Price: ");
p.setPrice(sc.nextDouble());
System.out.print("Enter Discount Percentage: ");
double discount = sc.nextDouble();
// Apply discount using encapsulated method
p.applyDiscount(discount);
// Output final product details
System.out.println("\n--- Product Details After Discount ---");
System.out.println("Product Name: " + p.getProductName());
System.out.println("Product Code: " + p.getProductCode());
System.out.println("Price after discount: $" + p.getPrice());
sc.close();
}
}
Variable Listing

Variable Name Data Type Description


productName String Stores the name of the product
productCode String Stores the unique code of the product
price double Stores the price of the product
product Product Object of the Product class used to access and modify
data
percentage double Discount percentage passed to the applyDiscount()
method

Algorithm

Step 1: Start the program and define a class Product with three private instance variables:
productName, productCode, and price.
Step 2: Create public getter and setter methods for each private variable to allow controlled
access.
Step 3: Create a method applyDiscount(double percentage) inside the Product class, which
reduces the price by the specified percentage.
Step 4: In the Main class, create an object p of the Product class.
Step 5: Prompt the user to enter the product name, code, and price using a Scanner.
Step 6: Ask the user to enter a discount percentage.
Step 7: Call the applyDiscount() method using the Product object.
Step 8: Use getter methods to print the final product name, code, and discounted price.
Step 9: Close the scanner and end the program.

Input

Output
Program 4: Bank Account Details Using Encapsulation and User Input in Java
Coding
import java.util.Scanner;
class Account {
// Private data members (encapsulated)
private long accNo; // Account number
private String name;
private String email;
private float amount;
// Public getter and setter methods (controlled access)
public long getAccNo() { return accNo; }
public void setAccNo(long accNo) { this.accNo = accNo; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public float getAmount() { return amount; }
public void setAmount(float amount) { this.amount = amount; }
}
// Main Class
public class Geeks
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// Create an Account object
Account acc = new Account();
// User input for account details
System.out.print("Enter Account Number: ");
acc.setAccNo(sc.nextLong());
sc.nextLine(); // Consume newline left after nextLong()
System.out.print("Enter Name: ");
acc.setName(sc.nextLine());
System.out.print("Enter Email: ");
acc.setEmail(sc.nextLine());
System.out.print("Enter Amount: ");
acc.setAmount(sc.nextFloat());
// Display values using getter methods
System.out.println("\n--- Account Details ---");
System.out.println("Account Number: " + acc.getAccNo());
System.out.println("Name: " + acc.getName());
System.out.println("Email: " + acc.getEmail());
System.out.println("Amount: " + acc.getAmount());
sc.close();
}
}

Variable Listing
Variable Name Data Description
Type
accNo long Account number of the account holder (private)
name String Name of the account holder (private)
email String Email address of the account holder (private)
amount float Account balance (private)
acc Account Object of Account class used to set and get data
sc Scanner Scanner object used to take user input from the console
Algorithm
Step 1: Define a class Account with private variables: accNo, name, email, and amount.
Step 2: Create public getter and setter methods for all variables to ensure encapsulation.
Step 3: In the main method, create a Scanner object and an object of the Account class.
Step 4: Prompt the user to enter account number, name, email, and amount using the
Scanner and set them using setter methods.
Step 5: Retrieve the entered values using getter methods and display them.
Step 6: Close the scanner and end the program.
Input
Output

Program 5: Desktop Configuration and RAM Upgrade Using Encapsulation


with User Input
Coding
import java.util.Scanner;
// Define the Desktop class
class Desktop {
// Private instance variables
private String brand;
private String processor;
private int ramSize;
// Public getter for the brand variable
public String getBrand() {
return brand;
}
// Public setter for the brand variable
public void setBrand(String brand) {
this.brand = brand;
}
// Public getter for the processor variable
public String getProcessor() {
return processor;
}
// Public setter for the processor variable
public void setProcessor(String processor) {
this.processor = processor;
}
// Public getter for the ramSize variable
public int getRamSize() {
return ramSize;
}
// Public setter for the ramSize variable
public void setRamSize(int ramSize) {
this.ramSize = ramSize;
}
// Method to upgrade the RAM size by a given value
public void upgradeRam(int additionalRam) {
if (additionalRam > 0) {
ramSize = ramSize + additionalRam;
}
}
}
// Main class
public class Main {
// Main method to test the Desktop class
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Create a new Desktop object
Desktop desktop = new Desktop();
// Input from user
System.out.print("Enter Desktop Brand: ");
desktop.setBrand(sc.nextLine());
System.out.print("Enter Processor: ");
desktop.setProcessor(sc.nextLine());
System.out.print("Enter Initial RAM Size (in GB): ");
desktop.setRamSize(sc.nextInt());
System.out.print("Enter Additional RAM to Upgrade (in GB): ");
int additionalRam = sc.nextInt();
// Upgrade RAM
desktop.upgradeRam(additionalRam);
// Display output
System.out.println("\n--- Desktop Details After Upgrade ---");
System.out.println("Brand: " + desktop.getBrand());
System.out.println("Processor: " + desktop.getProcessor());
System.out.println("RAM Size: " + desktop.getRamSize() + "GB");
sc.close();
}
}

Variable Listing
Variable Name Data Type Description
brand String Brand name of the desktop (private variable in Desktop
class)
processor String Processor type of the desktop (private)
ramSize int RAM size of the desktop in GB (private)
desktop Desktop Object of the Desktop class
additionalRam int Value of RAM to be added, input by the user
sc Scanner Scanner object to read user input

Algorithm
Step 1: Create a class Desktop with private instance variables: brand, processor, and ramSize.
Step 2: Define public getter and setter methods for all three variables to implement
encapsulation.
Step 3: Include a method upgradeRam(int additionalRam) in the class that adds the specified
RAM to the current RAM.
Step 4: In the main method, create an object of the Desktop class.
Step 5: Prompt the user to input the desktop’s brand, processor, and initial RAM size.
Step 6: Ask the user for how much RAM they want to add.
Step 7: Call the upgradeRam() method with the user input to increase RAM.
Step 8: Display the final desktop details using getter methods.
Step 9: End the program by closing the Scanner.

Input

Output
STRING HANDLING
Program 6: Reversing Each Word of a Sentence in Java
Coding
import java.util.*;
class New_Delhi {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String s, st = "", pw = "";
char c, ch = ' ';
int i, len, l, j;
System.out.println("Enter the String");
s = in.nextLine();
s = s + " ";
l = s.length();
for (i = 0; i < l; i++) {
c = s.charAt(i);
if (c != ' ') {
st = st + c; // create word
} else {
len = st.length();
for (j = len - 1; j >= 0; j--) {
ch = st.charAt(j);
pw = pw + ch;
}
System.out.print(pw + " ");
st = "";
pw = "";
}
}
in.close();
}
}

Variable Listing
Variable Data Type Description
Name
s String Input sentence entered by the user
st String Temporary string to build each word
pw String Stores the reversed word before printing
c char Each character of the input string
ch char Temporary character used while reversing
i, j int Loop counters
len int Length of the word being reversed
l int Length of the entire string
in Scanner Scanner object to take user input

Algorithm
Step 1: Import the Scanner class and define the main class and method.
Step 2: Prompt the user to enter a sentence.
Step 3: Append a space at the end of the input string to ensure the last word is processed.
Step 4: Loop through each character of the string.
Step 5: If the character is not a space, add it to the word string st.
Step 6: If a space is encountered, reverse the collected word st and print it.
Step 7: Reset the temporary variables st and pw after each word is printed.
Step 8: Continue until the full string is processed.
Step 9: Close the scanner and end the program.

Input & Output


Program 7: Display Words That Start and End with a Vowel from a Sentence
Coding
import java.util.*;
class begin_end_vowel {
public static void main() {
Scanner sc = new Scanner(System.in);
String s, w = "";
int i;
int c = 0;
char ch1 = 0, ch2 = 0;
System.out.print("Enter a sentence: ");
s = sc.nextLine().toUpperCase();
s = s + " ";
System.out.println("\nWords starting and ending with a vowel are:");
for (i = 0; i < s.length(); i++) {
char x = s.charAt(i);
if (x == ' ') {
if (w.length() > 0) {
ch1 = w.charAt(0);
ch2 = w.charAt(w.length() - 1);
if ((ch1 == 'A' || ch1 == 'E' || ch1 == 'I' || ch1 == 'O' || ch1 == 'U') &&
(ch2 == 'A' || ch2 == 'E' || ch2 == 'I' || ch2 == 'O' || ch2 == 'U')) {
System.out.println("- " + w);
c++;
}
w = "";
}
} else {
w = w + x; // creating each word
}
}
if (c == 0) {
System.out.println("No words found that start and end with a vowel.");
}
System.out.println("\nTotal words starting and ending with a vowel: " + c);
sc.close();
}
}

Variable Listing
Variable Name Data Type Description
sc Scanner Used to take user input
s String Input sentence (converted to uppercase)
w String Temporarily stores each word being formed
i int Loop counter
c int Counter for number of words starting and ending with a
vowel
ch1 char First character of a word
ch2 char Last character of a word
x char Current character being read from the input string

Algorithm
Step 1: Import the Scanner class and declare required variables.
Step 2: Ask the user to enter a sentence and convert it to uppercase.
Step 3: Append a space at the end of the sentence to process the last word.
Step 4: Traverse the sentence character by character.
Step 5: If the character is not a space, build the word character by character.
Step 6: When a space is found, check if the built word starts and ends with a vowel.
Step 7: If it does, print the word and increase the count.
Step 8: After the loop, print the total number of such words.
Step 9: End the program.

Input
Output

Program 8: Check and Convert a String to Palindrome by appending the


reverse
Coding
import java.util.Scanner;
class palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many strings would you like to check? ");
int count = in.nextInt();
in.nextLine(); // Consume the leftover newline
for (int k = 1; k <= count; k++) {
System.out.println("\n--- String " + k + " ---");
System.out.print("Enter a string: ");
String str = in.nextLine().toUpperCase();
String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
}
System.out.println("\nOriginal String: " + str);
System.out.println("Reversed String: " + rev);
if (str.equals(rev)) {
System.out.println("Result: The string is a Palindrome.");
} else {
System.out.println("Result: The string is NOT a Palindrome.");
System.out.println("Converted Palindrome: " + (str + rev));
}
}
System.out.println("\n=== PROGRAM ENDED ===");
in.close();
}
}

Variable Listing
Variable Name Data Type Description
in Scanner Scanner object to take user input
str String User input string (converted to uppercase)
rev String Reverse of the input string
i, k int Loop counters (i for reversing, k for repetitions)
count int Number of strings user wants to check

Algorithm
Step 1: Import Scanner and create a scanner object.
Step 2: Ask the user how many strings they want to check.
Step 3: Use a loop to repeat the process for the given number of times.
Step 4: Inside the loop, take string input and convert it to uppercase.
Step 5: Reverse the string using a loop and store it in a new string.
Step 6: Compare the original and reversed strings using .equals().
Step 7: If equal, print that it is a palindrome.
Step 8: If not, print the reversed string and the new palindrome formed by appending the
reverse.
Step 9: End the program after all iterations are complete.

Input & Output


Program 9: Generate All Non-Repeating Three-Letter Combinations of a Word
Coding
import java.util.*;
public class Combinations {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String str;
int i, j, k, p;
System.out.println("Enter a three letter word:");
str = in.next();
str = str.toUpperCase();
p = str.length();
System.out.println("The required combinations of the word:");
for (i = 0; i < p; i++) {
for (j = 0; j < p; j++) {
for (k = 0; k < p; k++) {
if (i != j && j != k && k != i) {
System.out.print(str.charAt(i) + "" + str.charAt(j) + "" + str.charAt(k));
System.out.println();
}
}
}
}
}
}
Variable Listing
Variable Data Type Description
Name
in Scanner Scanner object for user input
str String Stores the input three-letter word
i, j, k int Loop counters to generate combinations
p int Length of the input string (should be 3)

Algorithm
Step 1: Import the Scanner class and create an object for input.
Step 2: Prompt the user to enter a three-letter word.
Step 3: Convert the word to uppercase for uniform output.
Step 4: Store the length of the word in a variable p.
Step 5: Use three nested loops with variables i, j, and k to generate all index positions.
Step 6: Ensure that the indices are not equal (i.e., no repetition of the same position).
Step 7: Print each valid combination of characters from the input word.
Step 8: Repeat for all valid unique index combinations.

Input

Output
Program 10: Replace Each Consonant with Previous Letter, Adjusting for
Vowels and replace with next letter if previous is a vowel.
Coding
import java.util.*;
public class ReplaceConsonants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();
String vowels = "AEIOUaeiou";
StringBuilder newSentence = new StringBuilder();
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (Character.isLetter(ch)) {
char prevChar = (char)(ch - 1);
if (!vowels.contains(String.valueOf(ch)) && Character.isLetter(prevChar)) {
if (vowels.contains(String.valueOf(prevChar))) {
ch = (char)(ch + 1); // Replace with next letter if prev is vowel
} else {
ch = prevChar; // Replace with previous letter
}
}
}
newSentence.append(ch);
}
System.out.println("Modified sentence:");
System.out.println(newSentence.toString());
}
}

Variable Listing
Variable Name Data Type Description
sc Scanner Scanner object for taking user input
sentence String Original sentence entered by the user
vowels String String containing all uppercase and lowercase vowels
newSentence StringBuilder To build the modified sentence with replaced characters
i int Loop counter for traversing the input sentence
ch char Current character being processed
prevChar char Previous alphabet character of current one

Algorithm
Step 1: Import Scanner class and create an object to take user input.
Step 2: Accept a sentence from the user.
Step 3: Define a string containing all vowels (both uppercase and lowercase).
Step 4: Create an empty StringBuilder to store the new sentence.
Step 5: Loop through each character of the original sentence.
Step 6: If the character is a letter and a consonant:
→ Find the previous letter in the alphabet.
→ If that previous letter is a vowel, use the next letter instead.
→ Otherwise, use the previous letter.
Step 7: If the character is not a consonant, keep it unchanged.
Step 8: Append the modified character to the new sentence.
Step 9: After the loop, print the final modified sentence.
Input

Output

Program 11: Frequency Analysis of Words in Uppercase Paragraph (Max 3


Sentences)
Coding
import java.util.Scanner;
public class WordFrequency {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of sentences: ");
int n = sc.nextInt();
sc.nextLine(); // consume newline
if (n < 1 || n > 3) {
System.out.println("INVALID INPUT. Number of sentences must be between 1 and
3.");
return;
}
System.out.println("Enter sentences:");
String paragraph = "";
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
paragraph += line + " ";
}
paragraph = paragraph.toUpperCase().trim();
paragraph = paragraph.replaceAll("[^A-Z ]", ""); // remove punctuation
String[] words = paragraph.split("\\s+");
System.out.println("Total number of words: " + words.length);
String[] uniqueWords = new String[words.length];
int[] freq = new int[words.length];
int uniqueCount = 0;
for (int i = 0; i < words.length; i++) {
boolean found = false;
for (int j = 0; j < uniqueCount; j++) {
if (words[i].equals(uniqueWords[j])) {
freq[j]++;
found = true;
break;
}
}
if (!found) {
uniqueWords[uniqueCount] = words[i];
freq[uniqueCount] = 1;
uniqueCount++;
}
}

// Sort by frequency (ascending)


for (int i = 0; i < uniqueCount - 1; i++) {
for (int j = i + 1; j < uniqueCount; j++) {
if (freq[i] > freq[j]) {
// Swap frequencies
int tempFreq = freq[i];
freq[i] = freq[j];
freq[j] = tempFreq;
// Swap corresponding words
String tempWord = uniqueWords[i];
uniqueWords[i] = uniqueWords[j];
uniqueWords[j] = tempWord;
}
}
}
// Display results
System.out.printf("%-10s%-10s%n", "WORDS", "FREQUENCY");
for (int i = 0; i < uniqueCount; i++) {
System.out.printf("%-10s%-10d%n", uniqueWords[i], freq[i]);
}
}
}

Variable Listing
Variable Data Type Description
Name
sc Scanner To take user input
n int Number of sentences entered by the user
paragraph String Combined paragraph formed by appending all
sentences
line String Stores each sentence entered in the loop
words[] String[] Array of all words extracted from the paragraph
uniqueWords[] String[] Array to store each unique word
freq[] int[] Array to store frequency count corresponding to words
uniqueCount int Total number of unique words
found boolean Flag to check if a word is already counted
tempFreq int Temporary variable for swapping frequencies
tempWord String Temporary variable for swapping words
i,j int Loop control variables

Algorithm
Step 1: Import Scanner class and create a Scanner object to take user input.
Step 2: Ask the user to enter the number of sentences.
Step 3: Check if n is between 1 and 3. If not, print an error and exit.
Step 4: Use a loop to take n sentences and join them into one string.
Step 5: Convert the string to uppercase and remove all punctuation.
Step 6: Split the cleaned string into words using space as delimiter.
Step 7: Print the total number of words.
Step 8: Loop through all words and build an array of unique words with their frequencies.
Step 9: Sort the unique words in ascending order based on their frequencies using nested
loops.
Step 10: Print the words and their frequencies in a tabular format.

Input
Output
ARRAY

Program 12: Merge two sorted 1D arrays in descending order using Bubble
Sort without repetition
Coding
import java.util.Scanner;
public class Merge {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N, M, i, j, k, temp;
int size = 0;
System.out.print("Enter number of elements in A: ");
N = in.nextInt();
int A[] = new int[N];
System.out.println("Enter " + N + " elements for A:");
for(i = 0; i < N; i++) {
A[i] = in.nextInt();
}
System.out.print("Enter number of elements in B: ");
M = in.nextInt();
int B[] = new int[M];
System.out.println("Enter " + M + " elements for B:");
for(i = 0; i < M; i++) {
B[i] = in.nextInt();
}
// Sorting A in descending order
for(i = 0; i < N - 1; i++) {
for(j = 0; j < N - 1 - i; j++) {
if(A[j] < A[j + 1]) {
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
// Sorting B in descending order
for(i = 0; i < M - 1; i++) {
for(j = 0; j < M - 1 - i; j++) {
if(B[j] < B[j + 1]) {
temp = B[j];
B[j] = B[j + 1];
B[j + 1] = temp;
}
}
}
// Merging arrays A and B into C without duplicates
int C[] = new int[N + M];
for(i = 0; i < N; i++) {
boolean found = false;
for(j = 0; j < size; j++) {
if(A[i] == C[j]) {
found = true;
break;
}
}
if(!found) {
C[size] = A[i];
size++;
}
}
for(i = 0; i < M; i++) {
boolean found = false;
for(j = 0; j < size; j++) {
if(B[i] == C[j]) {
found = true;
break;
}
}
if(!found) {
C[size] = B[i];
size++;
}
}
// Sorting merged array C in descending order
for(i = 0; i < size - 1; i++) {
for(j = 0; j < size - 1 - i; j++) {
if(C[j] < C[j + 1]) {
temp = C[j];
C[j] = C[j + 1];
C[j + 1] = temp;
}
}
}
// Displaying all arrays
System.out.println("SORTED ARRAYS");
System.out.print("A[]: ");
for(i = 0; i < N; i++) {
System.out.print(A[i] + " ");
}
System.out.println();
System.out.print("B[]: ");
for(i = 0; i < M; i++) {
System.out.print(B[i] + " ");
}
System.out.println();
System.out.println("MERGED ARRAY");
System.out.print("C[]: ");
for(i = 0; i < size; i++) {
System.out.print(C[i] + " ");
}
}
}
Variable Listing
Variable Data Description
Name Type
N int Number of elements in array A
M int Number of elements in array B
A[] int[] Array of size N storing input elements for array A
B[] int[] Array of size M storing input elements for array B
C[] int[] Array to store merged elements from A and B without duplicates
size int Number of valid elements in array C after merging
i,j,k int Loop control variables
temp int Temporary variable used during element swapping in sorting
found boolean Flag used to detect duplicate elements during merge

Algorithm
Step 1: Import Scanner class and create a Scanner object to accept input from the user.
Step 2: Input the sizes of the arrays: N (for A[]) and M (for B[]).
Step 3: Input N elements into array A[] and M elements into array B[].
Step 4: Sort both arrays in descending order using nested loops (basic bubble sort logic).
Step 5: Create a merged array C[] and copy elements of both arrays into C[], skipping
duplicates.
Step 6: Sort the final merged array C[] in descending order using nested loops.
Step 7: Display all three arrays: A[], B[], and C[].

Input
Output

Program 13: To calculate the largest gap between sorted elements in 1D array
Coding
import java.util.Scanner;
public class LargestGap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input number of elements
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
if (n < 2) {
System.out.println("Array must have at least two elements.");
return;
}
int[] arr = new int[n];
// Input array elements
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Sort the array using simple bubble sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display sorted array
System.out.print("Sorted Array: ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
// Find the largest gap
int maxGap = 0;
for (int i = 1; i < n; i++) {
int gap = arr[i] - arr[i - 1];
if (gap > maxGap) {
maxGap = gap;
}
}
System.out.println("Largest Gap: " + maxGap);
}
}Variable Listing

Variable Name Data Description


Type
sc Scanner To take user input
n int Number of elements in the array
arr[] int[] Array to store user input integers
i, j int Loop control variables for input and sorting
temp int Temporary variable to swap elements during sorting
gap int Difference between two consecutive sorted elements
maxGap int Stores the maximum gap found between sorted elements

Algorithm
Step 1: Import the Scanner class and create a Scanner object to take input from the user.
Step 2: Prompt the user to enter the number of elements and store it in n.
Step 3: If n < 2, print an error message and exit, since at least 2 elements are required for a
gap.
Step 4: Create an integer array arr of size n.
Step 5: Use a loop to take n integer inputs from the user and store them in the array.
Step 6: Sort the array using bubble sort by comparing and swapping adjacent elements.
Step 7: Display the sorted array.
Step 8: Initialize a variable maxGap to 0.
Step 9: Loop through the sorted array and calculate the gap between every two adjacent
elements.
Step 10: If the gap is greater than maxGap, update maxGap.
Step 11: Print the final value of maxGap.
Input

Output

Program 14: Matrix Multiplication of Two n x n Matrices


Coding
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input matrix size
System.out.print("Enter the size of the square matrices (n): ");
int n = sc.nextInt();
int[][] A = new int[n][n];
int[][] B = new int[n][n];
int[][] C = new int[n][n];
// Input elements of matrix A
System.out.println("Enter elements of Matrix A:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = sc.nextInt();
}
}
// Input elements of matrix B
System.out.println("Enter elements of Matrix B:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
B[i][j] = sc.nextInt();
}
}
// Multiply A and B, store in C
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Display Matrix A
System.out.println("Matrix A:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(A[i][j] + "\t");
}
System.out.println();
}
// Display Matrix B
System.out.println("Matrix B:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(B[i][j] + "\t");
}
System.out.println();
}
// Display result matrix C
System.out.println("Product Matrix C (A x B):");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(C[i][j] + "\t");
}
System.out.println();
}
}
}

Variable Listing
Variable Data Type Description
Name
sc Scanner To take user input
n int Size of the square matrices (n × n)
A[][] int[][] First matrix input
B[][] int[][] Second matrix input
C[][] int[][] Result matrix after multiplying A and B
i, j, k int Loop control variables for rows and columns

Algorithm
Step 1: Import the Scanner class and create a Scanner object to take user input.
Step 2: Ask the user to enter the size n of the square matrices.
Step 3: Declare three 2D arrays A, B, and C of size n × n.
Step 4: Input the elements of matrix A using nested loops.
Step 5: Input the elements of matrix B using nested loops.
Step 6: Use three nested loops to multiply A and B and store the result in matrix C:
→ For each cell C[i][j], calculate the sum of A[i][k] * B[k][j].
Step 7: Print matrix A and matrix B.
Step 8: Print matrix C after multiplication.
Input

Output
Program 15: Circular Filling of a Square Matrix with Natural Numbers
Coding
import java.util.Scanner;
public class CircularMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Step 1: Input matrix size
System.out.print("Enter the size of the matrix (n): ");
int n = sc.nextInt();
int[][] mat = new int[n][n];
int num = 1; // Number to fill
int top = 0, bottom = n - 1, left = 0, right = n - 1;
// Step 2: Fill the matrix in circular layers
while (num <= n * n) {
// Left to Right (Top Row)
for (int i = left; i <= right; i++) {
mat[top][i] = num++;
}
top++;
// Top to Bottom (Right Column)
for (int i = top; i <= bottom; i++) {
mat[i][right] = num++;
}
right--;
// Right to Left (Bottom Row)
for (int i = right; i >= left; i--) {
mat[bottom][i] = num++;
}
bottom--;
// Bottom to Top (Left Column)
for (int i = bottom; i >= top; i--) {
mat[i][left] = num++;
}
left++;
}
// Step 3: Print the matrix
System.out.println("The matrix filled in circular fashion:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
}
}
Variable Listing
Variable Name Data Type Description
sc Scanner To take user input
n int Size of the square matrix
mat[][] int[][] 2D array to store natural numbers in circular
fashion
num int Current number to be inserted
top int Top boundary index of the current layer
bottom int Bottom boundary index of the current layer
left int Left boundary index of the current layer
right int Right boundary index of the current layer
i, j int Loop control variables

Algorithm
Step 1: Import Scanner class and accept input n from the user.
Step 2: Create a 2D array mat[n][n] and initialize num = 1.
Step 3: Define boundaries top, bottom, left, and right.
Step 4: Run a loop until num <= n², and in each iteration:
→ Fill top row left to right
→ Fill right column top to bottom
→ Fill bottom row right to left
→ Fill left column bottom to top
→ Update boundaries accordingly after each direction
Step 5: Print the matrix row by row.

Input

Output
Program 16: To Sort a Square Matrix and print sum of principal diagonal
elements
Coding
import java.util.Scanner;
public class SortedMatrixDiagonalSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Step 1: Input matrix size
System.out.print("Enter the size of the matrix (n): ");
int n = sc.nextInt();
int[][] mat = new int[n][n];
int[] temp = new int[n * n];
int index = 0;
// Step 2: Input matrix elements
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
temp[index++] = mat[i][j]; // Copy to temp array
}
}
// Step 3: Display the original matrix
System.out.println("Original Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
// Step 4: Sort the temp array
for (int i = 0; i < temp.length - 1; i++) {
for (int j = i + 1; j < temp.length; j++) {
if (temp[i] > temp[j]) {
int t = temp[i];
temp[i] = temp[j];
temp[j] = t;
}
}
}
// Step 5: Refill sorted elements into matrix
index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = temp[index++];
}
}
// Step 6: Display sorted matrix
System.out.println("Sorted Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
// Step 7: Calculate sum of principal diagonal
int sum = 0;
for (int i = 0; i < n; i++) {
sum += mat[i][i];
}
System.out.println("Sum of principal diagonal elements: " + sum);
}
}

Variable Listing
Variable Name Data Type Description
sc Scanner To take user input
n int Size of the square matrix
mat int[][] 2D array to store matrix elements
temp int[] 1D array to hold all matrix elements for sorting
index int Index pointer for temp array
i, j int Loop control variables
t int Temporary variable used during sorting
sum int Sum of principal diagonal elements

Algorithm
Step 1: Import Scanner class and input matrix size n.
Step 2: Declare a 2D array mat[n][n] and a 1D array temp[n*n].
Step 3: Input elements into mat and simultaneously store in temp.
Step 4: Display the original matrix.
Step 5: Sort the temp array using nested loops.
Step 6: Refill the sorted values back into mat row-wise.
Step 7: Display the sorted matrix.
Step 8: Sum the elements of the principal diagonal (mat[i][i]).
Step 9: Display the sum.
Input

Output
Program 17: Mirror Image of a m x n 2D Matrix
Coding
import java.util.Scanner;
public class MirrorImageMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Step 1: Input matrix size
System.out.print("Enter number of rows (m): ");
int m = sc.nextInt();
System.out.print("Enter number of columns (n): ");
int n = sc.nextInt();
int[][] mat = new int[m][n];
int[][] mirror = new int[m][n];
// Step 2: Input matrix elements
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
}
}
// Step 3: Create mirror image
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mirror[i][j] = mat[i][n - 1 - j]; // reverse each row
}
}
// Step 4: Display original matrix
System.out.println("Original Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
// Step 5: Display mirror image matrix
System.out.println("Mirror Image Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mirror[i][j] + "\t");
}
System.out.println();
}
}
}
Variable Listing
Variable Data Type Description
Name
sc Scanner To take user input
m int Number of rows in the matrix
n int Number of columns in the matrix
mat int[][] 2D array to store original matrix elements
mirror int[][] 2D array to store the mirror image of the matrix
i, j int Loop control variables

Algorithm
Step 1: Import Scanner and input values of m and n.
Step 2: Declare a 2D array mat[m][n] for the original matrix and mirror[m][n] for the mirror
image.
Step 3: Take input for all elements of mat.
Step 4: For each row, reverse the order of its elements and store it in mirror.
Step 5: Display the original matrix.
Step 6: Display the mirror image matrix.

Input
Output

You might also like