0% found this document useful (0 votes)
53 views168 pages

Java Programs

Computer programming with algorithm for ISC Java blueJ

Uploaded by

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

Java Programs

Computer programming with algorithm for ISC Java blueJ

Uploaded by

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

Index

Assignment Program Description Assignment


Number Date
1 Write a program where given are two strings, input string and a 16.04.25
mask string that remove all the characters of the mask string from
the original string.
Example: INPUT: ORIGINAL STRING: communication MASK STRING:
mont OUTPUT: cuicai
2 Design a class EqMat to check if two matrices are equal or not. 21.04.25
Check whether the two matrices have the same dimension or
not.Two matrices are said to be equal if they have the same
dimension and each row and column of both matrices have equal
numbers of odd and even numbers.
3 Write a program to declare a matrix A [ ] [ ] of order (M × N) where 24.04.25
‘M’ is the number of rows and ‘N’ is the number of columns such
that both M and N must be greater than 2 and less than 10. Allow
the user to input integers into this matrix. Display appropriate
error message for an invalid input.
4 Write a program to declare a matrix A[][] having order MxN( where 24.04.25
M is no. of rows and N is no. of columns) where values of both M
and N must be greater than 2 and less than 10.Allow the user to
accept value for matrix where matrix elements will be only
uppercase alphabets (check for validity).
5 Design a class Hex2Oct that will convert any hexadecimal number 05.05.25
to octal number using short cut logic. Do possible checking. Add
possible methods to perform the above function.
6 Design a class SwapSort has been defined to perform string related 07.05.25
operations on a word input, interchange/swap the first and last
characters of the word in ‘wrd’ and stores the new word in
‘swapwrd’and sorts the characters of the original word in
alphabetical order and stores it in ‘sortwrd’ without using any
sorting algorithm.
7 Write a prpgram on Encryption according to the logic given by the 09.05.25
company
8 Design a program to accept a day number (between 1 and 366), 09.05.25
year (in 4 digits) from the user to generate and display the
corresponding date. Also, accept 'N' (1 <= N <= 100) from the user
to compute and display the future date corresponding to 'N' days
after the generated date. Display an error message if the value of
the day number, year and N are not within the limit or not
according to the condition specified.
9 A sequence of Fibonacci strings is generated as follows: S0 = “a”, 12.05.25
S1 = “b”, Sn = S(n-1) + S(n-2) where ‘+’ denotes concatenation.
Thus the sequence is: a, b, ba, bab, babba, babbabab,……. n terms.
Design a class FiboString to generate Fibonacci strings.
10 A company manufactures packing cartons in four sizes, i.e. cartons 15.05.25
to accommodate 6 boxes, 12 boxes, 24 boxes and 48 boxes. Design
a program to accept the number of boxes to be packed (N) by the
user (maximum up to 1000 boxes) and display the break-up of the
1
cartons used in descending order of capacity (i.e. preference
should be given to the highest capacity available, and if boxes left
are less than 6, an extra carton of capacity 6 should be used.)
11 Write a program that will create a pattern with Fibonacci numbers 15.05.25
in pyramid shape. Numbers in the pattern i.e Fibonacci numbers
must be generated using recursive technique. Take number of lines
to print as input and display the Fibonacci pattern.
12 Write a java program to print the oden sequence from a given 18.06.25
number to a number which is less or equal to 2. Also display length
of the sequence. Oden sequence is a sequence where the numbers
go up and down again. For example: 50, 13 , 7, 4, -2
13 Design a class ArmNum to check if a given number is an Armstrong 20.06.25
number or not. [A number is said to be Armstrong if sum of its
digits raised to the power of length of the number is equal to the
number]
14 Design a program to accept the number of participants N such that 23.06.25
N must be greater than 3 and less than 11. Create a double-
dimensional array of size (Nx2) to store participants details
including participant roll and name. Create another 1D array of size
5 to store answers for 5 question. Create another 2D array of size
Nx5 which will store solution given by N participants. Calculate the
sxore for each participant by matching the correct answer stored in
a singledimensional array of size 5. Display the scores for each
participant and also the participant(s) having the highest score
15 A superclass Detail has been defined to store the details of a 27.06.25
customer. Define a subclass Bill to compute the monthly telephone
charge of the customer as per the chart is given
16 An interface Data is defined with a data member and a method 03.07.25
volume( ) which returns the volume of the implementing shape. A
super class Base has been defined to contain the radius of a
geometrical shape. Define a sub class CalVol which uses the
properties of the interface Data and the class Base and calculates
the volume of a cylinder
17 Design a class WordPile which is an entity which can hold a 08.07.25
maximum of 20 characters. The restriction is that a character can
be added or removed from one end only.
18 Design a class Queue which is an entity which can hold a maximum 11.07.25
of 100 integers. The queue enables the user to add integers from
the rear and remove integers from the front.
19 Implement the abstract methods of the interface in both the 21.07.25
classes. Finally write the main method in the class
InterfaceImplement and create a reference of interface type to
store object reference of both the classes FixedStack and
DynamicStack and call the methods accordingly. Design a menu to
show the working of both the stacks(Fixed and Dynamic) on user`s
choice.
20 A super class Record contains names and marks of the students in 25.07.25
two different single dimensional arrays. Define a sub class Lowest
to display the name(s) of the student(s) obtaining the lowest mark

2
ASSIGNMENT 1

Q1. Given are two strings, input string and a mask string that remove all the
characters of the mask string from the original string.

Example: INPUT:
ORIGINAL STRING: communication
MASK STRING: mont
OUTPUT: cuicai
A class StringMask is defined as follows to perform above operation.
Some of the members of the class are given below:
Class name : StringMask
Data members/instance variables:
str : to store the original string
msk : to store the mask string
nstr : to store the resultant string
Methods / Member functions:
StringMask() : default constructor to initialize the data member with legal
initial value.
void accept( ) : to accept the original string str and the mask string msk in
lower case.
void form() : to form the new string nstr after removal of characters present
in mask string from the original string.
void display( ) : to display the original string and the newly formed string
nstr.
Specify the class StringMask giving details of the constructor( ), void accept(
), void form() and void display( ).
Define a main( ) function to create an object and call all the functions
accordingly to enable the task.

3
ALGORITHM :-

Constructor: StringMask()
Step 1: Start
Step 2: Initialise all string variables str, msk, and nstr to empty strings ""
Step 3: End of constructor
Method: accept()
Step 1: Start
Step 2: Create a Scanner object for input
Step 3: Display "INPUT:"
Step 4: Prompt user to "ENTER ORIGINAL STRING"
Step 5: Accept the original string into variable str and convert it to lowercase
Step 6: Prompt user to "ENTER MASK STRING"
Step 7: Accept the mask string into variable msk and convert it to lowercase
Step 8: End of function
Method: form()
Step 1: Start
Step 2: Assign value of str to nstr
Step 3: Initialize i = 0
Step 4: Check if i < length of msk, if false GOTO Step 9
Step 5: Remove all occurrences of msk.charAt(i) from nstr using replaceAll()
Step 6: Increment i by 1
Step 7: GOTO Step 4
Step 8: End of function

4
Method: display()
Step 1: Start
Step 2: Display "ORIGINAL STRING: " followed by value of str
Step 3: Display "MASK STRING: " followed by value of msk
Step 4: Display "RESULTANT STRING: " followed by value of nstr
Step 5: End of function
Method: main(String args[])
Step 1: Start
Step 2: Create object ob of class StringMask
Step 3: Call accept() method using ob
Step 4: Call form() method using ob
Step 5: Call display() method using ob
Step 6: End of function

5
SOURCE CODE :-

import java.util.Scanner;
class StringMask{ private String str,msk,nstr;
private StringMask() {
str=msk=nstr=""; }
private void accept()//to accept String from user {
Scanner sc = new Scanner(System.in);
System.out.println("INPUT: ");
System.out.print("ENTER ORIGINAL STRING: ");
str=sc.nextLine().toLowerCase();
System.out.print("ENTER MASK STRING: ");
msk=sc.nextLine().toLowerCase(); }
private void form() {
nstr=str; //initially taking resulatant string as original string
for(int i=0;i<msk.length();i++){//iterate through all characters of mask
string
nstr=nstr.replaceAll(""+msk.charAt(i),"");//removing charcters of mask
string
} }
private void display(){//display resultant string
System.out.println("ORIGINAL STRING: "+str);
System.out.println("MASK STRING: "+msk);
System.out.println("RESULTANT STRING: "+nstr); }
public static void main(String args[]){//creating object and calling methods
StringMask ob = new StringMask();
ob.accept(); ob.form(); ob.display(); } }
6
OUTPUT :-

7
VARIABLE LISTING :-

StringMask

Variable Name Data Type Scope Purpose/Description


str String StringMask To store the original input string
msk String StringMask To store the mask string input
To store the resultant string after
nstr String StringMask
masking
To take user input from the
sc Scanner accept()
console
Loop counter to iterate through
i int for loop
the characters of mask string
ob StringMask main() Object to call non-static methods

8
ASSIGNMENT 2

Q2. Two matrices are said to be equal if they have the same dimension and each row and
column of both matrices have equal numbers of odd and even numbers.
For example, the two matrices A and B is given below are equal:
Matrix 1: 12 11 10 (row1: odd numbers=1, even=2) (col1: odd=1,even=2)
13 12 11 (row2: total odd numbers=2, even=1) (col2: odd=1,even=2)
14 8 6 (row3: odd numbers=0, even=3) (col3: odd=1,even=2) Page 3 of 15

Matrix 2:
5 4 8 (row1: odd numbers=1, even=2) (col1: odd=1,even=2)
2 17 11 (row2: total odd numbers=2, even=1) (col2: odd=1,even=2)
6 8 10 (row3: odd numbers=0, even=3) (col3: odd=1,even=2)
Here Matrix1 and Matrix2 can be considered as equal matrices.
Design a class EqMat to check if two matrices are equal or not. Check whether the two
matrices
have the same dimension or not.
Some of the members of the class are given below :
Class name: EqMat
Data members/instance variables:
a[][] : to store integer elements
m: to store the number of rows
n: to store the number of columns
Member functions/methods:
EqMat(…): parameterized constructor to initialise the data members.
void readArray(): to enter elements in the array
boolean check(EqMat P, EqMat Q): checks if the array in the objects P and Q are equal
and returns true, otherwise returns false as per criteria given above.
void display(): displays the array elements
Define the class EqMat giving details of the constructor ), void readarray( ), boolean
check(EqMat, EqMat) and void display( ). Define the main( ) function to create objects and
call the functions accordingly to enable the task.

9
ALGORITHM :-

Constructor: EqMat(int x, int y)


Step 1: Start
Step 2: Assign m = x and assign n = y and create a 2D array a of size m × n
Step 3: End of constructor
Method: readArray()
Step 1: Start
Step 2: Create Scanner object and display message to enter elements
Step 3: If i >= m, GOTO Step 12, If j >= n, GOTO Step 10
Step 4: Accept integer input and store in a[i][j]
Step 5: Increment j by 1, GOTO Step 7
Step 6: Inner loop ends
Step 7: Increment i by 1, GOTO Step 5
Step 8: End of function
Method: boolean check(EqMat P, EqMat Q)
Step 1: Start
Step 2: If P.m ≠ Q.m or P.n ≠ Q.n, return false
Step 3: If i >= m, GOTO Step 15 then Initialize e1 = 0, o1 = 0, e2 = 0, o2 = 0
Step 4: If j >= n, GOTO Step 11
Step 5: If P.a[i][j] is even, increment e1, else increment o1
Step 6: If Q.a[i][j] is even, increment e2, else increment o2
Step 7: Increment j by 1, GOTO Step 7
Step 8: If e1 ≠ e2 or o1 ≠ o2, return false
Step 9: Row comparison ends
Step 10: Increment i by 1, GOTO Step 4

10
Step 11: If j >= n, GOTO Step 27
Step 12: Initialize e1 = 0, o1 = 0, e2 = 0, o2 = 0
Step 13: If i >= m, GOTO Step 23
Step 14: If P.a[i][j] is even, increment e1, else increment o1
Step 15: If Q.a[i][j] is even, increment e2, else increment o2
Step 16: Increment i by 1, GOTO Step 19
Step 17: If e1 ≠ e2 or o1 ≠ o2, return false
Step 18: Increment j by 1, GOTO Step 16
Step 19: Return true
Step 20: End of function
Method: display()
Step 1: Start
Step 2: If i >= m, GOTO Step 10, If j >= n, GOTO Step 8
Step 3: Print a[i][j] with a space
Step 4: Increment j by 1, GOTO Step 5, Increment i by 1, GOTO Step 3
Step 5: End of function
Method: main(String args[])
Step 1: Start
Step 2: Create Scanner object and Prompt user to enter sizes, Accept x and y
Step 3: Create object ob1 and call ob1.readArray(), Call ob1.display()
Step 4: Create object ob2 and Call ob2.readArray(), Call ob2.display()
Step 5: Call ob1.check(ob1, ob2) and store result in result, print value of
result
Step 6: End of function

11
SOURCE CODE :-
import java.util.*;
class EqMat {
int a[][]; int m; int n;
EqMat(int x, int y) {
m = x; n = y; a = new int[m][n]; }
void readArray() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements of the array");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
} } }
boolean check(EqMat P, EqMat Q) {
if (P.m != Q.m || P.n != Q.n)
return false;
for (int i = 0; i < m; i++) {
int e1 = 0, o1 = 0, e2 = 0, o2 = 0;
for (int j = 0; j < n; j++) {
if (P.a[i][j] % 2 == 0) e1++; else o1++;
if (Q.a[i][j] % 2 == 0) e2++; else o2++;
} if (e1 != e2 || o1 != o2) return false; }
for (int j = 0; j < n; j++) { int e1 = 0, o1 = 0, e2 = 0, o2 = 0;
for (int i = 0; i < m; i++) {
if (P.a[i][j] % 2 == 0) e1++; else o1++;
if (Q.a[i][j] % 2 == 0) e2++; else o2++; }

12
if (e1 != e2 || o1 != o2) return false; }
return true; }
void display() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
System.out.print(a[i][j] + " ");
System.out.println(); } }
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter sizes of array");
int x = sc.nextInt();
int y = sc.nextInt();
EqMat ob1 = new EqMat(x, y);
ob1.readArray();
ob1.display();
EqMat ob2 = new EqMat(x, y);
ob2.readArray();
ob2.display();
boolean result = ob1.check(ob1, ob2);
System.out.println(result);
}
}

13
OUTPUT :-

14
VARIABLE LISTING :-

EqMat

Variable Name Data Type Scope Purpose/Description


m1 int[][] EqMat To store elements of the first matrix
m2 int[][] EqMat To store elements of the second matrix
r int EqMat To store number of rows in both matrices
To store number of columns in both
c int EqMat
matrices
i int for loop Loop counter for traversing rows
j int for loop Loop counter for traversing columns
sc Scanner main() To take user input from the console
ob EqMat main() Object to invoke non-static methods

15
ASSIGNMENT 3

Q3. Write a program to declare a matrix A [ ] [ ] of order (M × N) where ‘M’ is the number
of rows and ‘N’ is the number of columns such that both M and N must be greater than 2
and less than 10. Allow the user to input integers into this matrix. Display appropriate error
message for an invalid input.
Perform the following tasks on the matrix.
(a) Display the input matrix

(b) Rotate the matrix by 2700 degrees anti clock wise and display the

resultant matrix
(c) Calculate the SUM of the boundary elements of the rotated matrix and display.
Test your program for the following data and some random data:

Example 1

INPUT: M = 3

N=4
ENTER ELEMENTS: 8, 7, 9, 3,-2, 0, 4, 5, 1, 3, 6, -4

OUTPUT: ORIGINALMATRIX

8793
-2 0 4 5
1 3 6 -4
ROTATED MATRIX ( 2700 ANTI CLOCK WISE )
1 -2 8
307
649
-4 5 3
SUM OF THE BOUNDARY ELEMENTS = 31

Example 2

INPUT: M = 3

N=2
16
ENTER ELEMENTS: 9, 13, 41, 5, 6, -5

OUTPUT: ORIGINALMATRIX

9 13 41
5 6 -5
ROTATED MATRIX ( 2700ANTI CLOCK WISE )
59
6 13
-5 41
SUM OF THE BOUNDARY ELEMENTS = 69Page 5 of 15

Example 3

INPUT: M = 2

N = 10

OUTPUT: INVALID INPUT

17
ALGORITHM :-

Method: input()
Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt and input integer M
Step 4: Prompt and input integer N
Step 5: If M < 2 OR N < 2 OR M > 10 OR N > 10, display "Invalid input" and
terminate the program
Step 6: Declare 2D array arr[M][N]
Step 7: Display message "Enter the elements->"
Step 8: Initialize loop counter i = 0
Step 9: If i >= M × N, GOTO Step 13
Step 10: Store next integer in arr[i / N][i % N]
Step 11: Increment i by 1
Step 12: GOTO Step 9
Step 13: Display message "ORIGINAL MATRIX->"
Step 14: Call show(arr)
Step 15: Call rot270(arr)
Step 16: End of function
Method: rot270(int a[][])
Step 1: Start
Step 2: Set rows = number of rows in a
Step 3: Set cols = number of columns in a
Step 4: Declare rotatedMatrix[cols][rows]
Step 5: Initialize i = 0
Step 6: If i >= rows, GOTO Step 14
18
Step 7: Initialize j = 0
Step 8: If j >= cols, GOTO Step 12
Step 9: Set rotatedMatrix[j][rows - 1 - i] = a[i][j]
Step 10: Increment j by 1
Step 11: GOTO Step 8
Step 12: Inner loop ends
Step 13: Increment i by 1, GOTO Step 6
Step 14: Display "ROTATED MATRIX (270 ANTICLOCLWISE)"
Step 15: Call show(rotatedMatrix)
Step 16: Call sumBoundary(rotatedMatrix)
Step 17: End of function
Method: sumBoundary(int a[][])
Step 1: Start
Step 2: Initialize sum = 0
Step 3: Initialize i = 0
Step 4: If i >= number of rows in a, GOTO Step 14
Step 5: Initialize j = 0
Step 6: If j >= number of columns in a, GOTO Step 11
Step 7: If i == 0 OR j == 0 OR i == last row index OR j == last column index,
then sum += a[i][j]
Step 8: Increment j by 1
Step 9: GOTO Step 6
Step 10: Inner loop ends
Step 11: Increment i by 1
Step 12: GOTO Step 4
Step 13: Outer loop ends

19
Step 14: Display "SUM OF THE BOUNDARY ELEMENTS = " followed by value
of sum
Step 15: End of function
Method: show(int y[][])
Step 1: Start
Step 2: Initialize i = 0
Step 3: If i >= number of rows in y, GOTO Step 10
Step 4: Initialize j = 0
Step 5: If j >= number of columns in y, GOTO Step 8
Step 6: Print y[i][j] followed by a space
Step 7: Increment j by 1, GOTO Step 5
Step 8: Print newline
Step 9: Increment i by 1, GOTO Step 3
Step 10: Print extra newline
Step 11: End of function
Method: main(String args[])
Step 1: Start
Step 2: Create object obj of class Rotation3
Step 3: Call obj.input()
Step 4: End of function

20
SOURCE CODE :-

import java.util.Scanner;
public class Rotation3{
void input(){
Scanner scan=new Scanner(System.in);
System.out.print("M= "); int M=scan.nextInt();
System.out.print("N= "); int N=scan.nextInt();
if(M<2||N<2||M>10||N>10){
System.out.println("Invalid input");
System.exit(0); }
int arr[][]=new int[M][N];
System.out.println("Enter the elements-> ");
for(int i=0;i<M*N;i++){
arr[i/N][i%N]=scan.nextInt(); }
System.out.println("ORIGINAL MATRIX->");
show(arr); rot270(arr); }
int counter=0;
void rot270(int a[][] ) {
int rows = a.length;
int cols = a[0].length;
int rotatedMatrix[][] = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotatedMatrix[j][rows - 1 - i] = a[i][j]; } }
System.out.println("ROTATED MATRIX (270 ANTICLOCLWISE)");
show(rotatedMatrix);
21
sumBoundary(rotatedMatrix);
}
void sumBoundary(int a[][]){
int sum=0;
for(int i=0;i<a.length;i++){
for(int j=0;j<a[0].length;j++){
if(i==0||j==0||i==(a.length-1)||j==a[0].length-1){
sum+=a[i][j]; } } }
System.out.println("SUM OF THE BOUNDARY ELEMENTS ="+ sum); }
void show(int y[][]){
for(int i=0;i<y.length;i++){
for(int j=0;j<y[0].length;j++){
System.out.print(y[i][j]+" "); }
System.out.println(); }
System.out.println(); }
public static void main(String args[]){
Rotation3 obj=new Rotation3();
obj.input(); } }

22
OUTPUT:-

23
VARIABLE LISTING:

Rotation3
Variable Data
Scope Purpose/Description
Name Type

counter int Rotation3 Not used in program logic (can be removed)

scan Scanner input() To read input from the user

M int input() Number of rows in the matrix

N int input() Number of columns in the matrix

arr int[][] input() To store original matrix values

Loop variable for inputting elements /


i int for loop
traversal

Loop variable for column traversal / copying


j int for loop
matrix

rows int rot270() Number of rows in original matrix

cols int rot270() Number of columns in original matrix

Parameter to receive matrix input in rotation


a int[][] rot270()
method

rotatedMatrix int[][] rot270() To store 270° rotated matrix

sum int sumBoundary() To calculate sum of boundary elements

a int[][] sumBoundary() Parameter to receive rotated matrix

y int[][] show() Matrix to be printed

obj Rotation3 main() Object to call non-static methods

24
ASSIGNMENT 4

Q4. Write a program to declare a matrix A[][] having order MxN( where M is no. of rows
and N
is no. of columns) where values of both M and N must be greater than 2 and less than
10.Allow

the user to accept value for matrix where matrix elements will be only uppercase
alphabets

(check for validity). Perform the following tasks:

a) Display original matrix

b) Sort the elements of the matrix in ascending order using selection sort
algorithm.(Don`t use 1D array to perform the task.)

