Algorithm for Colsum Program
Step 1: Start the program.
Step 2: Define a class named Colsum with the following data members:
A 2D integer array matix
Two integer variables m and n for rows and columns
Step 3: Create a constructor Colsum(int mm, int nn) that initializes:
m = mm
n = nn
mat = new int[m][n]
Step 4: Define the method readArray() to input matrix elements:
Use two nested loops:
Outer loop from i = 0 to m – 1
Inner loop from j = 0 to n – 1
Inside the inner loop, read the value and store it in mat[i][j]
Step 5: Define the method check(Colsum A, Colsum B) to compare column sums:
Loop from i = 0 to n – 1
Initialize two variables sumA and sumB to 0
Loop from j = 0 to m – 1
Add [Link][j][i] to sumA
Add [Link][j][i] to sumB
If sumA is not equal to sumB, return false
After the loop ends, return true
Step 6: Define the method print() to display matrix:
Use nested loops to print all elements of mat in row-column format
Step 7: In the main() method:
Create a Scanner object for input
Ask the user to enter number of rows and columns
Store the values in rows and cols
Step 8: Create two Colsum objects m1 and m2 with rows and cols
Step 9: Display message to enter elements of Matrix A and call [Link]()
Step 10: Display message to enter elements of Matrix B and call [Link]()
Step 11: Print both matrices using the print() method
Step 12: Call [Link](m1, m2) to compare column sums
Step 13: If result is true, display "Column sums are same!"
Step 14: Else, display "Column sums are not same."
Step 15: End of program
Algorithm for Flipgram Program
Step 1: Start the program.
Step 2: Define a class named Flipgram with a data member:
String word
Step 3: Create a constructor Flipgram(String s) that:
Assigns the value of s to the data member word
Step 4: Define the method ishetero():
Loop from i = 0 to [Link]() - 2
For each character ch at position i, get the substring from i + 1 to end
If ch is found again in the substring (i.e., duplicate exists), return false
After the loop, return true (i.e., all characters are unique)
Step 5: Define the method flip():
Find the length len of the word
If len is even:
Divide the word into two halves: a = [Link](0, len/2) and b = [Link](len/2)
Return b + a
If len is odd:
Split the word into a = [Link](0, len/2), b = [Link](len/2 + 1)
Take the middle character [Link](len/2)
Return b + middle character + a
Step 6: Define the method display():
Call ishetero()
If it returns true, print "HETEROGRAM"
Else, call flip() and print the result in uppercase
Step 7: In the main() method:
Create a Scanner object to take input
Ask the user to enter a word
Store the input in variable w
Step 8: Create an object obj of Flipgram using w as argument
Step 9: Call [Link]() to execute the logic and show output
Step 10: End of program
Algorithm for SeriesSum Program
Step 1: Start the program.
Step 2: Define a class named SeriesSum with the following data members:
int x to store the value of x
int n to store the number of terms
double sum to store the result of the series
Step 3: Create a constructor SeriesSum(int xx, int nn) to:
Assign x = xx
Assign n = nn
Initialize sum = 0.0
Step 4: Define the method findFact(int m) to compute factorial recursively:
If m == 0 or m == 1, return 1.0
Otherwise, return m * findFact(m - 1)
Step 5: Define the method findPower(int x, int y) to compute power recursively:
If y == 0, return 1.0
Otherwise, return x * findPower(x, y - 1)
Step 6: Define the method calculate() to compute the series:
Loop from i = 2 to n in steps of 2
For each i, compute: x^i / (i - 1)!
Add the result to sum
Step 7: Define the method display() to print the series sum:
Display the value of sum with a label
Step 8: In the main() method:
Create a Scanner object to take input
Ask the user to input values for x and n
Read both inputs and store in xx and nn
Step 9: Create an object obj of SeriesSum using the values of x and n
Step 10: Call [Link]() to compute the series
Step 11: Call [Link]() to print the result
Step 12: End of program
Algorithm for BinSearch Program
Step 1: Start the program.
Step 2: Define a class BinSearch with:
A string array s to store words
An integer n to store the number of words
Step 3: Define the constructor BinSearch(int n):
Assign this.n = n
Create a string array s of size n
Step 4: Define the method accept() to take user input:
Create a Scanner object
Ask the user to enter n words
Use a loop from i = 0 to n - 1 to read and store each word in the array s[i]
Step 5: Define the method sort() to sort the array using bubble sort:
Use two nested loops:
Outer loop from i = 0 to n - 2
Inner loop from j = 0 to n - i - 2
In each pass, compare adjacent words using compareToIgnoreCase()
If they are in the wrong order, swap them
Step 6: Define the recursive method search(String x, int low, int high):
If low > high, return -1 (word not found)
Calculate mid = (low + high) / 2
Compare x with s[mid] using compareToIgnoreCase()
If equal, return mid
If x is smaller, search in the left half
If x is larger, search in the right half
Step 7: Define the method display():
Print the sorted array using a for-each loop
Ask the user to enter a word to search
Call the search() method with low = 0 and high = n - 1
If result is -1, print “not found”
Otherwise, print the position where the word is found
Step 8: In the main() method:
Create a Scanner object
Ask the user for the number of words
Read the number and store it in size
Create a BinSearch object using size
Call accept() to take input
Call sort() to sort the array
Call display() to show the sorted array and search result
Step 9: End of program
Algorithm for DeciHex Program
Step 1: Start the program.
Step 2: Define a class DeciHex with two data members:
int num to store the decimal number
String hexa to store the hexadecimal equivalent
Step 3: Define the constructor DeciHex():
Initialize num = 0
Initialize hexa = ""
Step 4: Define the method getNum():
Create a Scanner object
Prompt the user to enter a decimal number
Read the number as a string, convert it to integer, take its absolute value, and store in num
Step 5: Define the recursive method convert(int n):
If n == 0, assign "0" to hexa
Else:
Calculate remainder d = n % 16
If d < 10, convert it to string and add to the front of hexa
If d >= 10, use a switch statement:
10 → "A", 11 → "B", 12 → "C", 13 → "D", 14 → "E", 15 → "F"
Prepend the character to hexa
If n / 16 > 0, call convert(n / 16) recursively
Step 6: Define the method display():
Call convert(num)
Print the original decimal number
Print the hexadecimal equivalent stored in hexa
Step 7: In the main() method:
Create an object obj of class DeciHex
Call [Link]() to take input
Call [Link]() to show the conversion result
Step 8: End of program
Algorithm for SortAlpha Program
Step 1: Start
Step 2: Initialize variables
Create a class SortAlpha with:
A String variable sent to store the input sentence.
An int variable n to store the number of words.
Step 3: Accept the sentence
Read the sentence from the user.
Convert the sentence to uppercase and trim extra spaces from beginning and end.
Count the number of words:
If sentence is not empty:
Initialize n = 1.
For each character in the sentence (starting from index 1), if a space is found, increment n.
Step 4: Extract words
Append a space at the end of the sentence to capture the last word.
Create an array words[] of size n.
Initialize index = 0 and empty string word = "".
Traverse each character of the sentence:
If the character is a letter or digit, append it to word.
If the character is a space:
Store the current word in words[index].
Increment index.
Reset word to empty.
Step 5: Sort the words alphabetically
Use Bubble Sort to sort the words[] array in lexicographical (alphabetical) order:
For each word i in the array:
Compare it with the next word j.
If words[j] comes before words[i], swap them.
Step 6: Construct the sorted sentence
Add each sorted word to the sent string with a space in between.
Step 7: Display the result
Print the sorted sentence.
Step 8: Endl
Algorithm: Union and Intersection of Sets
Step 1 – Start
Define a class named Set with two data members: an integer array arr[] and an integer n.
Step 2 :Create a constructor Set(int nn) to initialize n and allocate memory for arr of size n.
Step 3 :Define a method readElements() that uses a loop and Scanner to read n elements from the user into the
array arr.
Step 4: Define a method display() that prints all the elements of the array arr using a loop.
Step 5: Define a method has(int ele) that searches for ele in the array arr; return 1 if found, else return -1.
Step 6: Define a method intersection(Set d) to compute intersection of the current set with another set d:
Create a new set object obj of size = min(this.n, d.n).
For each element in [Link], check if it exists in d using has().
If it exists, add it to [Link] and increase counter k.
Update obj.n = k and return obj.
Step 7: Define a method union(Set d) to compute union of current set with another set d:
Copy all elements of [Link] to [Link].
Create a new set object obj of size = this.n + d.n.
For each element in [Link], check if it is not present in [Link] using has().
If not present, add it to [Link] and increase counter k.
Update obj.n = k and return obj.
Step 8 : In the main(String[] args) method:
Create two Set objects obj1 and obj2 of sizes 3 and 4 respectively.
Call readElements() on both objects to input elements from the user.
Display both sets using display().
Call intersection() and store result in obj3. Display obj3.
Call union() and store result in obj4. Display obj4.
Step 9 – End
Algorithm: Tower of Hanoi using Recursion
Step 1 – Start
Step 2 – Define the Class
Create a public class named Tower to contain the logic of the Tower of Hanoi.
Step 3 – Define the shift() Method
Inside the Tower class, define a method:
public void shift(int n, String first, String middle, String last)
This method is for shifting n number of discs from the source rod (first) to the destination rod (last) using
the auxiliary rod (middle).
Step 4 – Handle the Base Case (n == 1)
Inside the shift() method: If n == 1, then only one disc needs to be moved.
Print the move: "Disc moved from A → C" (or the corresponding rod names).
Step 5 – Handle the Recursive Case (n > 1)
If n > 1, perform the following 3 recursive steps:
Move n-1 discs from the source rod (first) to the auxiliary rod (middle) using the destination rod (last) as
temporary storage.
Call: shift(n - 1, first, last, middle);
Move the nth disc (largest one) from the source rod (first) to the destination rod (last).
Print the move: "Disc moved from A -> C"
Move the n-1 discs from the auxiliary rod (middle) to the destination rod (last) using the source rod (first)
as temporary storage.
Call: shift(n - 1, middle, first, last);
Step 6 – Define the main() Method
Define the main(String[] args) method to control the flow of the program.
Step 7 – Create Object and Take Input
Inside main():
Create an object of the Tower class:
Tower ob = new Tower();
Step 8 – Call the Recursive Method
Call the shift() method using the object:
[Link](nod, "A", "B", "C");
Step 9 – End
Algorithm: Linear Queue (Lqueue)
Step 1 – Start
Step 2 – Define Class and Variables
Create a class Lqueue to implement the queue.
Declare: An integer array q[] to store elements.
Integer variables cap, front, and rear to handle capacity and tracking indices.
Step 3 – Initialize the Queue in Constructor
Define the constructor Lqueue(int nn): Set cap = nn.
Allocate memory for q as new int[cap].
Initialize both front and rear to 0 to denote an empty queue.
Step 4 – Push (Insert) Operation
Define void push(int x) method:
Check if rear < cap - 1:
If true, insert element x at position rear, then increment rear.
If false, print "QUEUE OVERFLOW" (queue is full, no more insertions allowed).
Step 5 – Pop (Remove) Operation
Define int pop() method:
Check if front != rear:
If true, increment front and return q[front] (element at the front).
If false, return -999 to indicate "QUEUE UNDERFLOW" (empty queue).
Step 6 – Display Operation
Define void display() method:
If front != rear, loop from front + 1 to rear:
Print each element of the queue.
Else, print "QUEUE UNDERFLOW" (nothing to show).
Step 7 – Main Method
Define the static main() method.
Step 8 – Menu-Driven Operations
Use a do-while loop to repeatedly show menu options:
1. Push 2. Pop 3. Display 4. Exit
Read user's choice in variable ch.
Step 9 – Handle User Choices with Switch Case
Case 1 – Push:
Ask the user to input an element.
Call [Link](x) to insert it into the queue.
Case 2 – Pop:
Call [Link]() and store result in x.
If x == -999, print "QUEUE UNDERFLOW", else print "Popped element is: x".
Case 3 – Display:
[Link]() to show all elements in the queue.
Case 4 – Exit:
Call [Link](0) to terminate the program.
Default:
Print "Invalid choice" for any other input.
Step 10 – Loop Continuation , Continue displaying the menu and performing actions until user selects choice 4 to
exit.
Step 11 – End
Algorithm : CardGame
Step 1 – Start
Step 2 – Define class and declare variables
Define the class CardGame.
Within the class, declare:
1. int[] cards → array to store card values
2. int cap → maximum number of cards
3. int top → index of the top card (initially -1)
Step 3 – Constructor
CardGame(int cc) constructor:
1. cap = cc
Creates an integer array cards of size cap
Initializes top = -1 to indicate the card pile is empty
Step 4 – Method to add a card (addCard(int v))
Checks if the stack (cards) has space:
If top < cap - 1, increments top and stores the card value at cards[top] : Prints a confirmation message
Else, prints "CARD PILE IS FULL"
Step 5 – Method to draw a card (drawCard())
Checks if there is at least one card:
If top >= 0, stores cards[top] in a variable and decrements top, returning the card
Else, returns -9999 to indicate the pile is empty
Step 6 – Start of main() method
Creates a Scanner object for input.
Prompts the user to enter the maximum number of cards.
Creates an object game of the CardGame class with the entered size.
Step 7 – Declare choice variable
Declares an integer choice to control the menu-driven loop.
Step 8 – Loop begins (do-while)
Displays a menu until the user selects the option to exit (choice 3).
Step 9 – Menu display
Inside the loop, prints: 1. Add a card 2. Draw a card 3. Exit
Then prompts the user to enter their choice.
Step 10 – Switch-case to handle choices
Case 1 – Add a card
o Prompts user for a card value
o Calls [Link](val)
Case 2 – Draw a card
Calls [Link]()
If return value is -9999, prints "No card to draw"
Else, prints the drawn card value
Case 3 – Exit
Prints "Exiting game." and breaks the loop
Default – Invalid input
Prints "Invalid choice. Try again."
Step 11 – Loop ends
The loop repeats until choice == 3.
Step 12 – End
Algorithm: Happy number
Step 1 – Start
Step 2 – Define class and declare variable
Define the class Happy.
Inside it, declare:
int n → to store the number being checked
Step 3 – Constructor
Happy() constructor: Initializes n = 0
Step 4 – Method to assign value to n
Method getnum(int nn):
Assigns the user-input number nn to the instance variable n
Step 5 – Recursive method to return sum of squares of digits
Method sum_sq_digits(int x):
If x == 0, return 0 (base case)
Else, extract last digit → x % 10
Return square of digit + recursive call for remaining digits → sum_sq_digits(x / 10)
Step 6 – Method to check if the number is happy
Method ishappy():
Start with result = n
Keep updating result = sum_sq_digits(result) in a loop
Loop continues until result becomes 1 or 4
If result == 1, the number is happy
If result == 4, the number is not happy (unhappy numbers fall into a known cycle containing 4)
Step 7 – Start of main() method
Create a Scanner object
Create an object happyNum of class Happy
Step 8 – Take user input
Prompt user to enter a number
Read the number and pass it to getnum(num) to store it in the object
Step 9 – Call ishappy()
Invoke the method ishappy() to check and print whether the number is happy or not
Step 10 – End
Algorithm: Statistics
Algorithm for class ARY
Step 1: Start
Step 2: Define abstract class ARY with integer array a[] and integer n
Step 3: Create constructor to initialize n to 0
Step 4: Define getData() to input n and read array elements from user
Step 5: Define showData() to display all array elements
Step 6: Define sort() method to sort the array in ascending order using bubble sort
Step 7: Declare abstract method display()
Step 8: End
Algorithm for class Mean
Step 1: Start
Step 2: Define class Mean extending ARY with double variable mean
Step 3: Create constructor to initialize mean to 0.0
Step 4: Define calculateMean() to compute mean as sum of all elements divided by n
Step 5: Define display() to show array elements and the mean value
Step 6: End
Algorithm for class Median
Step 1: Start
Step 2: Define class Median extending ARY with double variable median
Step 3: Create constructor to initialize median to 0.0
Step 4: Define calculateMedian() to sort the array and compute median (middle element for odd n,
average of two middle elements for even n)
Step 5: Define display() to show array elements and the median value
Step 6: End
Algorithm for class Mode
Step 1: Start
Step 2: Define class Mode extending ARY with double variable mode
Step 3: Create constructor to initialize mode to 0.0
Step 4: Define calculateMode() to sort the array and find the element with highest frequency
Step 5: Define display() to show array elements and the mode value
Step 6: End
Algorithm for class StandardDeviation
Step 1: Start
Step 2: Define class StandardDeviation extending Mean with double variable sd
Step 3: Create constructor to initialize sd to 0.0
Step 4: Define calculateSD() to compute standard deviation using the formula √(Σ(x − mean)² / n)
Step 5: Define display() to show array elements, mean, and standard deviation value
Step 6: End
Algorithm for class StatisticsProgram
Step 1: Start
Step 2: Create object of Mean and call getData() to input array elements
Step 3: Create new Mean object using same data and call display() to calculate and show mean
Step 4: Create new Median object using same data and call display() to calculate and show median
Step 5: Create new Mode object using same data and call display() to calculate and show mode
Step 6: Create new StandardDeviation object using same data and call display() to calculate and show
standard deviation
Step 7: End
Algorithm: Student Interace
Algorithm for class Student
Step 1: Start
Step 2: Define class Student with integer variable rollNumber
Step 3: Define method getNumber(int n) to assign roll number to rollNumber
Step 4: Define method putNumber() to display roll number
Step 5: End
Algorithm for class Test
Step 1: Start
Step 2: Define class Test extending Student with float variables part1 and part2
Step 3: Define method getMarks(float m1, float m2) to assign values to part1 and part2
Step 4: Define method putMarks() to display marks of part1 and part2
Step 5: End
Algorithm for interface Sports
Step 1: Start
Step 2: Define interface Sports with constant float sportwt = 6.0
Step 3: Declare abstract method putWt()
Step 4: End
Algorithm for class Result
Step 1: Start
Step 2: Define class Result extending Test and implementing Sports with float variable total
Step 3: Define method putWt() to display sports weight
Step 4: Define method display() to:
a) Calculate total = part1 + part2 + sportwt
b) Call putNumber() to display roll number
c) Call putMarks() to display marks
d) Call putWt() to display sports weight
e) Display total score
Step 5: End
Algorithm for class Hybrid (main method)
Step 1: Start
Step 2: Create Scanner object for input
Step 3: Create object r of class Result
Step 4: Input roll number from user
Step 5: Input marks for Part 1 from user
Step 6: Input marks for Part 2 from user
Step 7: Call [Link](roll) to set roll number
Step 8: Call [Link](m1, m2) to set marks
Step 9: Call [Link]() to show roll number, marks, sports weight, and total score
Step 10: Close scanner
Step 11: End
-
Algorithm for Circular Queue Program
Step 1: Start the program.
Step 2: Create a Scanner object sc to take input.
Step 3: Display "Enter capacity of queue:".
Step 4: Read integer n from the user.
Step 5: Create an object ob of class Cqueue with capacity n + 1 (extra space for circular queue logic).
Step 6: Initialize variables ch and x.
Step 7: Start a do loop to repeatedly display the menu until the user chooses 4.
Step 8: Display "[Link] [Link] [Link] [Link]".
Step 9: Display "Enter your choice:".
Step 10: Read the choice in ch.
Step 11: Use a switch(ch) to perform actions:
Step 12: Case 1 (Push): Display "Enter element to push:", read x, and call [Link](x).
Step 13: Inside push(x), check if (rear + 1) % cap != front.
Step 14: If true, update rear = (rear + 1) % cap and store x in q[rear].
Step 15: If false, display "QUEUE IS FULL".
Step 16: Case 2 (Pop): Call x = [Link]().
Step 17: Inside pop(), check if front != rear.
Step 18: If true, update front = (front + 1) % cap and return q[front].
Step 19: If false, return -999.
Step 20: If x == -999, display "QUEUE IS EMPTY", else display "Popped: " + x.
Step 21: Case 3 (Display): Call [Link]().
Step 22: Inside display(), check if front != rear.
Step 23: If true, set i = (front + 1) % cap and loop while i != (rear + 1) % cap, printing q[i] and updating i =
(i + 1) % cap.
Step 24: If false, display "QUEUE IS EMPTY".
Step 25: Case 4 (Exit): Call [Link](0).
Step 26: Default: Display "Wrong choice".
Step 27: End the switch block.
Step 28: Repeat from Step 8 while ch != 4.
Step 29: End the program.
Algorithm for Double-Ended Queue Program
Step 1: Start the program.
Step 2: Create a Scanner object sc to take user input.
Step 3: Display "Enter size of dequeue:".
Step 4: Read integer n from the user.
Step 5: Create an object ob of class Dqueue with capacity n.
Step 6: In the constructor, store cap = n, create integer array q of size cap, and set front = rear = 0.
Step 7: Declare integer variables ch and x.
Step 8: Start a do loop to repeatedly perform operations until the user chooses 6.
Step 9: Display the menu:
[Link] Front [Link] Rear [Link] Front [Link] Rear [Link] [Link].
Step 10: Display "Enter your choice:".
Step 11: Read ch using [Link]().
Step 12: Use a switch(ch) statement to perform operations:
Step 13: Case 1 (Push Front):
a. Display "Enter element to push front:".
b. Read x.
c. Call pushfront(x):
- If front != 0, decrement front and store x in q[front].
- Else display "Queue full from front".
Step 14: Case 2 (Push Rear):
a. Display "Enter element to push rear:".
b. Read x.
c. Call pushrear(x):
- If rear < cap, store x in q[rear] and increment rear.
- Else display "Queue full at rear".
Step 15: Case 3 (Pop Front):
a. Call x = popfront():
- If front != rear, return q[front] and increment front.
- Else display "Queue is empty" and return -999.
b. If x != -999, display "Popped from front: " + x.
Step 16: Case 4 (Pop Rear):
a. Call x = poprear():
- If front != rear, decrement rear and return q[rear].
- Else display "Queue is empty" and return -999.
b. If x != -999, display "Popped from rear: " + x.
Step 17: Case 5 (Display):
a. Call display():
- If front != rear, loop i from front to rear - 1 and print q[i].
- Else display "Queue is empty".
Step 18: Case 6 (Exit): Call [Link](0).
Step 19: Default: Display "Invalid choice".
Step 20: End the switch block.
Step 21: Repeat Steps 9–20 while ch != 6.
Step 22: End the program.
Algorithm: Stack Operation
Step 1: Start the program.
Step 2: Create a Scanner object sc to take user input.
Step 3: Display the message "Enter capacity".
Step 4: Read the value of cap using [Link]().
Step 5: Create an object obj of class stack with capacity cap (sets cap, top = -1, and allocates array s).
Step 6: Declare integer variables ch and x.
Step 7: Start a do loop to repeatedly show the menu until the user chooses 4.
Step 8: Display the menu "[Link] [Link] [Link] [Link]".
Step 9: Display the message "ENTER CHOICE".
Step 10: Read the choice in ch using [Link]().
Step 11: Use a switch(ch) to perform operations based on the user’s choice.
Step 12: If case 1, display "ENTER A ELEMNT TO PUSH", read x, and call push(x).
Step 13: In push(x), if top < cap - 1, increment top and store x in s[top]; otherwise display "Stack
overflows".
Step 14: If case 2, call pop() and store the result in x.
Step 15: In pop(), if top >= 0, store s[top] in x, decrement top, and return x; otherwise return -999.
Step 16: If x returned from pop() is -999, display "Stack underflows", else display "popped element is"
followed by x.
Step 17: If case 3, call display() to print stack elements from top to 0.
Step 18: If case 4, call [Link](0) to terminate the program.
Step 19: If none of the above cases match, display "wrong choice".
Step 20: Repeat steps 8–19 while ch != 4.
Step 21: End the program.