Question 1:-
Flipogram Algorithm
1. Start
→ Marks the beginning of the program execution.
2. Create a class named Flipgram
→ Define a user-defined class `Flipgram` to encapsulate all
operations related to the word (like checking heterogram and
flipping).
3. Declare a String variable ‘word’ as a data member
→ Inside the class, declare a `String` variable `word` to hold the
word input from the user.
4. Define a constructor that accepts a String ‘s’
→ Create a constructor `Flipgram(String s)` to initialize the class
with a word passed by the user.
5. Inside the constructor, assign ‘s’ to the data member ‘word’
→ Set the value of the instance variable `word` to the parameter
`s` passed during object creation.
6. Define a method ‘ishetero()’ which returns a boolean
→ This method checks whether the word has all unique
characters (i.e., is a heterogram) and returns `true` or `false`.
7. Loop through the string from index 0 to word.length()-2
→ Use a `for` loop to iterate through each character (except the
last) to check for repetition.
8. In each iteration, assign the current character to variable ‘ch’
→ Extract the current character using `charAt(i)` and store it in
`ch`.
9. Create a substring ‘s’ from the next character to the end
→ Use `substring(i + 1)` to get all characters after the current
character.
10. Check if ‘s’ contains character ‘ch’
→ Use `s.indexOf(ch)` to check if the current character appears
again in the rest of the string.
11. If yes, return false
→ If a duplicate is found, return `false` because it's not a
heterogram.
12. After loop ends, return true
→ If no duplicates are found, return `true`, meaning the word is a
heterogram.
13. Define a method ‘flip()’ that returns a String
→ This method rearranges the word based on its length (even or
odd) and returns the flipped version.
14. Find the length of ‘word’ and assign to ‘len’
→ Store the word’s length in the variable `len` for processing.
15. If ‘len’ is even, split ‘word’ into two equal halves: ‘a’ and ‘b’
→ Use `substring()` to divide the word into two equal parts if the
length is even.
16. Return concatenation of ‘b’ and ‘a’
→ Flip the word by placing the second half before the first half
and return the new string.
17. Else, split ‘word’ into two parts excluding middle character: ‘a’
and ‘b’
→ For odd lengths, split the word around the middle character.
Exclude the middle from both `a` and `b`.
18. Return concatenation of ‘b’, middle character, and ‘a’
→ Place the second half first, then the middle character, then the
first half (i.e., `b + mid + a`).
19. Define a method ‘display()’ that checks if the word is a
heterogram
→ A display method to decide what output to show the user.
20. If true, print "HETEROGRAM", else print the flipped word in
uppercase
→ If the word is a heterogram, display "HETEROGRAM";
otherwise, display the flipped version in uppercase.
21. In the main() method, create Scanner object
→ Start the execution from `main()`, create a `Scanner` to accept
user input.
22. Prompt the user to enter a word and store in variable ‘w’
→ Display a message asking for input, and store it in `w`.
23. Create an object of class Flipgram passing ‘w’
→ Create an instance of `Flipgram` with the entered word so we
can process it.
24. Call the ‘display()’ method using the object
→ Use the object to invoke the `display()` method, which prints
the final result.
25. End
→ Marks the end of the algorithm and the program.
Variable Description Data Type
word Stores the input String
word to be
processed
s (in constructor) Temporary variable String
to store the passed
input string
ch Holds a character char
from word during
iteration
s (in ishetero()) Holds the substring String
after the current
character
len Stores the length of int
the input word
a First part of the String
string used in flip
operation
b Second part of the String
string used in flip
operation
w Stores user input String
from scanner
in Scanner object to Scanner
take input
obj Object of class Flipgram
Flipgram
Question 2
COLUMNSUM
1. Start
→ Begin execution of the program.
2. Import Scanner class
→ Required to take user input from the console.
3. Define a class named Colsum
→ Create a user-defined class to handle matrix operations.
4. Declare data members: ‘mat’ as 2D int array, and ‘m’ and ‘n’ as
int
→ These represent the matrix and its dimensions.
5. Define a constructor with parameters ‘mm’ and ‘nn’
→ Initializes rows and columns of the matrix.
6. Inside constructor, assign mm to m, nn to n
→ Set matrix size from user input.
7. Initialize the matrix ‘mat’ as a 2D array of size m x n
→ Prepare space to store matrix elements.
8. Define method ‘readArray()’ to input matrix elements
→ Accepts user inputs for matrix data.
9. Create Scanner object ‘sc’ inside readArray
→ Used to read integers from the user.
10. Loop through each element (i, j) and assign user input to
mat[i][j]
→ Fill the matrix with user-provided values.
11. Define method ‘print()’ to display the matrix
→ Outputs the matrix in tabular form.
12. Use nested loops to print each matrix element with tab spacing
→ Formats output neatly for readability.
13. Define method ‘check(Colsum B)’ returning boolean
→ Compares column-wise sums between two matrices.
14. Loop through each column index `j` from 0 to n - 1
→ Iterate over all columns.
15. Initialize `sumA` and `sumB` to 0 for each column
→ Prepare to calculate column sums.
16. Loop through each row `i` from 0 to m - 1
→ Iterate over rows to access each column element.
17. Add mat[i][j] to `sumA`, and B.mat[i][j] to `sumB`
→ Accumulate the sum of the current column from both matrices.
18. Compare `sumA` and `sumB`; if not equal, return false
→ If any column sums mismatch, matrices don't match.
19. If all column sums are equal, return true
→ Successfully confirms that corresponding column sums are
equal.
20. In `main()` method:
a. Create Scanner object
b. Take number of rows and columns from user
c. Create objects A and B with those dimensions
d. Call `readArray()` for both matrices
e. Call `print()` for both matrices
f. Call `check()` method
g. Print appropriate message based on result
→ Executes the full flow from input, comparison to output.
21. End
→ Program execution ends.
Variab Description Data
le Type
mat 2D array to store matrix elements int[]
[]
m Number of rows in the matrix int
n Number of columns in the matrix int
i Loop control variable for rows int
j Loop control variable for columns int
sumA Stores sum of column j of matrix A int
sumB Stores sum of column j of matrix B int
sc Scanner object to take input from user Scann
er
rows Variable to hold number of rows int
entered by user
cols Variable to hold number of columns int
entered by user
A Object of class Colsum representing Colsu
the first matrix m
B Object of class Colsum representing Colsu
the second matrix m
Question 3
Sort Alpha
1. Start
→ Begin the execution of the program.
2. Import Scanner class
→ Required for taking input from the user.
3. Define a class named SortAlpha
→ This class will contain all the logic for accepting, sorting, and
displaying the sentence.
4. Declare data members: 'sent' and 'n'
→ `sent` stores the sentence and `n` stores the number of words.
5. Define a constructor to initialize 'sent' to empty string and 'n' to 0
→ Prepares the object with default values.
6. Define method 'acceptsent()' to accept sentence from user
→ Reads the input sentence from the user and converts it to
uppercase.
7. Trim the input and convert to uppercase
→ Removes unwanted spaces and standardizes the case for
sorting.
8. Count the number of words by checking spaces
→ Loop through characters to count words based on whitespace.
9. Define method 'sort(SortAlpha P)' to sort words
→ Responsible for sorting the words alphabetically.
10. Create a String array ‘words’ of size P.n
→ Stores the extracted words for sorting.
11. Append a space to the end of the sentence
→ Helps extract the last word cleanly in the loop.
12. Loop through each character in P.sent
→ Used to extract words based on whitespace.
13. Build words by concatenating non-space characters
→ Create each word from individual characters.
14. On encountering whitespace, store the word in the array
→ Adds the built word into the `words` array and resets the
temporary word.
15. Apply bubble sort on the ‘words’ array
→ Sorts the words alphabetically using `compareTo`.
16. Compare each pair of words and swap if not in order
→ Maintains ascending order by lexicographic comparison.
17. Concatenate sorted words back into ‘sent’
→ Rebuilds the sentence from sorted words.
18. Define method ‘display()’ to output the sentence
→ Prints the final sorted sentence to the user.
19. In the ‘main’ method, create two objects of SortAlpha
→ `obj1` for accepting, `obj2` for sorting and displaying.
20. Call `acceptsent()` on `obj1`, `sort(obj1)` on `obj2`, and then
`display()`
→ Execute the full flow: input → sort → output.
21. End
→ End of the program.
Variable Description Table
Variab Description Data
le Type
sent Stores the sentence (original or sorted) Strin
g
n Stores the number of words in the int
sentence
P Object of SortAlpha passed to the sort() SortA
method lpha
word Array that stores the individual words of the Strin
s sentence g[]
inde Index used to insert words into the array int
x
word Temporary variable used to build and hold Strin
individual words g
ch Character from the sentence used for char
processing
i, j Loop control variables for iterating over int
characters/words
temp Temporary variable used for swapping Strin
words during sorting g
obj1 Object of class SortAlpha used for SortA
accepting sentence lpha
obj2 Object of class SortAlpha used for sorting SortA
and displaying lpha
in Scanner object used for taking input Scann
er
Question 4:
SeriesSum
1. Start
→ Begin execution of the program.
2. Import the Scanner class
→ Required to accept user input from the keyboard.
3. Define a class named 'SeriesSum'
→ This class will encapsulate all data and methods for the
problem.
4. Declare instance variables 'x', 'n', and 'sum'
→ 'x' is the base number, 'n' is the number of terms, and 'sum'
stores the result.
5. Define a parameterized constructor with parameters 'xx' and 'nn'
→ Initialize the variables 'x' and 'n' with the values passed, set
sum to 0.0.
6. Define a recursive method 'findfact(int m)'
→ Calculates the factorial of a number using recursion.
7. Inside 'findfact', if m is 0 or 1, return 1
→ Base condition for factorial.
8. Else return m * findfact(m - 1)
→ Recursive step to calculate factorial.
9. Define a recursive method 'findpower(int base, int expo)'
→ Calculates base raised to the power of expo recursively.
10. Inside 'findpower', if expo is 0, return 1
→ Base condition for exponentiation.
11. Else return base * findpower(base, expo - 1)
→ Recursive step to calculate power.
12. Define a method 'calculate()' to evaluate the series
→ Main logic to compute the required mathematical series.
13. Initialize variable 'power' to 2
→ First term's power is 2.
14. Loop from i = 1 to i <= n
→ Loop to calculate each term of the series for n terms.
15. Calculate power of x using 'findpower(x, power)' and store in
'num'
→ Compute the numerator of the term.
16. Calculate factorial of (power - 1) using 'findfact(power - 1)' and
store in 'den'
→ Compute the denominator of the term.
17. Add (num / den) to 'sum'
→ Compute and add the current term to the cumulative sum.
18. Increment 'power' by 2
→ Move to the next power (2, 4, 6, ...).
19. Define a method 'display()' to print the sum
→ Displays the final result of the series sum.
20. In the main method:
a. Create a Scanner object
b. Accept input for 'x' and 'n' from the user
c. Create object of SeriesSum
d. Call 'calculate()'
e. Call 'display()'
→ Drives the program logic step-by-step using the created
object.
21. End
→ Marks the termination of the program.
Variable Description Table
Variab Description Data
le Type
x The base number used in the power part of int
the series
n The number of terms in the series int
sum The cumulative sum of the series doubl
e
m Parameter used in recursive factorial int
calculation
base Base value for the recursive power int
calculation
expo Exponent value for the recursive power int
calculation
powe Tracks the current power value (starts at 2 int
r and increases by 2)
num Stores the result of x raised to the current doubl
power e
den Stores the result of factorial of (power - 1) doubl
e
sc Scanner object to take input from the user Scann
er
ob Object of class SeriesSum used to call Serie
methods sSum
Question 5:
Algorithm: BinSearch
VariablStep 1: Start the program.
Step 2: Import the Scanner class from java.util package.
Step 3: Declare a class BinSearch.
Step 4: Declare instance variables:
- String s[] to store words
- int n to store the number of words
Step 5: Define a constructor BinSearch(int n) to initialize n and
create the array s.
Step 6: Define method accept() to input n words from the user
using a loop.
Step 7: Create a Scanner object for input inside the accept()
method.
Step 8: Run a loop from i = 0 to n - 1, and accept each word
into array s[i].
Step 9: Define method sort() to arrange words in ascending
order.
Step 10: Apply Bubble Sort logic: use two nested loops to compare
and swap strings using compareTo().
Step 11: Define a recursive method search(String x, int
low, int high) to perform Binary Search.
Step 12: In search(), if low > high, return -1 (not found).
Step 13: Calculate mid = (low + high) / 2.
Step 14: If s[mid].equals(x), return mid (found).
Step 15: If s[mid].compareTo(x) < 0, search in the right half:
search(x, mid + 1, high).
Step 16: Else, search in the left half: search(x, low, mid -
1).
Step 17: Define display() method to show the sorted array and
perform search.
Step 18: Use a loop to print all sorted words.
Step 19: Accept the word to be searched, call search() method,
and print the result (position or not found).
Step 20: In main(), create a BinSearch object, call accept(),
sort(), and display() methods. End the program.e Description
Table
Variab Description Data
le Type
s Array to store the list of input words Strin
g[]
n Number of words to be accepted and int
processed
temp Temporary variable used to swap Strin
elements during sorting g
x Word to be searched in the array Strin
g
low Lower bound index for binary search int
high Upper bound index for binary search int
mid Middle index used during binary search int
pos Position returned by the search method int
sc Scanner object to take user inputs Scann
er
Question 6:-
Algorithm: CardGame
1.Start
2.Declare cards[] as integer array
3.Declare integer variables cap, top
4.Create class CardGame to simulate a card pile using a stack
5.Inside the class, define a constructor CardGame(int cc)
6.In the constructor, set cap = cc, top = -1, and initialize
cards with size cap
7.Define method addCard(int v) to push card value into the
stack
8.Inside addCard(), check if top == cap - 1
9.If true, display "CARD PILE IS FULL"
10. Else, increment top and assign cards[top] = v
11. Define method drawCard() to pop the top card
12. In drawCard(), check if top == -1
13. If true, return -999 (indicating empty pile)
14. Else, store cards[top] in value, decrement top, and
return value
15. Define method display() to show all cards in the pile
16. If top == -1, display "CARD PILE IS EMPTY"
17. Else, loop from top to 0 and display each card
18. In main() method, create Scanner object sc
19. Input capacity of card pile, store in capacity
20. Create object game using CardGame class and call
methods: addCard(), drawCard(), and display() as
required
End
Variable Description Table
Varia Description Data
ble Type
card Array to store card values int[]
s (simulating a stack)
cap Capacity of the card pile (max int
number of cards)
top Index of the top card in the pile int
cc Constructor parameter for capacity int
v Value of the card to be added int
valu Value of the drawn card int
e
capa User input for card pile capacity int
city
sc Scanner object for user input Scann
er
game Object of class CardGame CardG
ame
Question 7:-
HAPPY NO
Step 1: Start
Step 2: Create a class Happy
Step 3: Declare an integer instance variable n to store the number
Step 4: Define a default constructor to initialize n = 0
Step 5: Define the method getnum(int nn)
Step 6: In getnum(), assign the input value nn to the instance
variable n
Step 7: Define a recursive method sum_sq_digits(int x)
Step 8: In sum_sq_digits(x), if x == 0, return 0
Step 9: Extract the last digit d as x % 10
Step 10: Recursively return d * d + sum_sq_digits(x / 10)
Step 11: Define a method ishappy()
Step 12: Inside ishappy(), copy the value of n to a local variable
num
Step 13: Repeat steps while num != 1 and num != 4
Step 14: In each iteration, set num = sum_sq_digits(num)
Step 15: If num == 1, print that the number is a Happy Number
Step 16: Else, print that the number is Not a Happy Number
Step 17: Define the main() method
Step 18: Create a Scanner object sc to take input
Step 19: Create an object obj of the class Happy
Step 20: Use getnum() to assign the number, then call
ishappy() to check
End
Variable Description Table
Variab Description Data
le Type
n Stores the number to be checked int
nn Parameter to assign value to n in int
getnum()
x Argument for recursive method int
sum_sq_digits()
d Stores the last digit of a number int
num Temporary variable used to evaluate if int
number is happy
sc Scanner object to take input Scann
er
obj Object of class Happy Happy
Question 8:-
DECIHEX
1.Start
2.Declare a class named DeciHex.
3.Inside the class, declare an integer variable num to store the
decimal number.
4.Declare a string variable hexa to store the hexadecimal result.
5.Define a constructor DeciHex():
○ Initialize num to 0.
○ Initialize hexa to an empty string.
6.Define method void getNum():
○ Create a Scanner object to take user input.
○ Prompt the user to enter a positive decimal number.
○ Read and store the number in num.
7.Define method void convert(int n):
○ This method will convert the decimal number n to
hexadecimal using recursion.
8.Inside convert(n), check:
○ If n == 0, then return (base condition for recursion).
9.Calculate rem = n % 16.
10. Call the function recursively with convert(n / 16).
11. After the recursive call:
● If rem < 10, convert it to character and append to hexa.
● Else, convert remainder to hexadecimal letter (A-F) using
char casting and append.
12. Define method void display():
● Call the convert(num) function.
● Print the original decimal number.
● Print the hexadecimal result.
13. Define the main() method:
● Create an object of the class DeciHex.
14. Call the method getNum() using the object.
15. Call the method display() using the object.
16. End of main method.
17. End of class.
18. Note: The hexadecimal digits are built during recursion
return phase, so the order is preserved.
19. Validation: Make sure only positive integers are input (as
per problem instruction).
20. Stop
Variable Description Table
Variab Description Data
le Type
num Stores the input decimal number int
hexa Stores the hexadecimal equivalent of the Strin
number as a string g
sc Scanner object to take input from user Scann
er
rem Stores the remainder when dividing the int
number by 16
n Parameter used in recursion to convert int
number to hexadecimal
Question 9:-
Tower Of Hanoi
Start
Define a class named TowersofHAnoi.
Declare a static method named swapping with parameters:
● int n: number of disks
● char from: source pole
● char to: destination pole
● char tempo: auxiliary pole
Inside swapping, check if n == 1 (base case of recursion)
If true, print:
● "Replace disk 1 from" + from + " to " + to
Else, recursively call:
● swapping(n - 1, from, tempo, to) (move top n−1
disks to auxiliary pole)
After that call, print:
● "Replace disk " + n + " from " + from + " to " + to
(move nth disk)
Then again call:
● swapping(n - 1, tempo, to, from) (move n−1 disks
from auxiliary pole to destination)
Define main(int n) method (non-standard main method, but
assume it's being called manually or adapted)
In main, check:
● If n <= 1, print "nothing to do" (base case when only
one or no disks are there)
Else, call:
● swapping(n, 'A', 'B', 'C') — Move disks from A to B
using C
End of main method
End of class
The recursive function handles three poles and moves disks
following the rules:
● Only one disk moved at a time
● A disk cannot be placed on top of a smaller disk
● All disks must be moved from source to destination using
auxiliary
For n disks, total number of moves = 2^n - 1
Moves are printed in the correct order due to recursion
Input can be called as TowersofHAnoi.main(3) to solve for 3
disks
Recursion uses divide and conquer approach
Each step is a precise move of a disk following constraints
Stop
Variab Description Data
le Type
n Number of disks to be moved int
from The source pole from where the char
disk is moved
to The destination pole where the disk char
is moved to
temp The auxiliary pole used during the char
o disk movement
Question 10:-
Algorithm: Pass and Return Object in Java
1.Start
2.Define a class Student.
3.Declare instance variables name (String) and marks (int)
inside the class.
4.Create a constructor Student(String name, int
marks).
5.Inside the constructor, assign values to instance variables
using this.name and this.marks.
6.Define a public class named PassAndReturnObject.
7.Inside it, create a static method improveMarks(Student
s).
8.This method accepts a Student object as a parameter.
9.Inside the method, create a new Student object named
updated.
10. Assign the same name as s and marks increased by 10.
11. Return the updated object from the method.
12. Define the main(String[] args) method.
13. Inside main, create a Student object s1 using the
constructor with name "Rahul" and marks 70.
14. Print s1's details: name and marks.
15. Call the improveMarks(s1) method and store the
returned object in Student s2.
16. This effectively creates a new student object s2 with
updated marks.
17. Print the updated student's name and marks.
18. The original student object s1 remains unchanged.
19. The method demonstrates passing and returning objects.
20. Stop
Variab Description Data
le Type
name Stores the name of the student Strin
g
mark Stores the marks of the student int
s
s1 Object of Student, stores Stude
original data nt
s2 Object of Student, stores Stude
updated data nt
s Parameter object passed to Stude
method nt
upda Temporary new object with Stude
ted improved marks nt
Question 11:-
Algorithm: Set Operations (Union and Intersection)
1.Start
2.Define a class set with two data members: an integer array
arr[] and integer n.
3.Define a constructor set(int nn) that initializes n with nn
and allocates arr of size n.
4.Define method readElements() to read n integers from the
user into the arr array using a Scanner.
5.Define method display() to print the contents of the array.
6.Define method has(int ele) to check whether a given
element exists in the array.
7.Initialize pos as -1.
8.Loop through the array. If ele matches any element, set pos
to 1 and break.
9.Return pos.
10. Define method intersection(set d) to return a new
set containing common elements of two sets.
11. Create a new set object obj with a large enough size.
12. Loop through elements of set d, and for each element
check if it is present in the current set using has().
13. If yes, add it to obj.
14. Set the correct number of elements (k) in obj and return it.
15. Define method unions(set d) to return a new set with all
unique elements from both sets.
16. Copy all elements from the current set to obj.
17. For each element in d, check if it's not in the current set
using has().
18. If not present, add it to obj.
19. In the main() method, create two set objects obj1 and
obj2.
20. Read values, display both sets, compute intersection and
union, and print the results.
Variable Description Data
Type
arr Array to store set elements int[]
n Number of elements in the set int
sc Scanner object for user input Scann
er
ele Element being searched in the int
has() function
pos Result of search: -1 if not found, 1 int
if found
d Second set object passed to set
intersection/union
obj Temporary set object for storing set
result
size3 Maximum possible size for result int
set
k Index tracker for result array int
obj1, First and second sets entered by set
obj2 user
obj3 Resultant set for intersection set
obj4 Resultant set for union set
i Loop control variable int