c) Display the final updated matrix.

25
ALGORITHM :-

Method: displayMatrix(char matrix[][])


Step 1: Start
Step 2: Initialize i = 0
Step 3: If i >= number of rows, GOTO Step 9
Step 4: Initialize j = 0
Step 5: If j >= number of columns, GOTO Step 7
Step 6: Print matrix[i][j] followed by a space, increment j by 1, GOTO Step 5
Step 7: Print newline
Step 8: Increment i by 1, GOTO Step 3
Step 9: End of function
Method: selectionSort2D(char a[][], int m, int n)
Step 1: Start
Step 2: Initialize i = 0
Step 3: If i >= (m × n - 1), GOTO Step 16
Step 4: Set minRow = i / n, minCol = i % n
Step 5: Initialize j = i + 1
Step 6: If j >= m × n, GOTO Step 11
Step 7: If a[j / n][j % n] < a[minRow][minCol], set minRow = j / n, minCol = j %
n
Step 8: Increment j by 1
Step 9: GOTO Step 6
Step 10: Swap a[i / n][i % n] with a[minRow][minCol] using temporary
variable
Step 11: Increment i by 1
Step 12: GOTO Step 3

26
Step 13: End of function
Method: main(String args[])
Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt and input value of M and N
Step 4: If M <= 2 OR M >= 10 OR N <= 2 OR N >= 10, display invalid message
and terminate
Step 5: Declare 2D array A[M][N]
Step 6: Display message to input uppercase letters
Step 7: Initialize i = 0, If i >= M, GOTO Step 23
Step 8: Initialize j = 0, If j >= N, GOTO Step 21
Step 9: Prompt to enter element [i][j]
Step 10: Read input string and trim it
Step 11: If length of input ≠ 1 OR input not uppercase, display invalid
message, GOTO Step 12
Step 12: Assign A[i][j] = input.charAt(0)
Step 13: Break loop
Step 14: Increment j by 1
Step 15: GOTO Step 11
Step 16: Increment i by 1, GOTO Step 9
Step 17: Create object obj of class MatrixCharSort
Step 18: Display "Original Matrix:"
Step 19: Call obj.displayMatrix(A)
Step 20: Call obj.selectionSort2D(A, M, N)
Step 21: Display "Sorted Matrix (Ascending Order):"
Step 22: Call obj.displayMatrix(A)
Step 23: End of function
27
SOURCE CODE :-

import java.util.Scanner;
public class MatrixCharSort{
void displayMatrix(char matrix[][]) {
for (int i=0;i<matrix.length;i++) {
for (int j=0;j<matrix[0].length;j++)
System.out.print(matrix[i][j]+" ");
System.out.println(); } }
void selectionSort2D(char a[][],int m,int n) {
for (int i=0;i<m*n-1;i++) {
int minRow=i/n; int minCol=i%n;
for (int j=i+1;j<m*n;j++) {
if (a[j/n][j%n]<a[minRow][minCol]) {
minRow=j/n; minCol=j%n; } }
char temp=a[i/n][i%n]; a[i/n][i%n]=a[minRow][minCol];
a[minRow][minCol]=temp; } }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows (M): ");
int M = sc.nextInt(); System.out.print("Enter number of columns (N): ");
int N = sc.nextInt();
if (M<=2 || M>=10 || N<=2 || N>=10){
System.out.println("Invalid matrix dimensions. M and N must be > 2 and <
10.");
return; }
char[][] A = new char[M][N];
28
System.out.println("Enter uppercase letters (A-Z) for the matrix:");
for (int i=0;i<M;i++) {
for (int j=0;j<N;j++){ String input;
while (true){
System.out.print("Element [" + i + "][" + j + "]: ");
input=new Scanner(System.in).nextLine().trim();
if (input.length()==1 && Character.isUpperCase(input.charAt(0))){
A[i][j] = input.charAt(0); break; }
else
System.out.println("Invalid input! Enter a single uppercase letter (A-
Z).");
}
}
}
MatrixCharSort obj=new MatrixCharSort();
System.out.println("\nOriginal Matrix:");
obj.displayMatrix(A); obj.selectionSort2D(A,M,N);
System.out.println("\nSorted Matrix (Ascending Order):");
obj.displayMatrix(A);
}
}

29
OUTPUT :-

30
VARIABLE LISTING :-

MatrixCharSort Program
Variable
Data Type Scope Purpose / Description
Name
displayMatrix() Stores the 2D character matrix to
matrix char[][]
method (parameter) be displayed
selectionSort2D() The 2D character array to be sorted
a char[][]
method (parameter) using selection sort logic
selectionSort2D()
m int Number of rows in the matrix
method (parameter)
selectionSort2D()
n int Number of columns in the matrix
method (parameter)
Used in loops to traverse elements
i int Loop variable
in 2D matrix
j int Loop variable Used in nested loops during sorting
selectionSort2D() Holds row index of the minimum
minRow int
method element during sorting
selectionSort2D() Holds column index of the
minCol int
method minimum element during sorting
selectionSort2D() Temporary variable to swap
temp char
method characters
Scanner object to take input from
sc Scanner main method
the user
Stores number of rows input by the
M int main method
user
Stores number of columns input by
N int main method
the user
Temporarily holds user input
input String main method before validation as a single
uppercase character
Stores the final user-entered 2D
A char[][] main method
character matrix
Object to call non-static methods
obj MatrixCharSort main method
displayMatrix and selectionSort2D

31
ASSIGNMENT 5

Q5. Design a class Hex2Oct that will convert any hexadecimal


number to octal number using

short cut logic. Do possible checking. Add possible methods to


perform the above function.

32
ALGORITHM :-

Method: accept()
Step 1: Start
Step 2: Create Scanner object
Step 3: Read hexadecimal string and convert to uppercase
Step 4: Initialize i = 0
Step 5: If i >= length of hex, GOTO Step 9
Step 6: Get character c = hex.charAt(i)
Step 7: If c is not a valid hex digit or is a second decimal point, print "INVALID
HEXADECIMAL" and exit
Step 8: Increment i and GOTO Step 5
Step 9: End of function
Method: convert()
Step 1: Start
Step 2: Set bin = "", i = 0
Step 3: If i >= length of hex, GOTO Step 9
Step 4: If hex.charAt(i) == '.', append "." to bin, GOTO Step 8
Step 5: If i == 0, append binary (without leading 0s) of hex.charAt(0) to bin
Step 6: Else, append 4-digit binary of hex.charAt(i) to bin
Step 7: Increment i
Step 8: GOTO Step 3
Step 9: Set oct = ""
Step 10: Set i = index of '.' if present, else i = bin.length()
Step 11: While i > 0, extract 3 bits from right, convert to octal and prepend to
oct, reduce i by 3
Step 12: If bin contains '.', append '.' to oct
33
Step 13: From index after '.', extract 3-bit groups and append converted octal
digits to oct
Step 14: If result has .0 at the end, convert to int
Step 15: Else convert to double to clean up
Step 16: Display final octal equivalent
Step 17: End of function
Method: getBin(char c)
Step 1: Start
Step 2: Convert c to decimal integer x
Step 3: Set empty string b
Step 4: While b.length() != 4, prepend x % 2 to b and divide x by 2
Step 5: Return b
Step 6: End of function
Method: getOct(String bin)
Step 1: Start
Step 2: Convert binary string to integer
Step 3: Set sum = 0, i = 0
Step 4: While binary > 0,add (last digit × 2^i) to sum, remove last digit,
increment i
Step 5: Return sum as string
Step 6: End of function
Method: main(String args[])
Step 1: Start
Step 2: Create object, Call accept(), Call convert()
Step 3: End of function

34
SOURCE CODE :-

import java.util.Scanner;
class Hex2Oct
{
private String hex,oct;
private void accept()//accept hexadecimal no. from user
{
Scanner sc = new Scanner(System.in);
System.out.print("ENTER HEXADECIMAL NUMBER: ");
hex=sc.next().toUpperCase();
for(int i=0;i<hex.length();i++)
{
char c=hex.charAt(i);//taking each digit

if(!(('0'<=c&&c<='9')||('A'<=c&&c<='F')||(c=='.'&&hex.indexOf(c)==i)))//hexa
decimal digits check and decimal point once
{
System.out.print("INVALID HEXADECIMAL");
System.exit(0);
}
}
}
private void convert()//to convert hexadecimal to octal
{
String bin="";
for(int i=0;i<hex.length();i++)

35
{
if(hex.charAt(i)=='.')
bin+=".";
else if(i==0)
bin+=Integer.parseInt(getBin(hex.charAt(0)));//removing leading 0s of
binary of first hex digit
else
bin+=getBin(hex.charAt(i));
}
oct="";
for(int i=(bin.indexOf('.')==-1)?bin.length():bin.indexOf('.');i>0;i-
=3)//whole part
{
if(i-3>=0)
oct=getOct(bin.substring(i-3,i))+oct;
else//when <3 digits are left
oct=getOct(bin.substring(0,i))+oct;
}
if(bin.indexOf('.')!=-1)//fractional part
{
oct+=".";
for(int i=bin.indexOf('.')+1;i<bin.length();i+=3)
{
if(i+3<=bin.length())
oct+=getOct(bin.substring(i,i+3));
else//when less than 3 digits are left
oct+=getOct(bin.substring(i));
36
}
}
if((int)Double.parseDouble(oct)==Double.parseDouble(oct))
oct=""+(int)Double.parseDouble(oct);//if no fractional part (.0) then
remove point
else
oct=""+Double.parseDouble(oct);//removing leading and ending zeroes
if any
System.out.println("OCTAL EQUIVALENT: "+oct);
}
private String getBin(char c)//converting octal digit to binary
{
int x=(c>=65)?c-55:Integer.parseInt(""+c);//taking hexadecimal digit as
decimal digit
String b="";//to store equivalent 4 digit binary
while(b.length()!=4)
{
b=(x%2)+b;
x/=2;
}
return b;
}
private String getOct(String bin)//convert binary to octal digit
{
int b=Integer.parseInt(bin);
int sum=0;
for(int i=0;b>0;i++)
37
{
sum+=b%10*(int)Math.pow(2,i);
b/=10;
}
return String.valueOf(sum);
}
public static void main(String args[])
{
Hex2Oct ob = new Hex2Oct();
ob.accept();
ob.convert();
}
}

38
OUTPUT :-

39
VARIABLE LISTING :-

Hex2Oct Program
Variable
Data Type Scope Purpose / Description
Name
To store the hexadecimal number input
hex String Class-level
by the user
oct String Class-level To store the converted octal number
sc Scanner accept() Scanner object to take input from user
accept(),
i int convert(), Loop counter used in various loops
getOct()
accept(),
Character variable used for digit
c char convert(),
validation and conversion
getBin()
Intermediate binary string converted from
bin String convert()
hexadecimal
x int getBin() Integer value of hexadecimal digit
Binary string (converted to int) passed for
b int getOct()
octal conversion
Stores decimal value converted from
sum int getOct()
binary
Temporary variable used during
t String convert()
conversion

40
ASSIGNMENT 6

Q6. A class SwapSort has been defined to perform string related operations on a word
input.
Some of the members of the class are as follows:
Class name : SwapSort
Data members/instance variables:
wrd : to store a word
len : integer to store length of the word
swapwrd : to store the swapped word
sortwrd : to store the sorted word
Member functions/methods:
SwapSort( ) : default constructor to initialize data members with legal default initial values
void readword( ) : to accept a word in UPPER CASE
void swapchar( ) : to interchange/swap the first and last characters of the word in ‘wrd’ and
stores the new word in ‘swapwrd’
void sortword( ) : sorts the characters of the original word in alphabetical order and stores
it in

‘sortwrd’ without using any sorting algorithm.

void display( ) : displays the original word, swapped word and the sorted word
Specify the class SwapSort, giving the details of the constructor( ), void readword( ), void
swapchar( ), void sortword( ) and void display( ). Define the main( ) function to create an
object
and call the functions accordingly to enable the task.

41
ALGORITHM :-

Constructor: SwapSort()
Step 1: Start
Step 2: Initialize wrd, swapwrd, sortwrd as empty strings
Step 3: Set len = 0
Step 4: End of constructor
Method: readword()
Step 1: Start
Step 2: Create Scanner object
Step 3: Read input word into wrd
Step 4: Initialize i = 0
Step 5: If i >= length of wrd, GOTO Step 9
Step 6: If wrd.charAt(i) is not uppercase, print "INVALID WORD" and exit
Step 7: Increment i by 1
Step 8: GOTO Step 5
Step 9: End of function
Method: swapchar()
Step 1: Start
Step 2: Set swapwrd = last character + middle substring + first character
Step 3: End of function
Method: sortword()
Step 1: Start
Step 2: Set c = 'A'
Step 3: If c > 'Z', GOTO Step 11
Step 4: Set i = 0
Step 5: If i >= length of wrd, GOTO Step 9
42
Step 6: If wrd.charAt(i) == c, append c to sortwrd
Step 7: Increment i by 1
Step 8: GOTO Step 5
Step 9: Increment c to next letter
Step 10: GOTO Step 3
Step 11: End of function
Method: display()
Step 1: Start
Step 2: Print "ORIGINAL WORD: " + wrd
Step 3: Print "SWAPPED WORD: " + swapwrd
Step 4: Print "SORTED WORD: " + sortwrd
Step 5: End of function
Method: main(String args[])
Step 1: Start
Step 2: Create object ob of class SwapSort
Step 3: Call ob.readword()
Step 4: Call ob.swapchar()
Step 5: Call ob.sortword()
Step 6: Call ob.display()
Step 7: End of function

43
SOURCE CODE :-

import java.util.Scanner;
class SwapSort
{
private String wrd,swapwrd,sortwrd;
private int len;
SwapSort()
{
wrd=swapwrd=sortwrd="";
len=0;
}
private void readword()//to accept word
{
Scanner sc = new Scanner(System.in);
System.out.print("ENTER WORD IN UPPERCASE: ");
wrd=sc.next();//converting word to upper case
for(int i=0;i<wrd.length();i++)//traversing through each character of
word
{
if(!Character.isUpperCase(wrd.charAt(i)))//check each character of
word is uppercase alphabet
{
System.out.print("INVALID WORD");
System.exit(0);
}
}
44
}
private void swapchar()//swap 1st and last
{
//adding last character then 2nd to 2nd last charcter then first character
swapwrd=wrd.charAt(wrd.length()-1)+wrd.substring(1,wrd.length()-
1)+wrd.charAt(0);
}
private void sortword()//sort characters in alphabetical order
{
for(char c='A';c<='Z';c++)//taking every letter in alphabetic order
{
for(int i=0;i<wrd.length();i++)//to traverse through each character of
word
{
if(c==wrd.charAt(i))//if letter present in word then add it to sorted
word
sortwrd+=c;
}
}
}
private void display()//to display all words
{
System.out.println("ORIGINAL WORD: "+wrd);
System.out.println("SWAPPED WORD: "+swapwrd);
System.out.println("SORTED WORD: "+sortwrd);
}
public static void main(String args[])
45
{
SwapSort ob = new SwapSort();
ob.readword();
ob.swapchar();
ob.sortword();
ob.display();
}
}

46
OUTPUT :-

47
VARIABLE LISTING :-

SwapSort Program

Variable
Data Type Scope Purpose / Description
Name
wrd String Class-level Original input word
Word after swapping
swapwrd String Class-level
first and last characters
Word after sorting
sortwrd String Class-level characters in
alphabetical order
Stores length of the
len int Class-level
word (not used directly)
sc Scanner readword() Scanner object for input
readword(), Loop index used for
i int
sortword() iteration
Alphabet character used
c char sortword()
to iterate from A to Z

48
ASSIGNMENT 7

Q7. You are being assigned a project by an Encryption company to encrypt a sentence in
such a way that it will be impossible to decode during data transmission wirelessly. The
company had given a logic which you will implement using programming language. The
logic states that for any sentence having multiple words separated by either one blank
space or more than one blank space can be terminated by any valid punctuation mark (.
or ? or !).
You have to extract each word to encrypt and then create a new sentence to be transmitted.
For a single letter word, replace it with a number which is the sum of 32 and Unicode
value of that character.
For two letter word replace the first character with its previous character and last character
to its next character maintaining alphabetical series in clockwise manner.
For other words calculate the word length and replace all characters from first to mid
character (wordlength/2) with their previous characters and remaining characters to be
replaced by next vowel in alphabetical series clockwise.
The sentence must be given in UPPERCASE only must terminate with valid punctuation
mark. Design a program with possible methods to implement above logic.
Example: Input: I AM GOING TO SCHOOL.
Output: 105 ZN FNOOI SP RBGUUO.

49
ALGORITHM :-

Method: input()
Step 1: Start
Step 2: Create Scanner object
Step 3: Read sentence into sent and trim extra spaces
Step 4: Initialize i = 0
Step 5: If i >= sent.length() - 1, GOTO Step 10
Step 6: Set c = sent.charAt(i)
Step 7: If c is not uppercase and not space, print "INVALID SENTENCE" and
exit
Step 8: Increment i by 1
Step 9: GOTO Step 5
Step 10: Set c = sent.charAt(sent.length() - 1)
Step 11: If c is not '.', '?' or '!', print "INVALID PUNCTUATION MARK" and exit
Step 12: End of function

Method: encrypt()
Step 1: Start
Step 2: Create StringTokenizer to break sentence into words
Step 3: Set esent = ""
Step 4: While more tokens exist, GOTO Step 5; else GOTO Step 20
Step 5: Get next token into s
Step 6: If s.length() == 1, set s = "" + (32 + ASCII of s.charAt(0)), GOTO Step 19
Step 7: If s.length() == 2, set s = previous of first letter + next of second letter
(cyclic)
Step 8: Else

50
Step 9: Set t = ""
Step 10: Initialize i = 0
Step 11: If i >= s.length() / 2, GOTO Step 14
Step 12: Append to t the previous letter of s.charAt(i) (cyclic A→Z)
Step 13: Increment i by 1, GOTO Step 11
Step 14: Initialize i = s.length() / 2
Step 15: If i >= s.length(), GOTO Step 18
Step 16: Let c = s.charAt(i), append next vowel after c to t
Step 17: Increment i by 1, GOTO Step 15
Step 18: Set s = t
Step 19: Append s + " " to esent
Step 20: Append punctuation mark (last char of sent) to esent
Step 21: Print "ORIGINAL SENTENCE: " + sent
Step 22: Print "ENCRYPTED SENTENCE: " + esent
Step 23: End of function

Method: main(String args[])


Step 1: Start
Step 2: Create object ob of class Encryption
Step 3: Call ob.input()
Step 4: Call ob.encrypt()
Step 5: End of function

51
SOURCE CODE :-

import java.util.Scanner;
import java.util.StringTokenizer;
class Encryption
{
private String sent;
private void input()//to accept sentence
{
Scanner sc = new Scanner(System.in);
System.out.print("ENTER SENTENCE IN UPPERCASE TERMINATED WITH
PUNCTUATION MARK: ");
sent=sc.nextLine().trim().replaceAll("[ ]+"," ");//removing unnecessary
spaces
for(int i=0;i<sent.length()-1;i++)//traversing through each character of
sentence
{
char c=sent.charAt(i);
if(!(Character.isUpperCase(c)||c==' '))//check each character is
uppercase alphabet or space
{
System.out.print("INVALID SENTECE");
System.exit(0);
}
}
char c=sent.charAt(sent.length()-1);//taking puncutation mark
if(!(c=='.'||c=='?'||c=='!'))//checking valididty of puncutation mark
{
52
System.out.print("INVALID PUNCTUATION MARK");
System.exit(0);
}
}
private void encrypt()
{
StringTokenizer st = new StringTokenizer(sent," ?.!");
String esent="";//to store encrypted sentence
while(st.hasMoreTokens())
{
String s=st.nextToken();//taking each word
if(s.length()==1)
s=""+(32+s.charAt(0));//updaqting sum of 32 and unicode value
else if(s.length()==2)
s=""+((s.charAt(0)=='A')?'Z':(char)(s.charAt(0)-
1))+((s.charAt(1)=='Z')?'A':(char)(s.charAt(1)+1));
else
{
String t="";
for(int i=0;i<s.length()/2;i++)//traversing each character till middle
t+=(s.charAt(i)=='A')?'Z':(char)(s.charAt(i)-1);//adding previous letter
(cyclic)
for(int i=s.length()/2;i<s.length();i++)//traversing each character
after middle
{
char c = s.charAt(i);//taking letter

53
t+=(c<'E')?'E':(c<'I')?'I':(c<'O')?'O':(c<'U')?'U':'A';//adding next
vowel
}
s=t;
}
esent+=s+" ";
}
esent+=sent.charAt(sent.length()-1);//adding punctuation mark
System.out.println("ORIGINAL SENTECE: "+sent);
System.out.println("ENCRYPTED SENTENCE: "+esent);
}
public static void main(String args[])
{
Encryption ob=new Encryption();
ob.input();
ob.encrypt();
}
}

54
OUTPUT :-

55
VARIABLE LISTING :-

Encryption Program

Variable
Data Type Scope Purpose / Description
Name
sent String Class-level Stores the input sentence
Scanner object for reading
sc Scanner input()
sentence input
Loop counter to validate
i int input()
each character of sentence
Used for checking validity
c char input(), encrypt() of characters and
punctuation
Used to break the sentence
st StringTokenizer encrypt()
into words
Stores the encrypted
esent String encrypt()
sentence
Stores each word extracted
s String encrypt()
from tokenizer
Temporary string for
t String encrypt()
storing transformed word
Loop counter used in word
i int encrypt()
transformation logic
Used for vowel substitution
c char encrypt()
in second half of word

56
ASSIGNMENT 8

Q8. Design a program to accept a day number (between 1 and 366), year (in 4 digits) from
the user to generate and display the corresponding date. Also, accept 'N' (1 <= N <= 100)
from the user to compute and display the future date corresponding to 'N' days after the
generated date.
Display an error message if the value of the day number, year and N are not within the
limit or not according to the condition specified.
Test your program with the following data and some random data:

Example 1

INPUT:

DAY NUMBER: 255


YEAR: 2018
DATE AFTER (N DAYS): 22

OUTPUT:

DATE: 12TH SEPTEMBER, 2018


DATE AFTER 22 DAYS: 4TH OCTOBER, 2018

Example 2

INPUT:

DAY NUMBER: 360


YEAR: 2018
DATE AFTER (N DAYS): 45

OUTPUT:

DATE: 26TH DECEMBER, 2018


DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019

57
Example 3

INPUT:

DAY NUMBER: 500


YEAR: 2018
DATE AFTER (N DAYS): 33

OUTPUT:

DAY NUMBER OUT OF RANGE

Example 4

INPUT:

DAY NUMBER: 150


YEAR: 2018
DATE AFTER (N DAYS): 330

OUTPUT:

DATE AFTER (N DAYS) OUT OF RANGE

58
ALGORITHM :-

Method: get()
Step 1: Start
Step 2: Create Scanner object
Step 3: Input dayNumber
Step 4: Input year
Step 5: If dayNumber < 1 OR dayNumber > 366, print error and exit
Step 6: If year is not a leap year AND dayNumber > 365, print error and exit
Step 7: Set startDate = January 1 of year
Step 8: Set enteredDate = startDate + (dayNumber - 1) days
Step 9: Input n
Step 10: If n < 1 OR n > 100, print error and exit
Step 11: Set futureDate = enteredDate + n days
Step 12: Call getDayWithSuffix() using enteredDate.getDayOfMonth() and
store in enteredDay
Step 13: Call getDayWithSuffix() using futureDate.getDayOfMonth() and
store in futureDay
Step 14: Format both dates in "MMMM, YYYY" format
Step 15: Display "Entered Date: " + enteredDay + formatted month-year
Step 16: Display n + " days later: " + futureDay + formatted month-year
Step 17: End of function

Method: getDayWithSuffix(day)
Step 1: Start
Step 2: If day is 11 to 13, return day + "th"
Step 3: If day % 10 == 1, return day + "st"

59
Step 4: If day % 10 == 2, return day + "nd"
Step 5: If day % 10 == 3, return day + "rd"
Step 6: Else, return day + "th"
Step 7: End of function

Method: isLeapYear(y)
Step 1: Start
Step 2: If (y % 4 == 0 AND y % 100 != 0) OR y % 400 == 0, return true
Step 3: Else return false
Step 4: End of function

Method: main(String args[])


Step 1: Start
Step 2: Create temporary object and call get()
Step 3: End of function

60
SOURCE CODE :-

// To display entered date and future date


import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
class Date
{
void get()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter day number (1-366) : ");
int dayNumber = sc.nextInt();
System.out.print("Enter year (yyyy) : ");
int year = sc.nextInt();

if (dayNumber < 1 || dayNumber > 366 || (!isLeapYear(year) &&


dayNumber > 365))
{
System.out.println("Error : Invalid day number for the given year");
return;
}
LocalDate startDate = LocalDate.of(year,1,1); // Setting object at 1st
january yyyy
LocalDate enteredDate = startDate.plusDays(dayNumber-1); // Desired
date
System.out.print("Enter N (1-100): ");

61
int n = sc.nextInt();
if (n < 1 || n > 100)
{
System.out.println("Error : N must be between 1 and 100.");
return;
}
LocalDate futureDate = enteredDate.plusDays(n); // Future date finding
String enteredDay = getDayWithSuffix(enteredDate.getDayOfMonth());
String futureDay = getDayWithSuffix(futureDate.getDayOfMonth());
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMMM, YYYY");
System.out.println("Entered Date: "+enteredDay+"
"+enteredDate.format(formatter));
System.out.println(n+" days later: "+futureDay+"
"+futureDate.format(formatter));
}
String getDayWithSuffix(int day)
{
if (day >= 11 && day <= 13)
return day + "th";
switch (day % 10)
{
case 1: return day + "st";
case 2: return day + "nd";
case 3: return day + "rd";
default: return day + "th";
}
62
}
boolean isLeapYear(int y)
{
return (y%4==0 && y%100!=0)||(y%400==0); // Condition of leap year
}
public static void main(String args[])
{
new Date().get(); // Calling method using temporary instance
}
}

63
OUTPUT :-

64
65
66
VARIABLE LISTING :-

Date

Variable
Data Type Scope Purpose/Description
Name

sc Scanner get() Scanner object to take user input

Day number (1–366) entered by the


dayNumber int get()
user

Year in yyyy format entered by the


year int get()
user

Represents January 1st of the given


startDate LocalDate get()
year

Actual date derived from the day


enteredDate LocalDate get()
number and year

Number of days to be added to the


n int get()
entered date

Future date calculated by adding n


futureDate LocalDate get()
days to enteredDate

Day of the month with suffix (like 1st,


enteredDay String get()
2nd...) of enteredDate

Day of the month with suffix for


futureDay String get()
futureDate

DateTimeForma Formatter to format dates in


formatter get()
tter "MMMM, YYYY" style

getDayWithSuffix The day of the month passed to


day int
() determine its ordinal suffix

67
ASSIGNMENT 9

Q9. A sequence of Fibonacci strings is generated as follows:


S0 = “a”, S1 = “b”, Sn = S(n-1) + S(n-2) where ‘+’ denotes concatenation.
Thus the sequence is:
a, b, ba, bab, babba, babbabab,……. n terms.
Design a class FiboString to generate Fibonacci strings. Some of the members of the
class are given below:
Class name: FiboString
Data members/instance variables:
x: to store the first string
y: to store the second string
z: to store the concatenation of the previous two strings
n: to store the number of terms
Member functions/methods:
FiboString(): constructor to assign x=”a”, y=”b” and z=”ba”
void accept(): to accept the number of terms ‘n’
void generate(): to generate and print the Fibonacci strings.
The sum of (‘+’ i.e. concatenation) first two strings is the third string.
Eg. “a” is first string, “b” is second string then the third will be “ba”, and fourth will be
“bab” and so on.
Specify the class FiboString, giving details of the constructor(), void accept() and void
generate().
Define the main() function to create an object and call the functions
accordingly to enable the task

68
ALGORITHM :-

Constructor: FiboString()
Step 1: Start
Step 2: Set x = "a"
Step 3: Set y = "b"
Step 4: Set z = "ba"
Step 5: Set n = 0
Step 6: End of constructor

Method: accept()
Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt user to input number of terms
Step 4: Read input into n
Step 5: If n <= 2, GOTO Step 4
Step 6: End of function

Method: generate()
Step 1: Start
Step 2: Print x
Step 3: Print y
Step 4: Print z
Step 5: Set i = 3
Step 6: If i > n, GOTO Step 11
Step 7: Set x = y
Step 8: Set y = z
69
Step 9: Set z = y + x
Step 10: Print z, increment i, GOTO Step 6
Step 11: End of function

Method: main(String args[])


Step 1: Start
Step 2: Create object obj of class FiboString
Step 3: Call obj.accept()
Step 4: Call obj.generate()
Step 5: End of function

70
SOURCE CODE :-

import java.util.Scanner;
public class FiboString{
String x;
String y;
String z;
int n;
public FiboString(){
x="a";
y="b";
z="ba";
n=0;
}
void accept(){
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number of terms you want-> ");
do{n=scan.nextInt();}while(n<=2);
}
void generate(){
System.out.print(x+" ");
System.out.print(y+" ");
System.out.print(z+" ");
for(int i=3;i<=n;i++){
x=y;
y=z;

71
z=y+x;
System.out.print(z+" ");
}
}
public static void main(String args[]){
FiboString obj=new FiboString();
obj.accept();
obj.generate();
}

72
OUTPUT :-

73
VARIABLE LISTING :-

FiboString

Variable
Data Type Scope Purpose/Description
Name

First term of the Fibonacci string


x String FiboString
sequence

Second term of the Fibonacci string


y String FiboString
sequence

Term to store next Fibonacci string


z String FiboString
(concatenation of y and x)

Number of terms to be generated in the


n int FiboString
Fibonacci string sequence

scan Scanner accept() Scanner object to read user input

Loop control variable for generating


i int for loop
Fibonacci string terms

74
ASSIGNMENT 10

Q10. A company manufactures packing cartons in four sizes, i.e. cartons to accommodate
6 boxes, 12 boxes, 24 boxes and 48 boxes.
Design a program to accept the number of boxes to be packed (N) by the user (maximum
up to 1000 boxes) and display the break-up of the cartons used in descending order of
capacity (i.e. preference should be given to the highest capacity available, and if boxes left
are less than 6, an extra carton of capacity 6 should be used.)
Test your program with the following data and some random data: (Maintain test data
format)
Example 1
INPUT:
N = 726
OUTPUT:
48 * 15 = 720
6*1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16
Example 2
INPUT:
N = 140
OUTPUT:
48 * 2 = 96
24 * 1 = 24
12 * 1 = 12
6*1=6
Remaining boxes = 2 * 1 = 2
Total number of boxes = 140
Total number of cartons = 6
Example 3
INPUT:

75
N = 4296
OUTPUT:
INVALID INPUT

76
ALGORITHM :-

Method: get()
Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt and input N
Step 4: If N < 1 OR N > 1000, print "OUTPUT: INVALID INPUT" and exit
Step 5: Store original = N
Step 6: Set cartons = 0
Step 7: Create array sizes = {48, 24, 12, 6}
Step 8: Create array count[4]
Step 9: Set i = 0
Step 10: If i >= 4, GOTO Step 15
Step 11: Set count[i] = N / sizes[i]
Step 12: Update N = N % sizes[i]
Step 13: Add count[i] to cartons
Step 14: Increment i by 1, GOTO Step 10
Step 15: Set remaining = N
Step 16: If remaining > 0, increment cartons by 1
Step 17: Print "OUTPUT : "
Step 18: Set i = 0
Step 19: If i >= 4, GOTO Step 23
Step 20: If count[i] > 0, print sizes[i] * count[i] = product
Step 21: Increment i by 1
Step 22: GOTO Step 19

77
Step 23: If remaining > 0, print "Remaining boxes = remaining * 1 =
remaining"
Step 24: Else print "Remaining boxes = 0"
Step 25: Print "Total number of boxes = original"
Step 26: Print "Total number of cartons = cartons"
Step 27: End of function

Method: main(String args[])


Step 1: Start
Step 2: Create temporary object and call get()
Step 3: End of function

78
SOURCE CODE :-

import java.util.Scanner;
class CartonPacking
{
void get()
{
Scanner sc = new Scanner(System.in);
System.out.print("INPUT: N = ");
int N = sc.nextInt();
if (N<1 || N>1000)
{
System.out.println("OUTPUT: INVALID INPUT");
return;
}
int original = N;
int cartons = 0;
int[] sizes = {48,24,12,6};
int[] count = new int[4];
for (int i=0;i<sizes.length;i++)
{
count[i]=N/sizes[i];
N%=sizes[i];
cartons+=count[i];
}
79
int remaining=N;
if (remaining > 0)
cartons++;
System.out.println("OUTPUT : ");
for (int i=0;i<sizes.length;i++)
{
if (count[i] > 0)
System.out.println(sizes[i]+" * " +count[i]+" = "+(sizes[i]*count[i]));
}
if(remaining>0)
System.out.println("Remaining boxes = "+remaining+" * 1 = "
+remaining);
else
System.out.println("Remaining boxes = 0");
System.out.println("Total number of boxes = "+original+"\nTotal
number of cartons = "+cartons);
}
public static void main(String args[])
{
new CartonPacking().get();
}
}

80
OUTPUT :-

81
VARIABLE LISTING :-

CartonPacking

Variable
Data Type Scope Purpose/Description
Name

sc Scanner get() Scanner object to take input from user

N int get() Number of boxes to be packed

original int get() Stores original value of N for final display

cartons int get() Count of total cartons used

Array of predefined carton sizes (48, 24,


sizes int[] get()
12, 6)

Stores the number of cartons used for each


count int[] get()
carton size

Loop control variable to iterate over carton


i int for loop
sizes

Number of boxes left after using all full


remaining int get()
cartons

82
ASSIGNMENT 11

Q11. Write a program that will create a pattern with Fibonacci numbers in pyramid shape.

Numbers in the pattern i.e Fibonacci numbers must be generated using recursive
technique.

Take number of lines to print as input and display the Fibonacci pattern.
Example: n=5
Output:
0
11
235
8 13 21 34
55 89 144 233 377

83
ALGORITHM :-

Method: get()
Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt user and input n
Step 4: If n <= 0, print "Invalid Input" and exit
Step 5: Set count = 0
Step 6: Set i = 1
Step 7: If i > n, GOTO Step 17
Step 8: Set j = 1
Step 9: If j > n - i, GOTO Step 12
Step 10: Print two spaces
Step 11: Increment j by 1, GOTO Step 9
Step 12: Set k = 1
Step 13: If k > i, GOTO Step 16
Step 14: Print fibonacci(count) left-aligned in width 4
Step 15: Increment count and k, GOTO Step 13
Step 16: Print newline
Step 17: Increment i by 1, GOTO Step 7
Step 18: End of function

Method: fibonacci(n)
Step 1: Start
Step 2: If n <= 1, return n

84
Step 3: Else return fibonacci(n - 1) + fibonacci(n - 2)
Step 4: End of function
Method: main(String args[])
Step 1: Start
Step 2: Create temporary object of class Fibonacci
Step 3: Call get()
Step 4: End of function

85
SOURCE CODE :-

import java.util.Scanner;
class Fibonacci
{
void get()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter number of lines: ");
int n=sc.nextInt();
if(n<=0)
{
System.out.println("Invalid Input");
return;
}
int count = 0;
System.out.println();
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n-i;j++)
System.out.print(" ");
for (int k=1;k<=i;k++)
{
System.out.printf("%-4d",fibonacci(count));

86
count++;
}
System.out.println();
}
}
int fibonacci(int n)
{
if (n<=1)
return n;
else
return fibonacci(n-1)+fibonacci(n-2);
}
public static void main(String args[])
{
new Fibonacci().get();
}
}

87
OUTPUT :-

88
VARIABLE LISTING :-

Fibonacci

Variable
Data Type Scope Purpose/Description
Name

sc Scanner get() Scanner object to take input from user

Number of lines to be printed in the


n int get()
Fibonacci triangle

Counter to track Fibonacci term being


count int get()
printed

i int for loop Controls outer loop to print rows

Controls loop to print spaces before


j int for loop
Fibonacci numbers

Controls loop to print Fibonacci numbers


k int for loop
in each row

89
Variable
Data Type Scope Purpose/Description
Name

Argument for recursive Fibonacci


n int fibonacci()
function

ASSIGNMENT 12

Q12. Write a java program to print the oden sequence from a given number to a number
which is less or equal to 2. Also display length of the sequence.
Oden sequence is a sequence where the numbers go up and down again.

For example: 50, 13 , 7, 4, -2

Oden Sequences follow these rules:


If a number is even, divide it by 3(integer division) and subtract 3
If a number is odd, divide it by 2(integer division) and add 1.
Test Data :
Input any number (positive) to start for Oden Sequence : 92

Expected Output :

The Oden sequence starting at 92 is :


92 , 27 , 14, 1
90
The length of the sequence is 4.

ALGORITHM :-

Method: get()
Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt user and input num
Step 4: If num <= 0, print "Invalid Input." and exit
Step 5: Print "The Oden sequence starting at num is :"
Step 6: Set count = 0
Step 7: If num <= 2, GOTO Step 13
Step 8: Print num followed by a comma
Step 9: Increment count
Step 10: If num % 2 == 0, set num = num / 3 - 3
91
Step 11: Else set num = num / 2 + 1
Step 12: GOTO Step 7
Step 13: Print num
Step 14: Increment count
Step 15: Print "The length of the sequence is count."
Step 16: End of function

Method: main(String args[])


Step 1: Start
Step 2: Create temporary object of class Oden
Step 3: Call get()
Step 4: End of function

SOURCE CODE :-

import java.util.Scanner;
class Oden
{
void get()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive number : ");
int num=sc.nextInt();
if (num<=0)
{

92
System.out.println("Invalid Input.");
return;
}
System.out.println("The Oden sequence starting at " + num + " is :");
int count=0;
while (num>2)
{
System.out.print(num+", ");
count++;
if (num%2==0)
{
num=num/3-3;
}
else
{
num=num/2+1;
}
}
System.out.println(num);
count++;
System.out.println("The length of the sequence is " +count+ ".");
}
public static void main(String args[])
{
new Oden().get();
}

93
}

OUTPUT :-

94
VARIABLE LISTING :-
95
Oden

Variable
Data Type Scope Purpose/Description
Name

sc Scanner get() Scanner object to take input from user

Stores the user-entered positive number for


num int get()
Oden sequence

Tracks the number of terms printed in the


count int get()
Oden sequence

ASSIGNMENT 13

Q13. Design a class ArmNum to check if a given number is an Armstrong number or not.
96
[A number is said to be Armstrong if sum of its digits raised to the power of length of the
number is equal to the number]
Example : 371 = 33 + 73 + 13
1634 = 14 + 64 + 34 + 44
54748 = 55 + 45 + 75 + 45 + 85
Thus 371, 1634 and 54748 are all examples of Armstrong numbers.
Some of the members of the class are given below:
Class name : ArmNum
Data members/instance variables:
n : to store the number
l : to store the length of the numberMethods/Member functions:
ArmNum (int nn) : parameterized constructor to initialize the data member n=nn
int sum_pow(int i) : returns the sum of each digit raised to the power of the length of the
number using recursive technique.

eg. 34 will return 32 + 42 (as the length of the number is 2)


void isArmstrong( ) : checks whether the given number is an Armstrong number by
invoking the function sum_pow( ) and displays the result with an appropriate message
Specify the class ArmNum giving details of the constructor( ), int sum_pow(int) and void
isArmstrong( ).
Define a main( ) function to create an object and call the functions accordingly to enable
the task.

ALGORITHM :-

Constructor: ArmNum(int nn)


97
Step 1: Start
Step 2: Set n = nn
Step 3: Set l = number of digits in n
Step 4: End of constructor

Method: sum_pow(int i)
Step 1: Start
Step 2: If i == 0, return 0
Step 3: Set digit = i % 10
Step 4: Return (digit^l) + sum_pow(i / 10)
Step 5: End of function

Method: isArmstrong()
Step 1: Start
Step 2: Set result = sum_pow(n)
Step 3: If result == n, print "n is an Armstrong number"
Step 4: Else, print "n is not an Armstrong number"
Step 5: End of function

Method: main(String args[])


Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt and input num
Step 4: If num <= 0, print "Invalid Input" and exit
Step 5: Create object obj = new ArmNum(num)
Step 6: Call obj.isArmstrong()

98
Step 7: End of function

SOURCE CODE :-

import java.util.Scanner;
class ArmNum
99
{
int n;
int l;
ArmNum(int nn)
{
n=nn;
l=Integer.toString(n).length();
}
int sum_pow(int i)
{
if(i==0)
return 0;
int digit=i%10;
return (int)Math.pow(digit,l)+sum_pow(i/10);
}
void isArmstrong()
{
int result=sum_pow(n);
if(result==n)
System.out.println("\n"+n+" is an Armstrong number.");
else
System.out.println("\n"+n+" is not an Armstrong number.");
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

100
System.out.print("Enter a number:");
int num=sc.nextInt();
if(num<=0)
{
System.out.println("Invalid Input");
return;
}
ArmNum obj=new ArmNum(num);
obj.isArmstrong();
}
}

OUTPUT :-

101
VARIABLE LISTING :-

102
ArmNum

Variable
Data Type Scope Purpose/Description
Name

Stores the number to be checked as an


n int ArmNum
Armstrong number

l int ArmNum Stores the number of digits in n

Current value used to compute the


i int sum_pow(int)
recursive digit power sum

Stores the last digit of i during recursive


digit int sum_pow(int)
decomposition

Stores the result of the Armstrong power


result int isArmstrong()
sum

sc Scanner main() Scanner object to take input from user

num int main() Stores the number input by the user

Object of ArmNum class used to call


obj ArmNum main()
methods

ASSIGNMENT 14

Q14. The result of a quiz competition is to be prepared as follows:


103
The quiz has five questions with four multiple choices (A, B, C, D), with each
question carrying 2 marks for the correct answer and 1 mark to be
deducted for wrong answer.

Design a program to accept the number of participants N such that N must be greater
than 3 and less than 11. Create a double-dimensional array of size (Nx2) to store
participants details including participant roll and name. Create another 1D array of size 5
to store answers for 5 question. Create another 2D array of size Nx5 which will store
solution given by N participants.
Calculate the sxore for each participant by matching the correct answer stored in a
singledimensional array of size 5. Display the scores for each participant and also the
participant(s) having the highest score. Participants have to attempt all the 5 questions.
Design a super class Participant having following details:
Data member:
N: total number of participants (check validity as given above)
stud[][]: 2D array of size Nx2 storing participant name and roll(alphanumeric) in two
columns.
Method:
1) Participant(…): parameterised constructor
2) void accept(): Accept N participants details.
3) void display() : display participants details
Page 10 of 15Page 11 of 15

Sub class: Score


Data member:
key[]: array of size 5 storing only answer keys (A,B,C,D) for 5 questions
solve[][]: 2D array of size Nx5 which will store keys(A,B,C,D) only for 5 questions as
solved by
N participants.
score[]: 1D array to store final score of N participants.

Methods:
1) Score(…): parameterised constructor to initialise members of both super and sub class.
Initialise key[] array with the value as {‘A’, ‘B’, ‘B’, ‘D’, ‘C’}
104
2) void accept(): Accept answers for N participants in array solve[][].
3) void calculate(): Calculate final score for each participant as per point value given above
and update it in array score.
4) void display(): display details of participants, solution given by each participants, score
achieved by each participant. Also display the name(s) of participant(s) with highest score.
Create object in main method and call methods accordingly following property of
inheritance.

ALGORITHM :-

Algorithm for Participant Class

105
Constructor: Participant()
Step 1: Start
Step 2: Set N = n
Step 3: Create 2D string array stud[][]
Step 4: End of constructor

Method: accept()
Step 1: Start
Step 2: Create Scanner object
Step 3: Set i = 0
Step 4: If i >= N, GOTO Step 10
Step 5: Prompt and input participant name into stud[][]
Step 6: Prompt and input participant roll into stud[][]
Step 7: Convert both to uppercase and trim
Step 8: Increment i by 1
Step 9: GOTO Step 4
Step 10: End of function

Method: display()
Step 1: Start
Step 2: Print heading and column titles
Step 3: Set i = 0
Step 4: If i >= N, GOTO Step 7
Step 5: Print participant name and roll with numbering
Step 6: Increment i by 1, GOTO Step 4
Step 7: Print line

106
Step 8: End of function

Algorithm for Score Class


Constructor: Score()
Step 1: Start
Step 2: Call super(n)
Step 3: Initialize key = {'A','B','B','D','C'}
Step 4: Create 2D char array solve[][]
Step 5: Create int array score[]
Step 6: End of constructor

Method: accept()
Step 1: Start
Step 2: Call super.accept()
Step 3: Create Scanner object
Step 4: Set i = 0
Step 5: If i >= N, GOTO Step 20
Step 6: Print participant name and roll
Step 7: Prompt for answer input
Step 8: Set j = 0
Step 9: If j >= 5, GOTO Step 18
Step 10: Prompt and input answer into solve[i][j]
Step 11: If answer not in "ABCD", print invalid message and GOTO Step 10
Step 12: Increment j by 1
Step 13: GOTO Step 9
Step 14: Increment i by 1, GOTO Step 5

107
Step 15: End of function

Method: calculate()
Step 1: Start
Step 2: Set i = 0
Step 3: If i >= N, GOTO Step 8
Step 4: Set j = 0
Step 5: If j >= 5, GOTO Step 7
Step 6: If solve[i][j] == key[j], add 2 to score[i], else subtract 1
Step 7: Increment j by 1, GOTO Step 5
Step 8: Increment i by 1, GOTO Step 3
Step 9: End of function

Method: display()
Step 1: Start
Step 2: Call super.display()
Step 3: Set maxscore = score[0]
Step 4: Set i = 0
Step 5: If i >= N, GOTO Step 14
Step 6: If score[i] > maxscore, set maxscore = score[i]
Step 7: Print participant name and roll
Step 8: Print solution and score heading
Step 9: Set j = 0
Step 10: If j >= 5, GOTO Step 13

Step 11: Print solution with ✓ or ✗ and score in middle row


Step 12: Increment j by 1, GOTO Step 10
108
Step 13: Print line and increment i, GOTO Step 5
Step 14: Print highest score
Step 15: Print achievers heading
Step 16: Set i = 0
Step 17: If i >= N, GOTO Step 20
Step 18: If score[i] == maxscore, print name and roll
Step 19: Increment i by 1, GOTO Step 17
Step 20: End of function
Algorithm for ScoreMain Class
Method: main(String args[])
Step 1: Start
Step 2: Prompt and input N
Step 3: If N <= 3 OR N >= 11, print "INVALID INPUT" and exit
Step 4: Create object ob = new Score(N)
Step 5: Call ob.accept()
Step 6: Call ob.calculate()
Step 7: Call ob.display()
Step 8: End of function

SOURCE CODE :-

109
//super class which stores participant details
import java.util.Scanner;
class Participant{ protected int N; protected String stud[][];
protected Participant(int n) {
N=n; stud=new String[N][2]; }
void accept(){
Scanner sc=new Scanner(System.in);
for(int i=0;i<N;i++)//to accept each participant's name and roll
{ System.out.print((i+1)+") ENTER PARTICIPANT NAME: ");
stud[i][0]=sc.nextLine().toUpperCase().trim();
System.out.print(" ".repeat((""+(i+1)).length()+2)+"ENTER PARTICIPANT
ROLL: ");
stud[i][1]=sc.nextLine().trim().toUpperCase(); } }
void display()//to display each participant details
{ System.out.println("-".repeat(40)+"\nPARTICIPANTS OF QUIZ
COMPETITION\n"+"-".repeat(40));
System.out.printf("%-28sPARTICIPANT ROLL\n","PARTICIPANT NAME");
System.out.println("-".repeat(20)+" ".repeat(8)+"-".repeat(20));
for(int i=0;i<N;i++)
System.out.printf((i+1)+") %-25s"+stud[i][1]+"\n",stud[i][0]);
System.out.println("-".repeat(80)); } }
//Sub class to accept answers and display score of participants
import java.util.Scanner;
class Score extends Participant{
private char key[],solve[][];
private int score[];
Score(int n){ super(n);
110
key=new char[]{'A','B','B','D','C'};
solve=new char[N][5]; score=new int[N];
}
void accept()//accept answers of participants
{
super.accept();
Scanner sc=new Scanner(System.in);
for(int i=0;i<N;i++)
{
System.out.println("\fPARTICIPANT NAME:
"+stud[i][0]+"\t\tPARTICIPANT ROLL: "+stud[i][1]+"\n");
System.out.println("ENTER ANSWER KEYS(A,B,C,D) only: ");
for(int j=0;j<5;j++)
{
System.out.print("QUESTION "+(j+1)+". ");
solve[i][j]=sc.next().charAt(0);
if("ABCD".indexOf(solve[i][j])==-1)//check answer key is only
A,B,C,D
{
System.out.println("INVALID ANSWER KEY.");
j--;
}
}
System.out.print("\f");
}
}
void calculate()//to calculate final score of each participant
111
{
for(int i=0;i<N;i++)//for each studentt
for(int j=0;j<5;j++)//for each question
score[i]+=(solve[i][j]==key[j])?2:-1;//if correct +2 else -1
}
void display()//to display details and score of participants
{ super.display();
int maxscore=score[0];//store highest score
for(int i=0;i<N;i++)//for each student
{ if(score[i]>maxscore)
maxscore=score[i];
System.out.println("PARTICIPANT NAME:
"+stud[i][0]+"\t\tPARTICIPANT ROLL: "+stud[i][1]+"\n");
System.out.println("SOLUTION OF PARTICIPANT\t\tSCORE\n");
for(int j=0;j<5;j++)//each question answer
{
System.out.print("QUESTION "+(j+1)+".
"+solve[i][j]+((solve[i][j]==key[j])?"✓(+2)":"✗(-1)"));
if(j==2) System.out.println("\t\t"+score[i]);
else System.out.println();
}
System.out.println("-".repeat(80));
}
System.out.println("-".repeat(40)+"\nHIGHEST SCORE-------
>"+maxscore+"\n");
System.out.print("ACHIEVED BY: ");
System.out.printf("%-25sPARTICIPANT ROLL\n","PARTICIPANT NAME");
112
System.out.println(" ".repeat(13)+"-".repeat(20)+" ".repeat(5)+"-
".repeat(20));
for(int i=0;i<N;i++)//to print highest scorer details
{
if(score[i]==maxscore)
System.out.printf(" ".repeat(13)+"%-25s"+stud[i][1]+"\n",stud[i][0]);
}
}
}
import java.util.Scanner;
class ScoreMain{
public static void main(String args[]) {
System.out.print("ENTER NUMBER OF PARTICIPANTS(N): ");
int N=new Scanner(System.in).nextInt();
if(!(N>3&&N<11)) {
System.out.print("INVALID INPUT");
return;
}
Score ob = new Score(N);
ob.accept();
ob.calculate();
ob.display();
}
}
OUTPUT :-

113
114
VARIABLE LISTING :-
115
Participant

Variable
Data Type Scope Purpose/Description
Name

N int Participant Number of participants

2D array to store each participant’s name


stud String[][] Participant
and roll

sc Scanner accept() Scanner object to take input

i int for loop Loop variable to iterate over participants

Score

Variable
Data Type Scope Purpose/Description
Name

key char[] Score Array storing correct answers for the quiz

solve char[][] Score 2D array storing participant answers

score int[] Score Array to store scores of each participant

sc Scanner accept() Scanner object to read user input

i int for loop Outer loop to iterate over each participant

j int for loop Inner loop to iterate over each answer

Stores the highest score among all


maxscore int display()
participants

ScoreMain

Variable
Data Type Scope Purpose/Description
Name

N int main() Number of participants

sc Scanner main() Scanner object for user input

ob Score main() Object of Score class to perform operations

ASSIGNMENT 15

116
Q15. A superclass Detail has been defined to store the details of a customer. Define a
subclass Bill to compute the monthly telephone charge of the customer as per the chart is
given below:
Number of calls: Rate
1 – 100: Only rental charge
101 – 200: 60 paise per call + rental charge
201 – 300: 80 paise per call + rental charge
Above 300: 1 rupee per call + rental charge
The details of both the classes are given below:
Class name: Detail
Data members/instance variables:
name: to store the name of the customer
address: to store the address of the customer
telno: to store the phone number of the customer
rent: to store the monthly rental charge
Member functions:
Detail (…): parameterized constructor to assign values to data members
void show (): to display the details of the customerPage 12 of 15
Class name: Bill
Data members/instance variables:
n: to store the number of calls amt: to store the amount to be paid by the customer
Member functions:
Bill (…): parameterized constructor to assign values to data members of both classes and
to initialize amt = 0.0
void cal(): calculate the monthly telephone charge as per the chart is given above
void show(): displays the details of the customer and amount to be paid.
Specify the class Detail giving details of the constructor, and void show(). Using the
concept of inheritance, specify the class Bill giving details of the constructor(), void cal()
and void show().
Write the main ( ) to test the program.

ALGORITHM :-

117
Class: Detail
Constructor: Detail(String n, String a, long t, double r)
Step 1: Start
Step 2: Set name = n
Step 3: Set address = a
Step 4: Set telno = t
Step 5: Set rent = r
Step 6: End of constructor

Method: show()
Step 1: Start
Step 2: Print "Name: " + name
Step 3: Print "Address: " + address
Step 4: Print "Telephone Number: " + telno
Step 5: Print "Rental Charge: ₹" + rent rounded to two decimal places
Step 6: End of function

Class: Bill (subclass of Detail)


Constructor: Bill(String nm, String a, long t, double r, int noc)
Step 1: Start
Step 2: Call super(nm, a, t, r)
Step 3: Set n = noc
Step 4: Set amt = 0.0
Step 5: End of constructor

Method: cal()
Step 1: Start
Step 2: If n >= 1 AND n <= 100, set amt = rent
Step 3: Else if n >= 101 AND n <= 200, set amt = 0.60 × n + rent
Step 4: Else if n >= 201 AND n <= 300, set amt = 0.80 × n + rent

118
Step 5: Else if n > 300, set amt = 1.0 × n + rent
Step 6: End of function

Method: show()
Step 1: Start
Step 2: Call super.show()
Step 3: Print "Amount to be PAID: ₹" + amt rounded to two decimal places
Step 4: End of function

Class: MainBill

Method: main(String args[])


Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt and input name, convert to uppercase
Step 4: Prompt and input address
Step 5: Prompt and input telno
Step 6: If number of digits in telno is not 10, print "INVALID PHONE NUMBER" and
exit
Step 7: Prompt and input rent
Step 8: If rent < 0, print "INVALID MONTHLY RENTAL CHARGE" and exit
Step 9: Prompt and input n (number of calls)
Step 10: If n < 0, print "INVALID NUMBER OF CALLS" and exit
Step 11: Create object ob = new Bill(name, address, telno, rent, n)
Step 12: Call ob.cal()
Step 13: Call ob.show()
Step 14: End of function

SOURCE CODE :-

119
class Detail
{
protected String name,address;
protected long telno;
protected double rent;
protected Detail(String n,String a,long t,double r)
{
name=n;
address=a;
telno=t;
rent=r;
}
void show()//to display details of customer
{
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("Telephone Number: "+telno);
System.out.println("Rental Charge:
₹"+(Math.round(rent*100)/100.0));//two decimal places (paise)
}
}
class Bill extends Detail
{
int n;
double amt;
Bill(String nm,String a,long t,double r,int noc)

120
{
super(nm,a,t,r);
n=noc;
amt=0.0;
}
void cal()//to calculate monthly telephone charge
{
if(n>=1 && n<=100)
amt=super.rent;
else if(n>=101 && n<=200)
amt=0.60*n+super.rent;
else if(n>=201 && n<=300)
amt=0.80*n+super.rent;
else if(n>300)
amt=1.0*n+super.rent;
}
void show()//to display telephone bill
{
super.show();
System.out.println("Amount to be PAID:
₹"+String.format("%.2f",amt));//two decimal places(paise)
}
}

OUTPUT :-
121
122
VARIABLE LISTING :-

Detail

Variable Name Data Type Scope Purpose/Description

name String Detail Name of the customer

address String Detail Address of the customer

telno long Detail Telephone number

rent double Detail Monthly rental charge

Bill

Variable Name Data Type Scope Purpose/Description

n int Bill Number of calls made

amt double Bill Final amount to be paid

MainBill

Variable Name Data Type Scope Purpose/Description

sc Scanner main() Scanner object for user input

nm String main() Name of the customer

ad String main() Address of the customer

tno long main() Telephone number

r double main() Monthly rental charge

n int main() Number of calls made

Object of Bill class to calculate


ob Bill main()
and display

123
ASSIGNMENT 16

Q16. An interface Data is defined with a data member and a method volume( ) which
returns the volume of the implementing shape.
A super class Base has been defined to contain the radius of a geometrical shape.
Define a sub class CalVol which uses the properties of the interface Data and the class
Base and calculates the volume of a cylinder.
The details of the members of the interface and both the classes are given below:
Interface name
Data
Data member: double pi: initialize pi = 3.142
Member functions/methods:
double volume( ) :abstract method
Class name: Base
Data member/instance variable: rad: to store the radius in decimal
Member functions/methods:
Base(…) parameterized constructor to initialize the data member
void show( ) displays the radius with an appropriate message
Class name: CalVol
Data member/instance variable:
ht: to store the height in decimal
Member functions/methods:
CalVol(…) parameterized constructor to initialize the data members of both the classes
double volume( )
calculates the volume of a cylinder by using the formula ( pi x radius^2 x height )
void show( ) displays the data members of both the classes and the volume of the cylinder
with appropriate messagePage 13 of 15
Using the concept of inheritance, specify the class CalVol giving the details of the
constructor(…), double volume( ) and void show( ) along with details of interface and
super class.
Write main method to implement the logic.

124
ALGORITHM :-

Interface: Data
Variable Declaration
Step 1: Define pi = 3.142
Step 2: Declare method volume() that returns double

Class: Base
Constructor: Base(double r)
Step 1: Start
Step 2: Set rad = r
Step 3: End of constructor

Method: show()
Step 1: Start
Step 2: Print "RADIUS: " + rad
Step 3: End of function

Class: CalVol (extends Base, implements Data)


Constructor: CalVol(double r, double h)
Step 1: Start
Step 2: Call super(r)
Step 3: Set ht = h
Step 4: End of constructor

125
Method: volume()
Step 1: Start
Step 2: Return pi * rad * rad * ht
Step 3: End of function

Method: show()
Step 1: Start
Step 2: Call super.show()
Step 3: Print "HEIGHT: " + ht
Step 4: Print "VOLUME OF CYLINDER: " + volume()
Step 5: End of function

Class: CalVolMain
Method: main(String args[])
Step 1: Start
Step 2: Create Scanner object
Step 3: Prompt and input r
Step 4: Prompt and input h
Step 5: If r < 0 OR h < 0, print "INVALID INPUT" and exit
Step 6: Create object ob = new CalVol(r, h)
Step 7: Call ob.show()
Step 8: End of function

126
SOURCE CODE :-

interface Data
{
double pi=3.142;
double volume();
}
class Base
{
protected double rad;
protected Base(double r)
{
rad=r;
}
void show()//prints radius of cylinder
{
System.out.println("RADIUS: "+rad);
}
}
class CalVol extends Base implements Data
{
double ht;
CalVol(double r,double h)
{
super(r);
ht=h;

127
}
public double volume()//calculates volume of cylinder
{
return pi*rad*rad*ht;
}
void show()//prints cylinder detils
{
super.show();
System.out.println("HEIGHT: "+ht);
System.out.println("VOLUME OF CYLINDER: "+volume());
}
}
import java.util.Scanner;
class CalVolMain
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("ENTER RADIUS OF CYLINDER: ");
double r=sc.nextDouble();
System.out.print("ENTER HEIGHT OF CYLINDER: ");
double h=sc.nextDouble();
if(r<0||h<0)
{
System.out.println("INVALID INPUT");
return;

128
}
CalVol ob = new CalVol(r,h);
ob.show();
}
}

129
OUTPUT :-

130
VARIABLE LISTING :-

Base

Variable Name Data Type Scope Purpose/Description

rad double Base Radius of the cylinder's base

CalVol

Variable Name Data Type Scope Purpose/Description

ht double CalVol Height of the cylinder

CalVolMain

Variable Name Data Type Scope Purpose/Description

sc Scanner main() Scanner object for user input

r double main() Radius entered by user

h double main() Height entered by user

Object of CalVol to compute and


ob CalVol main()
display volume

131
ASSIGNMENT 17

Q17. WordPile is an entity which can hold a maximum of 20 characters. The restriction is
that a character can be added or removed from one end only.
Some of the members of classes are given below:
Class name: WordPile
Data members/instance variables:
ch[]: character array to hold the character elements
capacity: integer variable to store the maximum capacity
top: to point to the index of the topmost element
Member functions/methods:
WordPile (int cap): constructor to initialise the data member
capacity = cap, top = -1 and create the WordPile
void pushChar(char v): adds the character to the top of WordPile if possible, otherwise
output a
message “WordPile is full”
char popChar(): returns the deleted character from the top of the WordPile if possible,
otherwise it returns null character.
Write the main ( ) to test the program.

132
ALGORITHM :-

Constructor: WordPile(int cap)


Step 1: Start
Step 2: Set capacity = cap
Step 3: Set top = -1
Step 4: Create character array ch of size capacity
Step 5: End of constructor

Method: pushChar(char v)
Step 1: Start
Step 2: If top == capacity - 1, print "WordPile is full" and exit
Step 3: Else increment top and assign ch[top] = v
Step 4: End of function

Method: popChar()
Step 1: Start
Step 2: If top == -1, return null character
Step 3: Else return ch[top--]
Step 4: End of function

Method: main(String args[])


Step 1: Start
Step 2: Create Scanner object
Step 3: Input s
Step 4: If s < 0 OR s > 20, GOTO Step 3

133
Step 5: Create object ob = new WordPile(s)
Step 6: Set an = 'y'
Step 7: If an != 'y' AND an != 'Y', GOTO Step 19
Step 8: Display menu: "Press 1 to add, 2 to delete..."
Step 9: Input choice
Step 10: If choice == 1, GOTO Step 11
Step 11: Input character x, call ob.pushChar(x), GOTO Step 17
Step 12: If choice == 2, GOTO Step 13
Step 13: Call ob.popChar() and store in y
Step 14: If y == null character, print "WordPile is empty"
Step 15: Else print "Deleted character: y"
Step 16: GOTO Step 17
Step 17: If choice is not 1 or 2, print "INVALID CHOICE"
Step 18: Prompt and input an
Step 19: If an == 'y' OR an == 'Y', GOTO Step 7
Step 20: End of function

134
SOURCE CODE :-

import java.util.Scanner;
class WordPile
{
private char ch[];
private int capacity,top;
private WordPile(int cap)
{
capacity = cap;
top=-1;
ch=new char[capacity];
}
private void pushChar(char v)//to add charcters into Word Pile
{
if(top==capacity-1)//word pile full
System.out.println("WordPile is full");
else
ch[++top]=v;
}
private char popChar()//to remove charcters from Word Pile
{
if(top==-1)//word pile empty
return '\u0000';
else
return ch[top--];
135
}
public static void main(String args[])
{
int s; char an ;
Scanner sc=new Scanner(System.in);
do{
System.out.print("Enter Maximum Capacity: ");
s=sc.nextInt();
}while(s<0||s>20);
WordPile ob=new WordPile(s);
do{ System.out.println("Press 1 to add, 2 to delete.....");
System.out.print("Enter your choice: ");
int choice=sc.nextInt();
switch(choice){
case 1: System.out.print("Enter the Character: ");
char x=sc.next().charAt(0);
ob.pushChar(x);
break ;
case 2: char y=ob.popChar();
if(y=='\u0000')
System.out.println("WordPile is empty.");
else
System.out.println("Deleted character: "+y);
break ;
default: System.out.println("INVALID CHOICE");
}

136
System.out.print("Do you want to continue(y/n): ");
an=sc.next().charAt(0);
}while(an=='y' || an=='Y');
}
}

137
OUTPUT :-

138
VARIABLE LISTING :-

WordPile

Variable Name Data Type Scope Purpose/Description

ch char[] WordPile Array to store characters in the stack

capacity int WordPile Maximum size of the character stack

top int WordPile Index of the top element in the stack

s int main() Maximum capacity input from user

an char main() User's response for continuing the loop

sc Scanner main() Scanner object to read input

User menu choice (push or pop


choice int for loop
operation)

Character input to be pushed into the


x char for loop
stack

y char for loop Character popped from the stack (if any)

139
ASSIGNMENT 18

Q18. A queue is an entity which can hold a maximum of 100 integers. The queue enables
the user to add integers from the rear and remove integers from the front.
Define a class Queue with the following details:
Class name: Queue
Data members/instance variables:
Que[]: array to hold the integer elements
size: stores the size of the array
front: to point the index of the front
rear: to point the index of the rear
Member functions:
Queue(int mm): constructor to initialize the data size = mm, front = 0, rear = 0
void addele(int v): to add integer from the rear if possible else display the message
“Overflow”
int delele(): returns elements from front if present, otherwise displays the message
“Underflow”
and return -9999
void display(): displays the array elements
Write the main ( ) to test the program.

140
ALGORITHM :-

Constructor: Queue(int mm)


Step 1: Start
Step 2: Set size = mm
Step 3: Create integer array Que of size size
Step 4: Set front = 0, rear = 0
Step 5: End

Method: addele(int v)
Step 1: Start
Step 2: If rear == size - 1, print "Overflow" and exit
Step 3: Else increment rear and store v in Que[rear]
Step 4: End

Method: delele()
Step 1: Start
Step 2: If front == rear, print "Underflow", return -9999
Step 3: Else increment front and return Que[front]
Step 4: End

Method: display()
Step 1: Start
Step 2: If front == rear, print "QUEUE EMPTY"
Step 3: Else loop from i = front + 1 to i <= rear and print Que[i]
Step 4: Print new line
Step 5: End
141
Method: main(String args[])
Step 1: Start
Step 2: Create Scanner object
Step 3: Input s
Step 4: If s < 0 OR s > 100, repeat Step 3
Step 5: Create object ob = new Queue(s)
Step 6: Set an = 'y'
Step 7: If an != 'y' AND an != 'Y', GOTO Step 18
Step 8: Display menu options
Step 9: Input ch
Step 10: If ch == 1, GOTO Step 11
Step 11: Input x, call ob.addele(x), GOTO Step 17
Step 12: If ch == 2, GOTO Step 13
Step 13: Call ob.delele() and store in t
Step 14: If t != -9999, print "Deleted element: t", GOTO Step 17
Step 15: If ch == 3, GOTO Step 16
Step 16: Call ob.display(), GOTO Step 17
Step 17: If ch is not 1, 2, or 3, print "Wrong Choice"
Step 18: Input an
Step 19: If an == 'y' OR an == 'Y', GOTO Step 7
Step 20: End

142
SOURCE CODE :-

import java.util.Scanner;
class Queue
{
private int Que[],size,front,rear;
private Queue(int mm)
{
size=mm;
Que=new int[size];
front=rear=0;
}
private void addele(int v)//to add integers
{
if(rear==size-1)//Queue overflow
System.out.println("Overflow");
else
Que[++rear]=v;
}
private int delele()//to delete elements
{
if(front==rear)//no element present
{
System.out.println("Underflow");
return -9999;
}
else
143
return Que[++front];
}
private void display()//to display elements
{
if(front==rear)
System.out.println("QUEUE EMPTY");
else
{
for(int i=front+1;i<=rear;i++)
System.out.print(Que[i]+" ");
}
System.out.println();
}
public static void main(String args[])
{
int s; char an ;
Scanner sc=new Scanner(System.in);
do{
System.out.print("Enter size of array: ");
s=sc.nextInt();
}while(s<0||s>100);
Queue ob=new Queue(s);
do{ System.out.println("Press 1 to add, 2 to delete, 3 to display.........");
System.out.print("Enter your choice: ");
int ch=sc.nextInt();
switch(ch){

144
case 1: System.out.print("Enter integer: ");
int x=sc.nextInt();
ob.addele(x);
break ;
case 2: int t=ob.delele();
if(t!=-9999)
System.out.println("Deleted element: "+t);
break ;
case 3 : ob.display();
break ;
default: System.out.println("Wrong Choice");
}
System.out.print("Do you wants to continue(y/n): ");
an=sc.next().charAt(0);
}while(an=='y' || an=='Y');
}
}

145
OUTPUT :-

146
VARIABLE LISTING :-

Queue

Variable
Data Type Scope Purpose/Description
Name

Que int[] Queue Array representing the queue

size int Queue Maximum capacity of the queue

front int Queue Index pointing before the front element

Index pointing at the last element in the


rear int Queue
queue

s int main() Size of the queue entered by user

an char main() User's choice to continue the loop

sc Scanner main() Scanner object to read input

ch int for loop Menu choice entered by user

x int for loop Integer to be added into the queue

t int for loop Element deleted from the queue

147
ASSIGNMENT 19

Q19. Interface : StringStack


Methods:
void insert(String item) //store an item
String del() // delete an item
void display() // print stack entry
class name : FixedStack (stack with fixed size)
Date members:
private String fq[]: array storing stack data
private int top
Methods:
FixedStack(int size): constructor creating array with size taken as input. Initialises top to 0.
class name : DynamicStack (stack that will grow double the size when it reaches overflow
condition)
Date members:
private String dq[]: array storing stack data
private int top
Methods:
DynamicStack(int size): constructor creating array with size taken as input. Initialises top
to 0.
Implement the abstract methods of the interface in both the classes. Finally write the main
method in the class InterfaceImplement and create a reference of interface type to store
object
reference of both the classes FixedStack and DynamicStack and call the methods
accordingly.
Design a menu to show the working of both the stacks(Fixed and Dynamic) on user`s
choice

148
ALGORITHM :-

Interface: StringStack
Step 1: Declare method insert(String)
Step 2: Declare method del() returning String
Step 3: Declare method display()
Step 4: End

Class: FixedStack
Constructor: FixedStack(int size)
Step 1: Set fq as a string array of given size
Step 2: Set top = 0
Step 3: End
Method: insert(String i)
Step 1: If top == fq.length, print "STACK OVERFLOW" and return
Step 2: Else store i in fq[top], increment top
Step 3: End
Method: del()
Step 1: If top == 0, return null
Step 2: Else decrement top, return fq[top]
Step 3: End
Method: display()
Step 1: If top == 0, print "STACK UNDERFLOW" and return
Step 2: Else from i = top-1 to 0, print fq[i]
Step 3: End

149
Class: DynamicStack
Constructor: DynamicStack(int size)
Step 1: Set dq as a string array of given size
Step 2: Set top = 0
Step 3: End
Method: insert(String i)
Step 1: If top == dq.length, double the array size using copyOf()
Step 2: Store i in dq[top], increment top
Step 3: End
Method: del()
Step 1: If top == 0, return null
Step 2: Else decrement top, return dq[top]
Step 3: End
Method: display()
Step 1: If top == 0, print "STACK UNDERFLOW" and return
Step 2: Else from i = top-1 to 0, print dq[i]
Step 3: End

Class: InterfaceImplement
Method: main(String args[])
Step 1: Start
Step 2: Create Scanner object
Step 3: GOTO Step 4
Step 4: Display "Press 1 for Fixed Stack, 2 for Dynamic Stack"
Step 5: Input user choice c1
Step 6: If c1 == 1, GOTO Step 7

150
Step 7: Repeat input of s until s >= 0
Step 8: Create FixedStack fs = new FixedStack(s)
Step 9: GOTO Step 11
Step 10: If c1 == 2, GOTO Step 15
Step 11: Repeat:
Display "Press 1 to insert, 2 to delete, 3 to print"
Input choice c2
If c2 == 1, input string str, call fs.insert(str)
If c2 == 2, call fs.del() and print result or underflow
If c2 == 3, call fs.display()
If invalid, print "Wrong Choice"
Ask "Do you want to continue(y/n)"
If Yes, repeat Step 11
Step 12: End FixedStack handling
Step 13: GOTO Step 19
Step 15: Repeat input of s until s >= 0
Step 16: Create DynamicStack ds = new DynamicStack(s)
Step 17: Repeat:
Display "Press 1 to insert, 2 to delete, 3 to print"
Input choice c3
If c3 == 1, input string str, call ds.insert(str)
If c3 == 2, call ds.del() and print result or underflow
If c3 == 3, call ds.display()
If invalid, print "Wrong Choice"
Ask "Do you want to continue(y/n)"
If Yes, repeat Step 17

151
Step 18: End DynamicStack handling
Step 19: Ask "Do you want to create another Stack(y/n)"
Step 20: If Yes, GOTO Step 4
Step 21: End

152
SOURCE CODE :-

interface StringStack
{
void insert(String item);
String del();
void display();
}
class FixedStack implements StringStack
{
private String fq[];
private int top;
FixedStack(int size)
{
fq=new String[size];
top=0;
}
public void insert(String i)//to store an item
{
if(top==fq.length)
System.out.println("STACK OVERFLOW");
else
fq[top++]=i;
}
public String del()//delete an item
{

153
if(top==0)
return null;
else
return fq[--top];
}
public void display()//print stack entry
{
if(top==0)
{
System.out.println("STACK UNDERFLOW");
return;
}
for(int i=top-1;i>=0;i--)
System.out.println(fq[i]);
}
}
class DynamicStack implements StringStack
{
private String dq[];
private int top;
DynamicStack(int size)
{
dq=new String[size];
top=0;
}
public void insert(String i)//to store an item

154
{
if(top==dq.length)//Stack overflow
dq=java.util.Arrays.copyOf(dq,dq.length*2);
dq[top++]=i;
}
public String del()//delete an item
{
if(top==0)
return null;
else
return dq[--top];
}
public void display()//print stack entry
{
if(top==0)
{
System.out.println("STACK UNDERFLOW");
return;
}
for(int i=top-1;i>=0;i--)
System.out.println(dq[i]);
}
}
class InterfaceImplement
{
public static void main(String args[])

155
{
int s;
java.util.Scanner sc=new java.util.Scanner(System.in);
do{
System.out.println("Press 1 for Fixed Stack, 2 for Dynamic
Stack.........");
System.out.print("Enter your choice: ");
switch(sc.nextInt())
{
case 1:
do{
System.out.print("Enter size of Fixed Stack: ");
s=sc.nextInt();
if(s<0)
System.out.println("INVALID SIZE");
}while(s<0);
StringStack fs=new FixedStack(s);
do{
System.out.println("Press 1 to insert, 2 to delete, 3 to
print.........");
System.out.print("Enter your choice: ");
switch(sc.nextInt())
{
case 1: System.out.print("Enter String: ");
fs.insert(new java.util.Scanner(System.in).nextLine());
break ;
case 2: String t=fs.del();
156
if(t==null)//.equals give null pointer exception
System.out.println("STACK UNDERFLOW");
else
System.out.println("Deleted item: "+t);
break ;
case 3: fs.display();
break ;
default: System.out.println("Wrong Choice");
}
System.out.print("Do you want to continue(y/n): ");
}while(Character.toUpperCase(sc.next().charAt(0))=='Y');
break;
case 2:
do{
System.out.print("Enter size of Dynamic Stack: ");
s=sc.nextInt();
if(s<0)
System.out.println("INVALID SIZE");
}while(s<0);
StringStack ds=new DynamicStack(s);
do{
System.out.println("Press 1 to insert, 2 to delete, 3 to
print.........");
System.out.print("Enter your choice: ");
switch(sc.nextInt())
{

157
case 1: System.out.print("Enter String: ");
ds.insert(new java.util.Scanner(System.in).nextLine());
break ;
case 2: String t=ds.del();
if(t==null)
System.out.println("STACK UNDERFLOW");
else
System.out.println("Deleted item: "+t);
break ;
case 3: ds.display();
break ;
default: System.out.println("Wrong Choice");
}
System.out.print("Do you want to continue(y/n): ");
}while(Character.toUpperCase(sc.next().charAt(0))=='Y');
break;
default:
System.out.println("Wrong Choice");
}
System.out.print("\fDo you want to create another Stack(y/n): ");
}while(Character.toUpperCase(sc.next().charAt(0))=='Y');
}
}

158
OUTPUT :-

159
VARIABLE LISTING :-

FixedStack

Variable Name Data Type Scope Purpose/Description

Array to store elements in fixed-size


fq String[] FixedStack
stack

top int FixedStack Index of the top eleent in stack

i int for loop Loop variable for displaying stack ()

DynamicStack

Variable Name Data Type Scope Purpose/Description

Index of the top element of the


top int DynamicStack
stack

Array to store elements in


dq String[] DynamicStack
dynamic-size stack

Loop variable for displaying stack


i int for loop
()

InterfaceImplement

Variable
Data Type Scope Purpose/Description
Name

s int main() Size of the stack entered by user

sc Scanner main() Scanner object to take user input

t String for loop Item deleted from the stack

fs StringStack main() Reference for FixedStack object

ds StringStack main() Reference for DynamicStack object

Loop variable for displaying stack (


i int for loop
)

160
ASSIGNMENT 20

Q20. A super class Record contains names and marks of the students in two different
single dimensional arrays. Define a sub class Lowest to display the name(s) of the
student(s) obtaining the lowest mark.
The details of the members of both the classes are given below:
Class name : Record
Data member/instance variable:
n[ ] : array to store names
m[ ] : array to store marks
size : to store the number of students
Member functions/methods:
Record(int cap) : parameterized constructor to initialize the data member size = cap Page 15
of 15

void readarray() : to enter elements in both the arrays


void display( ) : displays the array elements
class name: Lowest
Member functions/methods:
Lowest(...) : parameterized constructor to initialize the data members of both the classes
void display( ) : displays the array elements along with the names and marks of all the
students.

Also display name of the student(s) and marks who have scored lowest marks. Don`t use
any sorting method to implement the logic.

161
ALGORITHM :-

Class: Record
Constructor:
Step 1: Store the total number of students
Step 2: Create arrays to hold names and marks
Step 3: End
Method: readarray()
Step 1: Repeat for each student
Step 2: Accept name
Step 3: Accept marks
Step 4: End loop
Step 5: End
Method: display()
Step 1: Print table headings
Step 2: Repeat for each student
Step 3: Print name and marks
Step 4: End loop
Step 5: End

Class: Lowest
Constructor:
Step 1: Call the constructor of Record
Step 2: End
Method: display()

162
Step 1: Call super.display()
Step 2: Set lowest to first mark
Step 3: Repeat for each mark
Step 4: If current mark is lower, update lowest
Step 5: End loop
Step 6: Print heading for lowest scorers
Step 7: Repeat for each student
Step 8: If marks match lowest, print name and mark
Step 9: End loop
Step 10: End

Class: RecordMain
Main Method:
Step 1: Accept number of students
Step 2: If input is invalid, print error and stop
Step 3: Create object of Lowest
Step 4: Call method to read student records
Step 5: Call method to display records and lowest scorer
Step 6: End

163
SOURCE CODE :-

import java.util.Scanner;
class Record
{
protected String n[];
protected int m[],size;
protected Record(int cap)
{
size=cap;
n=new String[size];
m=new int[size];
}
void readarray()//to accept name and marks of students
{
for(int i=0;i<size;i++)
{
System.out.print("Enter name of student: ");
n[i]=new Scanner(System.in).nextLine().trim();
System.out.print("Enter marks: ");
m[i]=new Scanner(System.in).nextInt();
}
}
void display()//to display name and marks of students
164
{
System.out.println(" ".repeat(8+(""+size).length())+"NAME OF
STUDENT"+" ".repeat(7)+"MARKS");
System.out.println(" ".repeat((""+size).length()+2)+"-".repeat(30-
((""+size).length()+2)));
for(int i=0;i<size;i++)
System.out.printf(String.format("%"+((""+size).length())+"d",i+1)+") %-
30s"+m[i]+"\n",n[i]);
System.out.println("-".repeat(50));
}
}
class Lowest extends Record
{
Lowest(int c)
{
super(c);
}
void display()
{
super.display();
int l=m[0];//to store lowest marks
for(int i=1;i<size;i++)
{
if(l>m[i])//comparing with each mark
l=m[i];
}
System.out.println("STUDENTS WITH LOWEST MARK");
165
System.out.println(" ".repeat(5)+"NAME OF STUDENT"+"
".repeat(8)+"MARKS");
System.out.println("-".repeat(26));
for(int i=0;i<size;i++)
{
if(m[i]==l)//if marks is lowest
System.out.printf("%-30s"+m[i]+"\n",n[i]);
}

}
}
class RecordMain
{
public static void main(String args[])
{
System.out.print("ENTER TOTAL NUMBER OF STUDENTS: ");
int s=new java.util.Scanner(System.in).nextInt();
if(s<=0)
{
System.out.println("INVALID INPUT");
return;
}
Lowest ob = new Lowest(s);
ob.readarray();
ob.display();
}

166
}

OUTPUT :-

167
VARIABLE LISTING :-

Record

Variable Name Data Type Scope Purpose/Description

n String[] Record Array to store names of the students

m int[] Record Array to store marks of the students

size int Record Total number of student records

Loop variable to access array


i int for loop
elements

Lowest

Variable Name Data Type Scope Purpose/Description

l int display() To store lowest marks

i int for loop Loop variable to control display()

RecordMain

Variable Name Data Type Scope Purpose/Description

s int main() Number of students entered by user

Object of class Lowest used to


ob Lowest main()
invoke methods

168

You might also like