0% found this document useful (0 votes)
7 views

Computer Science Assignment

Uploaded by

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

Computer Science Assignment

Uploaded by

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

COMPUTER SCIENCE ASS

CLASS XII

PREPARED BY:
ANTAREEP GHOSH
CLASS: XII
SECTION: A
ROLL NUMBER: 23
INDEX
ASSIGNMENT NO. ASSIGNMENT DETAILS IN BRIEF PAGE NUMBER DATE TEACHER SIGNATURE

1. DATE OF DAY 2 11.04.22

2. TIME ADDITION 11 11.04.22

3. BINODD NUMBER 19 13.04.22

4. SQUARE MATRIX 27 22.04.22

5. STRING MODIFICATIONS 35 04.05.22

6. SMALLEST INTEGER 43 11.05.22

7. PARAGRAPH MODIFICATIONS 50 21.06.22

8. MIX OF STRINGS 58 27.06.22

9. FIBOPRIME NUMBERS 65 29.06.22

10. ARRANGEMENT OF MATRIX 73 12.07.22

11. BINARY TO HEXA-DECIMAL 81 19.07.22

12. ENCRYPTION 91 25.07.22

13. PRODUCT OF SERIES 101 28.07.22

14. COIN DENOMINATION 109 03.08.22

15. MATRIX SORT 115 17.08.22

16. QUEUE 125 18.08.22

17. STACK 133 14.09.22

18. EMPLOYEE 141 15.09.22

19. ENCRYPT 150 21.09.22

20. LOGIN LOGOUT 158 23.09.22

21. REV-PRINT 169 27.09.22

22. PRIME ADAM NUMBER 177 09.11.22

23. COMMON WORDS 185 16.11.22

24. FASCINATING NUMBER 193 21.11.22

25. LINKED LIST 200 05.11.22

1|Page
ASSIGNMENT 1
DATE: 11.04.22

A. PROGRAM DESCRIPTION: ---


Write a program to accept a date in format dd/mm/yyyy and accept the name of the

day on 1st January of the corresponding year. Find the day for the given date. Do

validation check where required. ex: input: date:5/7/2001

day on 1st

January: Monday

output: day on

5/7/2001:

Thursday

2|Page
B. ALGORITHM: --
A class is designed with the name Date.
Method calc():
STEP 1: Start
STEP 2: Declare array monthDays and store 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
STEP 3: Declare array dayNames and store "MONDAY", "TUESDAY", "WEDNESDAY",
"THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"
STEP 4: Take input from user in dateStr
STEP 5: Count the number of tokens followed by ‘/’ and store in tokenCount
STEP 6: If tokenCount is less than equal to 0 or greater than 3 then give an error message and
return the control
STEP 7: Separate the tokens accordingly in variables day, month and year respectively
STEP 8: Check whether year is leap or not by calling isLeap method using year as parameter
STEP 9: If year is leap then make monthDays[1]=29
STEP 10: If month less than 1 or greater than 12 give error message
STEP 11: If day less than 1 or greater than monthDays[month-1] give error message
STEP 12 : Accept day of 1st January from user in variable startDayName
STEP 13: Declare variable startDayIdx and assign -1
STEP 14: Start a loop with variable i from 0 to less that dayNames.length with increment value
+1
STEP 15: Within loop, If dayNames[i] is equal to startDayName then startDayIdx=i and goto
STEP 16
STEP 16: If startDayIdx=-1, give error message and return the control
STEP 17: Declare variable tDays and assign 0
STEP 18: Start a loop with variable i=0 to less than month-1 and increment value +1
STEP 19: Within loop, tDays=tDay+monthDays[i]
STEP 20: tdays=tdays+day
STEP 21: Declare variable currDayIdx and assign tdays mod 7 + startDayIdx-1
3|Page
STEP 22: If currDayIdx>=7 then make currDayIdx=currDayIdx-7
STEP 23: Print dateStr and dayNames[currDayIdx] with proper orientation
STEP 24: End
Method isLeap() with parameter y:
STEP 1: Start
STEP 2: Declare variable ret and assign false to it
STEP 3: If y mod 400 = 0 then ret=true and go to STEP 6
STEP 4: If y mod 100=0 then ret=false and go to STEP 6
STEP 5: If y mod 4=0 then ret=true and go to STEP 6
STEP 6: ret=false
STEP 7: Return ret
STEP 8: End
A class is designed with the name Date_main
Method main() with parameter String args[]:
STEP 1: Start
STEP 2: Create an object ob of Date class
STEP 3: Call calc() using ob
STEP 4: End

4|Page
C. SOURCE CODE: --
//Program 1 : To find day of a given date with respect to day of 1st January of corresponding
year
import java.util.*;
class Date{
void calc() { //method to calculate day of date
//to store the dates and day names
int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String dayNames[] = {"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY",
"FRIDAY", "SATURDAY", "SUNDAY"};
Scanner in = new Scanner(System.in);
System.out.print("Enter Date(dd/mm/yyyy): ");
String dateStr = in.nextLine();
StringTokenizer st = new StringTokenizer(dateStr, "/");
int tokenCount = st.countTokens();
// to validify the input date
if (tokenCount <= 0 || tokenCount > 3) {
System.out.println("Invalid Date");
return;
}
int day = Integer.parseInt(st.nextToken());
int month = Integer.parseInt(st.nextToken());
int year = Integer.parseInt(st.nextToken());
//leap year check
if (isLeap(year)) {
5|Page
monthDays[1] = 29;
}
//month validity check
if (month < 1 || month > 12) {
System.out.println("Invalid Month");
return;
}
//day validity check
if (day < 1 || day > monthDays[month - 1]) {
System.out.println("Invalid Day");
return;
}
//to accept 1st January date
System.out.print("Day on 1st January: ");
String startDayName = in.nextLine();
int startDayIdx = -1;
for (int i = 0; i < dayNames.length; i++) {
if (dayNames[i].equalsIgnoreCase(startDayName)) {
startDayIdx = i;
break;
}
}
if (startDayIdx == -1) {
System.out.println("Invalid Day Name");
return;
}

6|Page
//to count total number of days
int tDays = 0;
for (int i = 0; i < month - 1; i++) {
tDays += monthDays[i];
}
tDays += day;
int currDayIdx = tDays % 7 + startDayIdx - 1;
if (currDayIdx >= 7) {
currDayIdx -= 7;
}
System.out.println("Day on " + dateStr + " : " + dayNames[currDayIdx]);
}//end of calc()
boolean isLeap(int y) { //method to check whether year is leap or not
boolean ret = false;
if (y % 400 == 0) {
ret = true;
}
else if (y % 100 == 0) {
ret = false;
}
else if (y % 4 == 0) {
ret = true;
}
else {
ret = false;
}

7|Page
return ret;
}//end of isLeap()
}//end of class
class Date_main{
public static void main(String args[]){ //main method to create objects and call methods
Date ob=new Date();
ob.calc();
}//end of main()
}

8|Page
D. OUTPUT: --

9|Page
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
monthDays[] int calc() Days of months
dayNames[] String calc() Names of days
dateStr String calc() String for day
St StringTokenizer calc() Tokenzier
tokencount int calc() Count of token
day int calc() Day input
month int calc() Month input
year int calc() Year input
startDayName String calc() String for 1st day
startDayIdx int calc() Starting index
tdays int calc() Total Days
CurrDayIdx int calc() Current Day Index
y int isLeap() Parameter
ret boolean isLeap() Return in boolean

10 | P a g e
--------------------------------------***-----------------------------------

ASSIGNMENT 2
DATE: 11.04.22

A. PROGRAM DESCRIPTION: ---

Write a program to add two times given by the user in hour,min


and seconds. class name: TimeAdd

Data member:
hr(hour),min(minutes),sec(seconds
) member methods:

TimeAdd():
DEFAULT
constructor void

11 | P a g e
accept(): accept
time from user

TimeAdd timeAdd(TimeAdd t): add two time objects return the


final time value. void display(): display time in hour,minutes and
seconds

B. ALGORITHM: --
A class is designed with the name TimeAdd and instance variables hr, min, sec
Method TimeAdd():
STEP 1: Start
STEP 2: Assign hr=0, min=0, sec=0
STEP 3: End
Method accept():
STEP 1: Start
STEP 2: Take input from user in hr, min and sec
STEP 3: If sec>60 then sec=sec-60 and min=min+1
STEP 4: If min>60 then min=min-60 and hr=hr+1

12 | P a g e
STEP 5: End
Method timeAdd(TimeAdd t):
STEP 1: Start
STEP 2: Create an object of TimeAdd class
STEP 3: Equalize the hr of ob object to sum of hr of current object and hr of t object
STEP 4: Equalize the min of ob object to sum of min of current object and min of t object
STEP 5: Equalize the sec of ob object to sum of sec of current object and sec of t object
STEP 6: If sec of object ob greater than equal to 60 then make sec of object ob=sec of object ob-
60 and min of ob object=min of ob object + 1
STEP 7: If min of object ob greater than equal to 60 then make min of object ob=min of object
ob-60 and hr of ob object=hr of ob object + 1
STEP 8: Return ob
STEP 9: End
Method display():
STEP 1: Start
STEP 2: Display hr, min and sec with proper message
STEP 3: End
A class is designed with name TimeAdd_main
Method main() with parameter String args[]:
STEP 1: Start
STEP 2: Create and object ob1 of class TimeAdd and call accept() using ob1
STEP 3: Create and object ob2 of class TimeAdd and call accept() using ob2
STEP 4: Create and object ob3 of class TimeAdd and call timeAdd of object ob1 with ob2 as
parameter
STEP 5: Call display() using ob3
STEP 6: End

13 | P a g e
C. SOURCE CODE: --
//Program 2 : To add two times in hours, minutes and seconds
import java.util.*;
class TimeAdd{
private int hr;
private int min;
private int sec;
TimeAdd(){ //default constructor
hr=0;
min=0;
sec=0;

14 | P a g e
}//end of TimeAdd()
void accept(){ //to accept the time from user
Scanner sc=new Scanner(System.in);
System.out.println("Enter hour : ");
hr=sc.nextInt();
System.out.println("Enter minutes : ");
min=sc.nextInt();
System.out.println("Enter second : ");
sec=sc.nextInt();
//to check whether minutes and seconds are within 60 or not
if(sec>60){
sec=sec-60;
min=min+1;
}
if(min>60){
min=min-60;
hr=hr+1;
}
}//end of accept()
TimeAdd timeAdd(TimeAdd t){
//to take time as objects
TimeAdd ob=new TimeAdd();
ob.hr=this.hr+t.hr;
ob.min=this.min+t.min;
ob.sec=this.sec+t.sec;
//to check whether minutes and seconds exceed 60 or not

15 | P a g e
if(ob.sec>=60){
ob.sec=ob.sec-60;
ob.min=ob.min+1;
}
if(ob.min>=60){
ob.min=ob.min-60;
ob.hr=ob.hr+1;
}
return ob;
}//end of timeAdd()
void display(){ //to display hour, minutes and seconds
System.out.println("Hour="+hr);
System.out.println("Minutes="+min);
System.out.println("Seconds="+sec);
}//end of display()
}//end of class
class TimeAdd_main{
public static void main(String args[]){//main method to create objects and call methods
TimeAdd ob1=new TimeAdd();
ob1.accept();
TimeAdd ob2=new TimeAdd();
ob2.accept();
TimeAdd ob3=ob1.timeAdd(ob2);
ob3.display();
}//end of main()
}

16 | P a g e
D. OUTPUT: --

17 | P a g e
E. VARIABLE LISTING: --
18 | P a g e
NAME DATATYPE SCOPE PURPOSE
hr int class Variable for hour
min int class Variable for minute
sec int class Variable for seconds
t TimeAdd timeAdd() Reference object

--------------------------------------***-----------------------------------

19 | P a g e
ASSIGNMENT 3
DATE: 13.04.22

A. PROGRAM DESCRIPTION: ---


Write a program to take lower and upper range from the user and print all the binodd numbers
within that range. (A binodd number is a number whose binary equivalent have all the 1s present
in the odd position of the binary number considering from MSB to LSB) Example: 17 is a
binodd number as its binary equivalent is 10001 where 1s are in the position 1st and 5th position
of the binary number which are odd position of the number.

20 | P a g e
B. ALGORITHM: --
A class is designed with the name Binodd
Method accept():
STEP 1: Start
STEP 2: Declare variables u, l, c and assign 0 to all
STEP 3: Start an exit control loop with condition to repeat if u<=0 or l<0 or u<l
STEP 4: Within the loop accept values of u and l from user using appropriate message
STEP 5: Start a loop with variable i from l to u with increment value +1
STEP 6: Within loop declare a variable bin and assign it the value by calling Binary method
using i as parameter
STEP 7: Within loop, if by calling isBinodd with bin as parameter we get true then print i and
increase c by +1
STEP 8: Outside loop, if c=0 then display “No Binodd Numbers Found”
STEP 9: End
Method Binary() with parameter k:
STEP 1: Start
STEP 2: Declare variables remainder, i and assign 0 and 1 respectively and also binaryNum and
assign 0 to it
STEP 3: Start a loop with condition to iterate if k not equal to 0
STEP 4: Within loop, remainder = k mod 2 and k=k/2 and binaryNum=binaryNum+remainder*i
and i=i*10
STEP 5: Outside loop, return binaryNum
STEP 6: End
Method isBinodd() with parameter num:
STEP 1: Start
STEP 2: Declare variables copy and digit and store num and 0 respectively
STEP 3: Start a loop with condition to iterate if copy>0
STEP 4: Within loop, digit=digit+1 and copy=copy/10
21 | P a g e
STEP 5: Outside loop, declare and assign k=0
STEP 6: Start a loop with variable i=0 to less than digit and increment i by 1 in every iteration
STEP 7: Within loop, k=digit-i and declare and assign j=num mod 10 and num=num/10
STEP 8: Within loop, if k mod 2=0 and j=1 then return false
STEP 9: Outside loop, return true
STEP 10: End
A class is designed with the name Binodd_main
Method main() with parameter String args[]:
STEP 1: Start
STEP 2: Create an object ob of Binodd class
STEP 3: Call accept method using ob
STEP 4: End

22 | P a g e
C. SOURCE CODE: --
//Program 3 : To display all Binodd numbers within a range
import java.util.*;
class Binodd{
void accept(){// method to accept input from user
Scanner sc=new Scanner(System.in);
int u,l=0,c=0;
//to accept and check for upper and lower limit
do{
System.out.println("Enter upper limit");
u=sc.nextInt();
System.out.println("Enter lower limit");
l=sc.nextInt();
}while(u<=0 || l<0 || u<l);
System.out.print("Binodd numbers within "+l+" and "+u+": ");
//to check and display binodd numbers within the given range
for(int i=l; i<=u; i++){
int bin=Binary(i);
if(isBinodd(bin)){
System.out.println(i+" ");
c++;
}
}
if(c==0)
System.out.println("No Binodd numbers found");
23 | P a g e
}//end of accept()
int Binary(int k){
int remainder, i = 1;
int binaryNum=0;
while (k != 0){
remainder = k % 2;
k /= 2;
binaryNum=binaryNum+remainder*i;
i *= 10;
}
return binaryNum;
}//end of Binary()
boolean isBinodd(int num){
int copy=num; int digit=0;
while(copy>0){
digit++;
copy/=10;
}
int k=0;
for(int i=0; i<digit; i++){
k=digit-i;
int j=num%10;
num/=10;
if(k%2==0 && j==1)
return false;
}

24 | P a g e
return true;
}//end of isBinodd()
}//end of class
class Binodd_main{
public static void main(String args[]){
Binodd ob=new Binodd();
ob.accept();
}//end of main()
}

25 | P a g e
D. OUTPUT: --

26 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
u int accept() Upper Limit
l int accept() Lower Limit
c int accept() Counter
i int for loop Loop control
k int Binary() Parameter
remainder int Binary() Remainder
num int isBinodd() Parameter
copy int isBinodd() Copy of num
digit int isBinodd() Number of digits

--------------------------------------***-----------------------------------

27 | P a g e
ASSIGNMENT 4
DATE: 22.04.22

A. PROGRAM DESCRIPTION: ---


Write a program to accept a square matrix CIR[][] of order MXM where M is no. of rows and no. of
columns. Value of M varies from 2<= M <= 10. Accept alphabet character values in UPPERCASE as
input. Display appropriate message for invalid input. Perform following tasks:

i) Display original matrix.

ii) Find the sum of Unicode values of the elements of four corners of the matrix.

Rotate the matrix 90 degrees anti-clockwise and display it

Example: INPUT : M=3 OUTPUT : ORIGINAL MATRIX :


AFD AFD
DBT DBT
CAA CAA
SUM=265

28 | P a g e
FINAL MATRIX :
DTA
FBA
ADC

B. ALGORITHM: --
A class is declared with the name SquareMatrix and instance variable CIR[][]
Method accept():
STEP 1: Start
STEP 2: Declare variable M
STEP 3: Take input of M from user and check validity using loop, condition is M should be
between 2 and 10
STEP 4: Assign dimensions of CIR as M rows and M columns
STEP 5: Accept the inputs of capital alphabets as elements of matrix CIR using loop
STEP 6: If input is not between A and Z then give error message and exit program
STEP 7: Print the original matrix with proper orientation using loop
STEP 8: Print the sum of corner elements by taking sum of CIR[0][0], CIR[0][M-1], CIR[M-1]
[0], CIR[M-1][M-1]
STEP 9: Call Rotate with CIR parameter
STEP 10: End
Method Rotate() with parameter a[][]:
29 | P a g e
STEP 1: Start
STEP 2: Start a loop from 0 to length of a and increment by 1 and within that, start another loop
from i to length of a and increment it by +1 also
STEP 3: Within both loop, declare and assign temp=a[i][j], a[i][j]=a[j][i] and a[j][i]=temp
STEP 4: Outside both loops, start another loop from 0 to length of a and increment by 1
STEP 5: Within it, declare and assign low and high as 0 and length of a respectively
STEP 6: Start another loop inside, with condition to iterate if low<high
STEP 7: Within, temp=a[low][i] and a[low][i]=a[high][i] and a[high][i]=temp and low=low+1
and high=high-1
STEP 8: Print final matrix using loop and proper orientation
STEP 9: End
A class with name SquareMatrix_main is designed
STEP 1: Start
STEP 2: Create and object ob of class SquareMatrix
STEP 3: Call accept() using ob
STEP 4: End

30 | P a g e
C. SOURCE CODE: --
//Program 4 : Alphabet Matrix
import java.util.*;
class SquareMatrix{
private char CIR[][];
void accept(){//method to accept data from user
Scanner sc=new Scanner(System.in);
int M;
do{
System.out.println("Enter row or column size of matrix");
M=sc.nextInt();
}while(M<2 || M>10);
CIR=new char[M][M];
System.out.println("Enter alphabets in capital letters as elements");
for(int i=0; i<M; i++){
31 | P a g e
for(int j=0; j<M; j++){
CIR[i][j]=sc.next().charAt(0);
if((int)CIR[i][j]<65 || (int)CIR[i][j]>97){
System.out.println("INVALID INPUT");
System.exit(0);
}
}
}
System.out.println("Original Matrix: ");
for(int i=0; i<M; i++){
for(int j=0; j<M; j++){
System.out.print(CIR[i][j]+" ");
}
System.out.println();
}
//printing sum of corner elements
System.out.println("SUM="+((int)CIR[0][0] + (int)CIR[0][M - 1] +(int)CIR[M - 1][0] +
(int)CIR[M - 1][M - 1]));
Rotate(CIR);
}//end of accept()

void Rotate(char a[][]){//method to rotate matrix 90 degrees anti-clockwise


for(int i=0;i<a.length;i++)
{
for(int j=i;j<a.length;j++)
{
char temp = a[i][j];
32 | P a g e
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
for(int i=0;i<a.length;i++)
{
//logic to swap columns
int low = 0;
int high = a.length-1;
while(low < high)
{
char temp = a[low][i];
a[low][i] = a[high][i];
a[high][i] = temp;
low++;
high--;
}
}
System.out.println("Final MAtrix :");
for(int i=0; i<a.length; i++){
for(int j=0; j<a.length; j++){
System.out.print(CIR[i][j]+" ");
}
System.out.println();
}
}//end of Rotate()

33 | P a g e
}//end of class
class SquareMatrix_main{
public static void main(String args[]){//main method to create objects and call methods
SquareMatrix ob=new SquareMatrix();
ob.accept();
}//end of main()
}

D. OUTPUT: --

34 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
CIR[][] char class Matrix
M int accept() Dimensions
i int for loop Loop Control
j int for loop Loop Control
a[][] char Rotate() Parameter
low int Rotate() Lower index
high int Rotate() Higher Index

--------------------------------------***-----------------------------------

35 | P a g e
ASSIGNMENT 5
DATE: 04.05.22

A. PROGRAM DESCRIPTION: ---


Design a class StringModify in your default package that will contain two methods that will work
on string values. The method definitions of the class is given below:

i) StringModify(String st): parameterized constructor

ii)String insertStringAt(String w,int pos): to insert string w at valid position pos and
returns final sentence without changing any other data.

iii) String deleteCharAt(char w,int pos): to delete character w from valid position
pos and returns final sentence without changing any other data.

Write a possible menu in main method to implement the above logic for any random sentence by
calling methods. DO POSSIBLE CHECKING WHERE REQUIRED.
36 | P a g e
B. ALGORITHM: --
A class is designed with the name StringModify and instance variable St
Method StringModify() with parameter St:
STEP 1: Start
STEP 2: Equalize the current object of St to St\
STEP 3: End
Method insertStringAt() with parameters w and pos:
STEP 1: Start
STEP 2: Declare variables temp1 and temp2
STEP 3: Start a loop from i= 0 to pos-1 and increment by +1
STEP 4: Within loop, temp1=temp1+character of St at position i
STEP 5: Start a loop from i= pos-1 to less than length of St and increment by +1
STEP 6: Within loop, temp2=temp2+character of St at position i
STEP 7: St=temp1+w+temp2
37 | P a g e
STEP 8: Return St
STEP 9: End
Method deleteCharAt() with parameters w and pos:
STEP 1: Start
STEP 2: Declare variables temp1 and temp2
STEP 3: Start a loop from i= 0 to less than pos-1 and increment by +1
STEP 4: Within loop, temp1=temp1+character of St at position i
STEP 5: Start a loop from i= pos-1 to less than length of St and increment by +1
STEP 6: Within loop, temp2=temp2+character of St at position i
STEP 7: St=temp1+temp2
STEP 8: Return St
STEP 9: End
A class with name StringModify_main is designed
Method main() with parameters String args[]:
STEP 1: Start
STEP 2: Take input of Str from user
STEP 3: Create object ob of class StringModify with parameter Str
STEP 4: Take choice from user in n
STEP 5: For 1, take input of string to add and position to add and call insertStringAt with ob
object
STEP 6: For 2, take input of character to delete and position to delete and call deleteCharAt with
ob object
STEP 7: For any other choice give error message “Invalid Input”
STEP 8: End

38 | P a g e
C. SOURCE CODE: --
//Program 5 : Modifications in Strings
import java.util.*;
class StringModify{
String St;
StringModify(String St){//parameterized constructor
this.St=St;
}//end of StringModify()
String insertStringAt(String w, int pos){//method to add string at given position
String temp1="";
String temp2="";
for(int i=0; i<pos-1; i++){
temp1=temp1+St.charAt(i);

39 | P a g e
}
for(int i=pos-1; i<St.length(); i++){
temp2=temp2+St.charAt(i);
}
St=temp1+w+temp2;
return St;
}//end of insertStringAt()
String deleteCharAt(char w, int pos){//method to delete character at given position
String temp1="";
String temp2="";
for(int i=0; i<pos-1; i++){
temp1=temp1+St.charAt(i);
}
for(int i=pos; i<St.length(); i++){
temp2=temp2+St.charAt(i);
}
St=temp1+temp2;
return St;
}//end of insertStringAt()
}//end of class
import java.util.*;
class StringModify_main{
public static void main(String args[]){//main method to create object and call methods
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String Str=sc.nextLine();

40 | P a g e
StringModify ob=new StringModify(Str);
System.out.println("Enter 1 for inserting string or 2 for deleting character");
int n=sc.nextInt();
switch(n){
case 1: System.out.println("Enter string to insert");
String insert=new Scanner(System.in).nextLine();
System.out.println("Enter position to insert");
int position1=sc.nextInt();
System.out.println("New String="+ob.insertStringAt(insert, position1));
break;
case 2: System.out.println("Enter character to delete");
char delete=sc.next().charAt(0);
System.out.println("Enter position to delete");
int position2=sc.nextInt();
System.out.println("New String="+ob.deleteCharAt(delete, position2));
break;
default : System.out.println("Invalid Input");
}
}//end of main()
}

41 | P a g e
D. OUTPUT: --

42 | P a g e
E. VARIABLE LISTING: --
43 | P a g e
NAME DATATYPE SCOPE PURPOSE
St String class Sentence
w String insertStringAt() Word input
pos int insertStringAt() position
temp1 String insertStringAt() temporary string
temp 2 String insertStringAt() temporary string
i int for loop loop control
w char deleteCharAt character to delete

--------------------------------------***-----------------------------------

ASSIGNMENT 6
DATE: 11.05.22

44 | P a g e
A. PROGRAM DESCRIPTION: ---

B. ALGORITHM: --
A class is designed with the name SmallestInteger

45 | P a g e
Method accept():
STEP 1: Start
STEP 2: Take input of M and N from user and if M<100 or M>10000 or N>=100 then give error
message and terminate program
STEP 3: Start a loop from i=M with increment value 1
STEP 4: Inside loop, if the value we get after calling SumDigit using i is equal to N then print i
and Digit of i
STEP 5: End
Method SumDigit() with parameter num:
STEP 1: Start
STEP 2: Declare variable sum and assign 0
STEP 3: Start a loop with condition num>0
STEP 4: Within loop, sum=sum+num mod 10 and num=num/10
STEP 5: Outside, return sum
STEP 6: End
Method Digit() with parameter k:
STEP 1: Start
STEP 2: Declare variable dig=0
STEP 3: Start a loop with condition k>0
STEP 4: Within loop, dig=dig+1 and k=k/10
STEP 5: Return dig
STEP 6: End

A class with name SmallestInteger_main is designed


Method main() with parameters String args[]:

46 | P a g e
STEP 1: Start
STEP 2: Create object ob of class SmallestInteger and call accept using ob
STEP 3: End

C. SOURCE CODE: --
//Program 6 : Program to find smallest integer to add up digits and get sum

47 | P a g e
import java.util.*;
class SmallestInteger{
void accept(){//method to accept input from user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of M");
int M=sc.nextInt();
System.out.println("Enter the value of N");
int N=sc.nextInt();
if(M<100 || M>10000 || N>=100){
System.out.println("INVALID INPUT");
System.exit(0);
}
//to print the smallest number greater than M whose sum of digits is equal to N
for(int i=M; ;i++){
if(SumDigit(i)==N){
System.out.println("The required number="+i);
System.out.println("Total number of digits="+Digit(i));
break;
}
}
}//end of accept()
int SumDigit(int num){//method to calculate sum of digits
int sum=0;
while(num>0){
sum=sum+num%10;
num/=10;

48 | P a g e
}
return sum;
}//end of SumDigit()
int Digit(int k){//method to calculate number of digits
int dig=0;
while(k>0){
dig++;
k/=10;
}
return dig;
}//end of Digit()
}//end of class
class SmallestInteger_main{
public static void main(String args[]){//method to create object and call methods
SmallestInteger ob=new SmallestInteger();
ob.accept();
}//end of main
}

D. OUTPUT: --

49 | P a g e
E. VARIABLE LISTING: --
50 | P a g e
NAME DATATYPE SCOPE PURPOSE
M int accept() Value of M
N int accept() Value of N
num int SumDigit() Parameter
sum int SumDigit() Sum of digits
k int Digit() Parameter
dig int Digit() Number of digits

--------------------------------------***-----------------------------------

ASSIGNMENT 7
51 | P a g e
DATE: 21.06.22

A. PROGRAM DESCRIPTION: ---

B. ALGORITHM: --
52 | P a g e
A class is designed with the name Paragraph
Method accept():
STEP 1: Accept St from user
STEP 2: Convert St to upper case
STEP 3: If it returns true by calling isValid of St then call SepCom of St
STEP 4: End
Method isValid() with parameter S:
STEP 1: Start
STEP 2: Create a string tokenizer t for S with respect to “.?!”
STEP 3: C=Number of tokens
STEP 4: If c not equal to 2, display “Invalid Input” and terminate program
STEP 5: Return true
STEP 6: End
Method SepCom() with parameter S:
STEP 1: Start
STEP 2: Declare S1, S2 and pos
STEP 3: Start a loop from i=0 to i<length of S and increment i by 1
STEP 4: If character at i of S not equal to ‘.’ or ‘!’ or ‘?’ then S1=S1+character at i of S
STEP 5: Else, pos=i, start loop j=i+1 to j<length of S-1 and increment j by 1 and
S2=S2+character at j of S and break from block
STEP 6: Print S1+character at pos of S
STEP 7: Print S2+character at length of S-1 of S
STEP 8: Declare arr1[] by splitting S1 with “ ” in between
STEP 9: Declare arr2[] by splitting S2 with “ ” in between and k=0
STEP 10: Start a loop from i=0 to i<length of arr1 and increment by 1
STEP 11: Declare c=1 and word= “ ”
STEP 12: Start a loop from j=0 to j<length of arr2, increment by 1
53 | P a g e
STEP 13: If arr2[j] equal to arr1[i] then c=c+1 and word=arr2[j]
STEP 14: If c>1 then k=k+1 and call displayfreq using word, c, k
STEP 15: If k=0 then print “NO COMMON WORDS”
STEP 16: End
Method displayfreq() with parameters word, c, k:
STEP 1: Start
STEP 2: Print word and c using proper orientation
STEP 3: End
A class is designed with name Paragraph_main
Method main() with parameters String args[]:
STEP 1: Start
STEP 2: Create an object ob of class Paragraph
STEP 3: Call accept using ob
STEP 4: End

C. SOURCE CODE: --
54 | P a g e
//Program 7 : Working on strings of paragraphs
import java.util.*;
class Paragraph{
void accept(){//method to accept input from the user
Scanner sc=new Scanner(System.in);
System.out.println("Enter a paragraph with two sentences only and ending with '.' or '!' or '?'
and all in capitals");
String St=sc.nextLine();
St=St.toUpperCase();
if(isValid(St)){
SepCom(St);
}
}//end of accept()
boolean isValid(String S){//method to check the validity of the string input
StringTokenizer t=new StringTokenizer(S,".?!");
int c=t.countTokens();
if(c!=2){
System.out.println("Invalid Input");
System.exit(0);
}
return true;
}

void SepCom(String S){//method to separate two sentences and find common words
String S1="";
String S2="";
int pos=0;
55 | P a g e
for(int i=0;i<S.length();i++){
if(S.charAt(i)!='.' && S.charAt(i)!='!' && S.charAt(i)!='?'){
S1=S1+S.charAt(i);
}
else{
pos=i;
for(int j=i+1; j<S.length()-1; j++){
S2=S2+S.charAt(j);
}
break;
}
}
System.out.println(S1+S.charAt(pos));
System.out.println(S2+S.charAt(S.length()-1));
String arr1[] =S1.split(" ");
String arr2[] =S2.split(" ");
int k=0;
for(int i=0; i<arr1.length; i++){
int c=1;String word="";
for(int j=0; j<arr2.length; j++){
if(arr2[j].compareTo(arr1[i])==0){
c++;
word=arr2[j];
}
}
if(c>1){

56 | P a g e
k++;
displayfreq(word,c,k);
}
}
if(k==0)
System.out.println("NO COMMON WORDS");
}//end of SepCom()
void displayfreq(String word, int c, int k){//method to display
if(k==1){
System.out.println("COMMON WORD"+"
"+"FREQUENCY");
System.out.println(word+" "+c);
}
else{
System.out.println(word+" "+c);
}
}//end of displayfreq()
}//end of class
class Paragraph_main{
public static void main(String args[]){//method to create object and call ,ethods
Paragraph ob=new Paragraph();
ob.accept();
}//end of main
}

57 | P a g e
D. OUTPUT: --

58 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
St String accept() String input
S String isValid() Parameter
t StringTokenizer isValid() Tokenizer
c int isValid() Counter
S String SepCom() Parameter
pos int SepCom() Positional value
i int for loop Loop Control
arr1[] String SepCom() Array of Strings
arr2[] String SepCom() Array of Strings
k int SepCom() Frequency
c int for loop Counter
word String for loop Temporary word

--------------------------------------***-----------------------------------

59 | P a g e
ASSIGNMENT 8
DATE: 27.06.22

A. PROGRAM DESCRIPTION: ---

60 | P a g e
B. ALGORITHM: --
A class is designed with the name Mix and instance variables wrd and len
Method Mix():
STEP 1: Start
STEP 2: wrd= “”
STEP 3: len=0
STEP 4: End
Method feedword():
STEP 1: Start
STEP 2: Take input from user for wrd and convert to upper case
STEP 3: len=length of wrd
STEP 4: End
Method mix_word() with parameters P and Q:
STEP 1: Start
STEP 2: Declare i=0 and j=0
STEP 3: Start loop with condition of true
STEP 4: Within loop, if i<length of P and j<length of Q then go to STEP 5 else break from if
statement
STEP 5: Add and equalize current object of wrd to character at i of P object of wrd
STEP 6: Add and equalize current object of wrd to character at j of Q object of wrd
STEP 7: Increase i and j by 1
STEP 8: Outside loop, if i<length of P then current object of wrd is added and equalized to P
object of wrd for the substring of i
STEP 9: Outside loop, if j<length of Q then current object of wrd is added and equalized to Q
object of wrd for the substring of i
STEP 10: End

61 | P a g e
Method display():
STEP 1: Start
STEP 2: Print wrd
STEP 3: End
A class is designed with name Mix_main
Method main() with parameter String args[]:
STEP 1: Start
STEP 2: Create an object ob of Mix class and call feedword with ob
STEP 3: Create an object ob1 of Mix class and call feedword with ob1
STEP 4: Create an object ob 2 of Mix class and call mix_word with ob2 as object and ob and ob1
as parameters
STEP 5: Call display using ob2
STEP 6: End

62 | P a g e
C. SOURCE CODE: --
//Program 8: Alternate letters of two words
import java .util.*;
class Mix{
private String wrd;
private int len;
Mix(){//default constructor
wrd="";
len=0;
}//end of Mix()

void feedword(){//to take word from user


System.out.println("Enter a word in uppercase");
wrd=new Scanner(System.in).nextLine();
wrd.toUpperCase();
len=wrd.length();
}//end of feedword

void mix_word(Mix P, Mix Q){//to mix the letters of two words


int i=0,j=0;
while(true){
if(i<P.len && j<Q.len){
this.wrd+=P.wrd.charAt(i);
this.wrd+=Q.wrd.charAt(j);
}
else

63 | P a g e
break;
i++;
j++;
}
if(i<P.len)
this.wrd+=P.wrd.substring(i);
if(j<Q.len)
this.wrd+=Q.wrd.substring(i);
}//end of mix_word

void display(){//method to display the word


System.out.println(wrd);
}//end of display
}//end of class
class Mix_main{
public static void main(String args[]){//main method to create objects and call methods
Mix ob=new Mix();
ob.feedword();
Mix ob1=new Mix();
ob1.feedword();
Mix ob2=new Mix();
ob2.mix_word(ob,ob1);
ob2.display();
}//end of main()
}

64 | P a g e
D. OUTPUT: --

65 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
wrd String class Word from user
len int class Length of word
P Mix mix_word Object 1
Q Mix mix_word Object 2
i int for loop Loop Control
j int for loop Loop Control

--------------------------------------***-----------------------------------

66 | P a g e
ASSIGNMENT 9
DATE: 29.06.22

A. PROGRAM DESCRIPTION: ---


Design a class FiboPrime which will display all the the Fibonacci numbers upto n terms which
have atleast one prime digit in the number. For example 2,3,5,13,21 are some of the examples of
Fibonacci numbers having atleast one prime digit in it.
Class name: FiboPrime
Date Members :
n: number of terms
Method:
FiboPrime(int): constructor
int fibo(int n): returns nth Fibonacci number
void displayFiboPrimes(): Display all the Fibonacci numbers upto n terms which have atleast
one digit s as prime
boolean isPrime(int p): returns true or false if p is either prime or not.
You can add method(s) if required.

67 | P a g e
B. ALGORITHM: --
A class is designed with the name FiboPrime and instance variable n
Method FiboPrime() with parameter n:
STEP 1: Start
STEP 2: Equalize the current object of n with n
STEP 3: End
Method fibo() with parameter n:
STEP 1: Start
STEP 2: Declare t1=0,t2=1,nextTerm=0 and i=0
STEP 3: If n=0 or n=1 then return n else nextTerm=t1+t2
STEP 4: Start a loop from i=3 to i<=n and increment i by 1
STEP 5: Within loop, t1=t2 and t2=nextTerm and nextTerm=t1+t2
STEP 6: Return t2
STEP 7: End
Method displayFiboPrimes():
STEP 1: Start
STEP 2: Start a loop from i=1 and i<=n and increment i by 1
STEP 3: Within it, declare k as value by calling fibo using i and c=0
STEP 4: Within it, start a loop with condition k>0
STEP 5: Within it, if k mod 10 is true when isPrime is called, print value by calling fibo using i
and break out from if statement
STEP 6: Within it, k=k/10
STEP 7: End
Method isPrime() with parameter p:
STEP 1: Start
STEP 2: if p=0 or p=1 return false
STEP 3: Declare c=0
68 | P a g e
STEP 4: Start a loop from i=2 to i<p and increment i by 1
STEP 5: Within it, if P mod i =0, c=c+1
STEP 6: Outside, if c not equal to 0 then return false
STEP 7: Return true
STEP 8: End
A class is designed with the name FiboPrime_main
Method main() with parameter String args[]:
STEP 1: Start
STEP 2: Accept the value of n from user
STEP 3: Create an object ob of FiboPrime class with n as parameter
STEP 4: End

69 | P a g e
C. SOURCE CODE: --
//Program 9: Fibonacci numbers with at least one prime digit
import java.util.*;
class FiboPrime{
private int n;
FiboPrime(int n){//parameterized constructor
this.n=n;
}//end of FiboPrime
int fibo(int n){//to return nth fibonacci number
int t1 = 0, t2 = 1, nextTerm = 0, i;
if(n == 0 || n == 1)
return n;
else
nextTerm = t1 + t2;
for (i = 3; i <= n; ++i)
{
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return t2;
}//end of fibo()
void displayFiboPrimes(){//to display fibonacci numbers with one prime digit
for(int i=1; i<=n; i++){
int k=fibo(i);
int c=0;

70 | P a g e
while(k>0){
if(isPrime(k%10)){
System.out.print(fibo(i)+" ");
break;
}
k/=10;
}
}
}//end of displayFiboPrimes()
boolean isPrime(int p){//method to check whether prime or not
if(p==0 || p==1)
return false;
int c=0;
for(int i=2; i<p; i++){
if(p%i==0)
c++;
}
if(c!=0)
return false;
return true;
}//end of isPrime()
}//end of class
import java.util.*;
class FiboPrime_main{
public static void main(String args[]){//main method to create object and call methods
Scanner sc=new Scanner(System.in);

71 | P a g e
System.out.println("Enter the value of n");
int n=sc.nextInt();
FiboPrime ob=new FiboPrime(n);
ob.displayFiboPrimes();
}//end of main
}

72 | P a g e
D. OUTPUT: --

73 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
n int class nth term of series
t1 int fibo() 1st term
t2 int fibo() 2nd term
nextTerm int fibo() 3rd term
i int fibo() Loop Control
k int for loop Stores fibonacci
c int for loop Counter
p int isPrime() Parameter

--------------------------------------***-----------------------------------

74 | P a g e
ASSIGNMENT 10
DATE: 12.07.22

A. PROGRAM DESCRIPTION: ---


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. Perform the following tasks:

a) Display original matrix


b) Sort each odd row of the matrix in descending order using bubble sort algorithm and each even row
of the matrix in ascending order using selection sort algorithm
c) Display the final updated matrix.

75 | P a g e
B. ALGORITHM: --
A class is designed with the name MatrixOrder
Method accept():
STEP 1: Start
STEP 2: Declare and take input from user for values of M and N
STEP 3: If M<=2 or M>=10 or N<=2 or N>=10 then go to STEP 2
STEP 4: Create matrix using 2d array A[][] of dimensions M and N
STEP 5: Accept values of elements of A[][] using loop
STEP 6: Print original matrix using loop
STEP 7: Start a loop from i=0 to i<M and increment i by 1
STEP 8: Within, declare arr[] of size N
STEP 9: Within, declare loop from j=0 to j<N and increment j by 1
STEP 10: Within, arr[j]=A[i][j]
STEP 11: Outside, if i mod 2=0 then call sortdesc using arr else call sortasc using arr
STEP 12: End
Method sortasc() with parameter z[]:
STEP 1: START
STEP 2: Start a loop from i=0 to i<length of z-1 and increment i by 1
STEP 3: Declare min=i
STEP 4: Start a loop from j=i+1 to j<length of z and increment j by 1
STEP 5: If z[j]<z[min] then min=j
STEP 6: Declare t=z[i]
STEP 7: z[i]=z[min]
STEP 8: z[min]=t
STEP 9: Using loop print values of z
76 | P a g e
STEP 10: End
Method sortdesc() with parameter z[]:
STEP 1: Start
STEP 2: Start a loop from i=0 to i<length of z-1 and increment i by 1
STEP 3: Start a loop from j=0 to j<length of z-i-1 and increment i by 1
STEP 4: If z[j]<z[j+1], t=z[j], z[j]=z[j+1] and z[j+1]=t
STEP 5: Print values of z
STEP 6: End
A class is designed with the name MatrixOrder_main
Method main() with parameter String args[]:
STEP 1: Start
STEP 2: Create an object ob of class MatrixOrder
STEP 3: Call accept using ob
STEP 4: End

77 | P a g e
C. SOURCE CODE: --
//Program 10: TO sort the alternate rows and columns in ascending and descing order
import java.util.*;
class MatrixOrder{
void accept(){//method to accept input from user
Scanner sc=new Scanner(System.in);
int M=0;
int N=0;
do{
System.out.println("Enter number of rows");
M=sc.nextInt();
System.out.println("Enter number of columns");
N=sc.nextInt();
}while(M<=2 || M>=10 || N<=2 || N>=10);
int A[][]=new int[M][N];
System.out.println("Enter elements of matrix");
for(int i=0; i<M; i++){
for(int j=0; j<N; j++){
A[i][j]=sc.nextInt();
}
}
System.out.println("Original Matrix");
for(int i=0; i<M;i++){
for(int j=0; j<N;j++){
System.out.print(A[i][j]+" ");
78 | P a g e
}
System.out.println();
}
System.out.println("Sorted matrix");
for(int i=0; i<M; i++){
int arr[]=new int[N];
for(int j=0; j<N; j++){
arr[j]=A[i][j];
}
if(i%2==0)
sortdesc(arr);
else
sortasc(arr);
}
}//end of accept()
void sortasc(int z[]){
for(int i=0; i<z.length-1; i++){
int min=i;
for(int j=(i+1); j<z.length; j++){
if(z[j]<z[min])
min=j;
}
int t=z[i];
z[i]=z[min];
z[min]=t;
}

79 | P a g e
for(int i=0; i<z.length; i++){
System.out.print(z[i]+" ");
}
System.out.println();
}
void sortdesc(int z[]){
for(int i=0; i<(z.length-1); i++){
for(int j=0; j<(z.length-i-1); j++){
if(z[j]<z[(j+1)]){
int t=z[j];
z[j]=z[j+1];
z[j+1]=t;
}
}
}
for(int i=0; i<z.length; i++){
System.out.print(z[i]+" ");
}
System.out.println();
}
}//end of class
class MatrixOrder_main{
public static void main(String args[]){//main method to create object and call methods
MatrixOrder ob=new MatrixOrder();
ob.accept();
}//end of main()

80 | P a g e
}

D. OUTPUT: --

81 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
M int accept() Rows
N int accept() Columns
A[][] int accept() Matrix
arr[] int for loop Row Matrix
i int for loop Loop Control
z[] int sortasc Parameter
min int for loop Minimum number
t int for loop temporary

--------------------------------------***-----------------------------------

82 | P a g e
ASSIGNMENT 11
DATE: 19.07.22

A. PROGRAM DESCRIPTION: ---


A superclass Binary has been defined to accept a binary number and a subclass ToHex has been defined
to convert binary number into its equivalent hexadecimal number using short cut logic of combining
bits. Some of the members of the class are given below:

Class name : Binary


Data members
n : stores the binary number

Member functions:
BinHex(int n) : constructor to initialize the
data member void display(): display the
binary number
class name: ToHEx

83 | P a g e
Data member:
hex: to store hexadecimal number
Methods:
ToHex(...): Parameterized constructor
void bin_hex(): calculates the hexadecimal equivalent of n and stores it in hex.( using short cut
logic of combining bits) void display() : displays the binary number and hexadecimal number.
You can add any extra methods if required.
Using concept of inheritance write details of both the classes and write main method accordingly.

B. ALGORITHM: --
A superclass named Binary is created with instance variable n

Method Binary

Step 1: start

Step 2: initialization of n with value a passed into as parameter

Step 3: end

Method display

84 | P a g e
Step 1: start

Step 2: printing the binary value stored in n

Step 3: end

A subclass named ToHex is created with instance variable hex

Method ToHex

Step 1: start

Step 2: the parameter of the constructor is passed to the superclass Binary using “super” keyword

Step 3: string hex is initialised to “”

Step 4: end

Method bin_hex

Step 1: start

Step 2: the input binary value is called from the superclass Binary and converted into string using
String.valueOf() method

Step 3: checking if the length of the string containing the binary number is divisible by four or
not using if condition

85 | P a g e
Step 4: declaring variable k with value of length of the string divided by four and then subtracted
from 4;

Step 5: initialising a for loop with i as loop counter variable from 0 to k with updation as i++

Step 6: “0” is concatenated to the string so that it can be divided as set of 4 digits

Step 7: string array bin is declared with binary values of all hexadecimal numbers

Step 8: string array hb is declared with hexadecimal values

Step 9: initialising a for loop with i as loop counter variable from 0 to k with updation as i++

Step 10: initialising a for loop with j as loop counter variable from 0 to k with updation as j++

Step 11: 4 digits are taken from the string from the starting using substring() method and is
compared with all the elements of bin[] using equals()

Step 12: if step 11 is true then hex variable is concatenated with the corresponding hexadecimal
value of the binary number from hb[]

Step 13: end

Method display()

Step 1: start

86 | P a g e
Step 2: calling the superclass Binary to invoke it’s display method to print the binary number
taken as input from user

Step 3: printing the hexadecimal equivalent of the input binary number from the user

Step 4: end

A class named BHmain is created that contains the main method for the super and subclass
Binary and ToHex

Method main

Step 1: start

Step 2: taking binary input from user using temporary scanner class

Step 3: a variable b is declared and initialized with the value in a

Step 4: a while loop is initialised with condition for b>0

Step 5: the digits of b are striped down to check whether all the digits are 1 or 0, i.e, the digits of
any binary number

Step 6: object creation

Step 7: methods bin_hex() and display() are called

Step 8: end
87 | P a g e
C. SOURCE CODE: --
//Program 11: Binary to Hexadecimal
import java.util.*;
class Binary
{
protected int n;
Binary(int a)
{//constructor
n=a;
}//end of Binary()
void display()
{//to display
System.out.println("Binary : "+n);
88 | P a g e
}//end of diaplay()
}//end of class
import java.util.*;
class ToHex extends Binary
{
protected String hex;
ToHex(int a)
{//constructor
super(a);
hex="";
}//end of ToHex
void bin_hex()
{//convert from bin to hex
String s=String.valueOf(super.n);
if(s.length()%4!=0)
{
int k=4-(s.length()%4);
for(int i=0;i<k;i++)
s="0".concat(s);
}
System.out.println(s);
String
bin[]={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","101
1","1100","1101","1110","1111"};
String hb[]={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
for(int i=0;i<s.length()-3;i+=4)
for(int j=0;j<bin.length;j++)

89 | P a g e
if(s.substring(i,i+4).equals(bin[j]))
hex=hex+hb[j];
}//end of bin_hex
void display()
{//sub class
super.display();
System.out.println("Hexadecimal: "+hex);
}
}
import java.util.*;
class Binary_main
{
public static void main(String args[])
{//main method
System.out.println("enter binary number");
int a=new Scanner(System.in).nextInt();
ToHex lys=new ToHex(a);
lys.bin_hex();
lys.display();
}//end of main
}//end of class

90 | P a g e
D. OUTPUT: --

91 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
n int Binary class Input in binary
a int Binary() Parameter
hex String ToHex class Hexa-decimal
a int ToHex() Parameter
S String bin_hex() String to store
k int bin_hex() Find positions
i int if statement Loop Control
j int for loop Loop Control
bin[] String for loop Binary Array
hb[] String bin_hex() Hexa-decimal Array

--------------------------------------***-----------------------------------

92 | P a g e
ASSIGNMENT 12
DATE: 25.07.22

A. PROGRAM DESCRIPTION: ---


A super class Sentence accepts a sentence in uppercase terminated by ‘.’ only. A subclass
Encrypt will
encrypt the words in the sentence with a valid logic given below.
Class name: Sentence Data members:
sen: accepts a sentence in uppercase and terminated by ‘.’ only. Words in the sentence can be
separated by one or more spaces. Methods:
Sentence(String): constructor
void show(): update the sentence where each word will be separated by single space and
terminated by ‘.’.
Display the updated sentence.
Class name: Encrypt Data member:

93 | P a g e
nsen: stores encrypted sentence
methods:
Encrypt(...): constructor void encrypt(): encrypt the words in the updated sentence as per logic
given below:
i) For the word(s) starting with vowel, write the vowel then append consecutive consonants
and vowels present in the word. Example say if the word is EXAMINATION then encrypted
word will be EXAMINATINO
ii) For the word(s) starting with consonant, arrange the characters in the word in descending
order as per ASCII value. Example say if the word is CONSTANT then encrypted word will be
TTSONNCA.
Finally create the encrypted sentence with encrypted word terminated by ‘.’
void show(): display updated original and encrypted sentence.
Using concept of inheritance write details of both the classes and write main method
accordingly.

B. ALGORITHM: --
class Sentence:
method Sentence ():
step 1: start.
step 2: store N in sen
step 3: trim, remove duplicate space and convert sen to upper case.
step 3:end.
Method display():
step 1: start.
step2: Display the Original Sentence
Step3:end.
class Encrypt:
method Encrypt ():
step 1: start.

94 | P a g e
step 2: call the super class constructor with s as parameter
step 3: initialize nsen as “”.
step 4: end.
Method vow(String):
step 1: start
step 2: Store characters of s in array ch.
Step3: store number of vowels and consonants in va and vc respectively.
step 4: initialize arrays vch and cch with the length va and vc as lengths respecctively
Step5: store the vowels and consonants of ch in vch and cch respectively.
Step6: initialize an infinite loop.
step 7: add the I th element of vch to r
step8: if an exception occurs in step 7 add all elements of cch to r and exit loop
step9: add the I th element of cch to r
step10: if an exception occurs in step 9 add all elements of vch to r and exit loop
Step11:increase value of I by 1.
Step12: return r
Step13:end.
Method cnst(String):
step 1: start
step 2: Store characters of s in array arr.
Step3: sort arr in decending order using selection sort logic.
step 4: convert arr into string and store it in a.
Step 5:return a
Step 6:end.
Method encrypt():
step 1: start

95 | P a g e
step 2: Store words of sen in array a.
Step3: initialize a loop with loop counter I as o and till I smaller than the length of a .
step 4: if the first character of the element at I th index of a is a vowel goto step 5 else goto step 6
Step 5: store value returned by calling vow with the element at I th index of a and store it in I th
index of a.
Step 6: store value returned by calling cnst with the element at I th index of a and store it in I th
index of a.
step 7: increase value of I by 1.
Step 9:end.

method display():
step 1: start.
step 2: call the super class display method .
step 3: display the Encrypted sentence
step 4: end.
class Encrypt_main:
method main():
step 1: start.
step 2: accept the sentence and put it as a parameter to call Encrypt constructor and make an
object
step 3: call methods encrypt() and display()and execute accordingly.
step 4: end.

96 | P a g e
C. SOURCE CODE: --
//Program 12: Encrypting Sentences
class Sentence
{
String sen;
Sentence(String N)
{//constructor
sen=N;
sen= sen.trim().replaceAll("\\s+"," ");
sen=sen.toUpperCase();
sen+='.';
}//end of Sentence()
void display()

97 | P a g e
{//to display
System.out.println("Original Sentence: "+sen);
}//end of display
}//end of class
class Encrypt extends Sentence
{
String nsen;
Encrypt(String s)
{//constructor
super(s);
nsen="";
}//end of Encrypt()
String vow(String s)
{//for vowels
char[] ch = s.toCharArray();
int va=0,vc=0;
for(int i=0;i<ch.length;i++)
{
if("AEIOU".indexOf(ch[i])!=-1)va++;
else vc++;
}
char vch[]=new char[va];
char cch[]=new char[vc];int c1=0,c2=0;
for(int i=0;i<ch.length;i++)
{
if("AEIOU".indexOf(ch[i])!=-1)vch[c1++]=ch[i];

98 | P a g e
else cch[c2++]=ch[i];
}
String r="";
mark:for(int i=0;;i++)
{
try{ r+=vch[i];}
catch(Exception e)
{
for(int j=i;j<vc-1;j++)r+=cch[j];
break mark;
}
try{ r+=cch[i];}
catch(Exception e)
{
for(int j=i;j<va-1;j++)r+=vch[j];
break mark;
}
}
return r;
}//end of vow
String cnst(String s)
{//for consonant
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;

99 | P a g e
for (int j = i + 1; j < arr.length; j++){
if (arr[j] > arr[index]){
index = j;//searching for lowest index
}
}
char smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
String a=String.valueOf(arr);
return a;
}//end of cnst
void encrypt()
{//method for encryption
String a[]=super.sen.split(" ");
for(int i=0;i<a.length;i++)
{
if("AEIOU".indexOf(a[i].charAt(0))!=-1)a[i]= vow(a[i]);
else a[i]=cnst(a[i]);
nsen=nsen+" "+a[i];
}
}//end of encrypt()
void display()
{//sub class
super.display();
System.out.println("Encrpted Sentence: "+nsen.toUpperCase());

100 | P a g e
}//end of display()
}//end of class
import java.util.*;
class Encrypt_main
{
public static void main(String args[])
{ //main method
System.out.println("Enter Sentence: ");
Encrypt ob=new Encrypt(new Scanner(System.in).nextLine());
ob.encrypt();
ob.display();
}//end of main()
}//end of class

D. OUTPUT: --

101 | P a g e
E. VARIABLE LISTING: --
102 | P a g e
NAME DATATYPE SCOPE PURPOSE
sen String class Sentence Sentence
N String Sentence() Parameter
nsen String class Encrypt Sentence New
S String Encrypt() Parameter
S String vow() Parameter
ch[] char vow() Character array
va int vow() count of vowels
vc int vow() count of consonants
i int for loop Loop Control
j int for loop Loop control
vch[] char vow() character array
cch[] char vow() character array
c1 int vow() counter 1
c2 int vow() counter 2
r String vow() String to store
arr[] char cnst() character array
smallerNumber char for loop Smaller Number
a[] String encrypt() Character Array

--------------------------------------***-----------------------------------

ASSIGNMENT 13
103 | P a g e
DATE: 28.07.22

A. PROGRAM DESCRIPTION: ---


A superclass Number is defined to accept number of terms and also calculate the factorial of a
number. Define a subclass Series to find the product of the series
P = x * x2/3! * x4/4! * x8/5! * x16/6! n terms
The details of the members of both classes are given below: Class name: Number
Data member/instance variable:
n: to store an integer number Member functions/methods:
Number(int): constructor to initialize the data member int factorial(int a): returns the factorial of
a number(use recursion)
(factorial of n(n!) = 1 × 2 × 3 × …… × n)
void display(): displays the value of n
Class name: Series
Data member/instance variable:
prod: to store the product of the series x: accepts value of unknown variable x(in double)
Member functions/methods:
Series(…) : parameterized constructor to initialize the data members of both the classes
void calProd(): calculates the PRODUCT of the given series void display(): displays the data
members of both the classes

Using concept of inheritance write details of both the classes and write main method accordingly

B. ALGORITHM: --
Parent class named Number is created with protected instance variable n
104 | P a g e
Constructor Number(int nn):
Step 1: start
Step 2: value of nn is stored in variable n
Step 3: end
Method int factorial(int a):
Step 1: start
Step 2: if the value of a is equal to 1, return 1
Step 3: return the product of a and method factorial() passed with the value of 1 decreased from a
Step 4: end
Method display():
Step 1: start
Step 2: display "Number of terms in the series: " with the value of n
Step 3: end
Subclass of parent class Number named Series is created with private instance variables prod and
x
Constructor Series(int nn, double xx):
Step 1: start
Step 2: super class constructor is called with the value of nn
Step 3: the value of xx is stored in x
Step 4: the value of x is stored in prod
Step 5: end
Method calProd():
Step 1: start
Step 2: for loop is created with loop counter variable I initiliased with 2, the final value being
less than or equal to the value of n
Step 3: variable num is declared and initialised with the value of x raised to the power of (2
raised to the power of (I-1))

105 | P a g e
Step 4: variable den is declared and initialised with the value of super class factorial() called with
the value of (I+1)
Step 5: the product of the value of prod and (num/den) is stored in variable prod
Step 6: value of I is increased by 1
Step 7: end
Method display():
Step 1: start
Step 2: super class display() is called
Step 3: display "Value of x given: " with the value of x
Step 4: display "Product of series: " with the value of prod
Step 5: end
Class named Series_Main is created
Method main():
Step 1: start
Step 2: display "Enter the number of numbers and value of x"
Step 3: object sc of Scanner class is created
Step 4: the number of numbers is entered by the user and stored in variable n
Step 5: the value of x is entered by the user and stored in variable x
Step 6: object ob of Series class is created with parameters n and x
Step 7: methods calProd() and display() are called to execute accordingly
Step 8: end

C. SOURCE CODE: --
//Program 13: To display product of series
106 | P a g e
class Number
{
protected int n;
Number(int nn)
{//constructor
n = nn;
}//end of Number()
int factorial(int a)
{//to calculate factorial
if(a == 1)
return 1;
return a * factorial(--a);
}//end of factorial
void display()
{//to display
System.out.println("Number of terms in the series: " + n);
}//end of display
}//end of class
class Series extends Number
{
private double prod,x;
Series(int nn, double xx)
{//constructor
super(nn);
x = xx;
prod = x;

107 | P a g e
}//end of Series()
void calProd()
{//to calculate product of series
for(int i = 2; i <= n; i++)
{
double num = Math.pow(x, Math.pow(2, i - 1));
double den = super.factorial(i + 1);
prod *= num/den;
}
}//end of callProd
void display()
{//sub class to display
super.display();
System.out.println("Value of x given: " + x);
System.out.println("Product of series: " + prod);
}//end of display()
}//end of class
import java.util.*;
class Series_Main
{
public static void main(String args[])
{//main method
System.out.println("Enter the number of numbers and value of x");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int x=sc.nextInt();

108 | P a g e
Series ob = new Series(n,x);
ob.calProd();
ob.display();
}//end of main
}//end of class

109 | P a g e
D. OUTPUT: --

110 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
n int Number class and stores the number of
main class numbers
nn int Number() Constructor variable
x int Series class and main Stores the value of x
class given by the user
a int Number class and Holds the value of
factorial() which the factorial is
calculated
I int calProd() Loop counter variable
prod double Number class Used to store the
product
den double calProd() Stores the factorial
num double calProd() Used for calculation

xx double Constructor of Series Used to store the


class passed value of x

--------------------------------------***-----------------------------------

ASSIGNMENT 14
111 | P a g e
DATE: 03.08.22

A. PROGRAM DESCRIPTION: ---


Mita and Gita are two sisters. Mita has a particular number of coins. Gita already has some
amount of money. The values are to be entered. Now coins of which denominations must be
given by Mita to Gita so that both of them have same amount of money.
Write a program to implement the above logic for n number of test cases, where for each test
case, first input line will contain how many coins Mita have and total amount of money available
with Gita. Second input line will contain different denomination present with Mita. Finally your
code will display 1 if it is possible to share coin(s) by Mita to Gita so that both of them have
same amount money otherwise display 0.
Example:
No. Of test cases: 2
Case 1: 5 6
12306
Case 2: 5 5
12326
Output: 1
0

112 | P a g e
B. ALGORITHM: --
A class named MoneyMatch is created
STEP 1: Start
STEP 2: declaring class variables
STEP 3: End
Method MoneyMatch(…)
STEP 1: Start
STEP 2: initialisation of class variables in constructor method
STEP 3: End
Method input()
STEP 1: Start
STEP 2: initialisation of scanner class
STEP 3: declaring for loop for taking in input from user
STEP 4: calling checkShare method for checking if sharing money is possible or not and then
either 1 or 0 is returned which is stored in array s
STEP 5: printing the output stored in array s
STEP 6: End
Method checkShare(…)
STEP 1: Start
STEP 2: initialisation of loop with counter variable i
STEP 3: variable c is initialised to store the sum of money with Mita
STEP 4: the money given to Gita is subtracted from c
STEP 5: steps 3 and 4 are repeated until 1 is returned
STEP 6: if 1 is not returned than by default 0 is returned
STEP 7: End

113 | P a g e
A class named MMmain is designed
STEP 1: start
STEP 2: scanner class is initialised
STEP 3: input is taken from user for the number of cases
STEP 4: object lya is created of class MoneyMatch
STEP 5: object lya used to call method input
STEP 6: End

C. SOURCE CODE: --
//Q14:matching two friend's money while sharing
import java.util.*;
class MoneyMatch
{
private int n;
private int x;
private int y;
private int s[];
MoneyMatch(int N)//initialising through constructor
{
n=N;
x=0;
y=0;
s=new int[n];
}
void input()//method to take input form user
{
Scanner xy=new Scanner(System.in);//scanner class initialisation
for(int i=0;i<n;i++)
114 | P a g e
{
System.out.println("Case "+(i+1)+" : ");
x=xy.nextInt();
y=xy.nextInt();//taking input from user
int a[]=new int[x];
for(int j=0;j<x;j++)
a[j]=xy.nextInt();//taking input from user
s[i]=checkShare(a);//calling checkShare
}
for(int i=0;i<n;i++)
System.out.println(s[i]);//printing 1 or 0 values to check money sharing cases
}//end of method
int checkShare(int arr[])//start of method chefckShare
{
for(int i=0;i<arr.length;i++)
{
int c=0;
for(int j=0;j<arr.length;j++)
c=c+arr[j];//taking all the sum of the money owned by Mita
c=c-arr[i];//subtracting the amount of money from Mita's total money that is given to Gita
if(c==(arr[i]+y))//checking if after the sharing of money they both have equal amount or
not
return 1;//if they have equal amput then 1 is returned as per program
}
return 0;//0 gets returned by default if the amount does'nt match
}//end of method
}//end of class
115 | P a g e
import java.util.*;
class MMmain
{
public static void main(String args[])
{//start of main methos
Scanner xy=new Scanner(System.in);
System.out.print("No. Of test cases: ");
int n=xy.nextInt();
MoneyMatch lya=new MoneyMatch(n);//creation of object and calling of constructor
method in MoneyMatch class
lya.input();//using object to call input method
}//end of main
}//end of class

D. OUTPUT: --

116 | P a g e
E. VARIABLE LISTING: --
name datatype scope purpose
n int MoneyMatch Stores user input for
number of test cases
x int MoneyMatch Stores number of
coins Mita has taken
from user
y int MoneyMatch Stores total money
Gita has taken from
user
s[] int MoneyMatch Stores output
N int MoneyMatch Stores paramitarised
value
i int for Loop conter

117 | P a g e
a[] int for Stores money
denomitations of
Mita
j int for Loop counter
i int for Loop counter
arr[] int checkShare Stores copy of array
a from method input
i int for Loop counter
c int for Used to store total
sum of money
owned by Mita
j int for Loop counter
n int main Takes input from
user for the number
of cases
----------------------------------- ***-----------------------------------

ASSIGNMENT 15
DATE: 17.08.22

A. PROGRAM DESCRIPTION: ---


Accept the row and column from user and create a 2 d Array. Accept elements in it. Then sort
the elements using two separate methods
a) By using a 1 d array
118 | P a g e
b) Without using a 1 d array

B. ALGORITHM: --
A class is created with the name MatrixSort with instance variables arr[][] ,r and c

119 | P a g e
Method MatrixSort():
Step 1:Start
Step 2:Initialize r and c to 0 and arr[][] with r and c as its row and column size respectively
Step 3:End
Method accept():
Step 1:Start
Step 2:Declare a scanner class
Step 3:Display “Enter row and column”
Step 4:Take row size as input from the user and store it in r
Step 5: Take column size as input from the user and store it in c
Step 6:Initialize arr[][] with r and c as its row and column size respectively
Step 7:Display “Enter elements”
Step 8:Declare a for loop with i as its counter variable initialized to 0 and final value less than r
Step 9:Declare a for loop with j as its counter variable initialized to 0 and final value less than c
Step 10:Take input from the user and store it in ith row and jth column of array arr[][]
Step 11:Increase the value of j by 1
Step 12:Increase the value of i by 1
Step 13:End
Method with1d():
Step 1:Start
Step 2:Declare a 1d array of size r multiplied by c
Step 3:Declare a variable named x and initialize 0 to it
Step 4:Declare a for loop with i as its counter variable initialized to 0 and final value less than r
Step 5:Declare a for loop with j as its counter variable initialized to 0 and final value less than c
Step 6:Store the element of ith row and jth column in the xth index of array s[]
Step 7:Increase the value of x by 1

120 | P a g e
Step 8:Increase the value of j by 1
Step 9:Increase the value of i by 1
Step 10:Declare a for loop with i as its counter variable initialized to 0 and final value 1 less than
the length of array s
Step 11:Declare a for loop with j as its counter variable initialized to 0 and final value less than
the length of array s-1-i
Step 12:If the element in jth index of array s is greater than (j+1)th index of array then go to step
13 else go to step 16
Step 13:Declare a variable named t and store the value in jth index of array s
Step 14:Store the element in (j+1)th index to jth index of array s
Step 15:Store the value of t in the (j+1)th index of array s
Step 16:Increase the value of j by 1
Step 17:Increase the value of i by 1
Step 18:Initialize x to 0
Step 19: Declare a for loop with i as its counter variable initialized to 0 and final value less than r
Step 20: Declare a for loop with j as its counter variable initialized to 0 and final value less than c
Step 21: Store the element of xth index of array s[] in the ith row and jth column of array arr[][]
Step 22: Increase the value of x by 1
Step 23:Increase the value of j by 1
Step 24:Increase the value of i by 1
Step 25:Call the method display()
Step 26:End
Method without1d():
Step 1:Start
Step 2:Declare a variable named n and store the length or row of array arr
Step 3:Declare a variable named m and store the column of array arr
Step 4:Declare a for loop with i as its counter variable initialized to 0 and final value less than (n
multiplied by m)-1

121 | P a g e
Step 5:Declare a for loop with j as its counter variable initialized to 0 and final value less than (n
multiplied by m)-1-i
Step 6:If the element in (j/m)th row and (j%m)th column is greater than the element in (j+1/m)th
row and (j+1%m)th column then go to step 7 else go to step 10
Step 7:Declare a variable named temp and store the element in (j+1/m)th row and (j+1%m)th
column
Step 8:Store the element in (j/m)th row and (j%m)th column element in (j+1/m)th row and
(j+1%m)th column
Step 9:Store the value of temp in (j/m)th row and (j%m)th column
Step 10:Increase the value of j by 1
Step 11:Increase the value of i by 1
Step 12:Call the display method
Step 13:End
Method display():
Step 1:Start
Step 2: Declare a for loop with i as its counter variable initialized to 0 and final value less than r
Step 3: Declare a for loop with j as its counter variable initialized to 0 and final value less than c
Step 4:Display the value stored in ith row and jth column of array
Step 5:Increase the value of j by 1
Step 6:Display “”
Step 7:Increase the value of i by 1
Step 8:End
A class is created with the name MatrixSortMain
Method main():
Step 1:Start
Step 2:Create an instance of MatrixSort class
Step 3:Call the method accept()
Step 4:Display “Sorted matrix with 1d array”

122 | P a g e
Step 5:Call the method with1d()
Step 6:Call the method accept()
Step 7:Display “Sorted matrix without 1d array”
Step 8:Call the method without1d()
Step 9:End

123 | P a g e
C. SOURCE CODE: --
//sorting of matrix
import java.util.*;
class MatrixSort{//instance variables
private int arr[][];
private int r;
private int c;
MatrixSort(){//constructor
r=0;c=0;
arr=new int[r][c];
}//end of constructor
void accept(){//taking input
Scanner sc=new Scanner(System.in);
System.out.println("Enter row and column");
r=sc.nextInt();
c=sc.nextInt();
arr=new int[r][c];
System.out.println("Enter elements");
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
124 | P a g e
arr[i][j]=sc.nextInt();
}//end of j loop
}//end of i loop
}//end of accept
void with1d(){//sorting with 1d array
int s[]=new int[r*c];
int x=0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){//assigning to 1d array
s[x]=arr[i][j];
x++;
}//end of j loop
}//end of i loop
for(int i=0;i<s.length-1;i++){//sorting
for(int j=0;j<s.length-i-1;j++){
if(s[j]>s[j+1]){//swapping
int t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}//end of if
}//end of j loop
}//end of i loop
x=0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){//re changing to 2d
arr[i][j]=s[x];

125 | P a g e
x++;
}//end of j loop
}//end of i loop
display();
}//end of with1d method
void without1d(){
int n=arr.length;
int m=arr[0].length;
for (int i=0;i<n*m - 1; ++i) {
for (int j=0;j<n*m-1-i; ++j) {//sorting without 1d
if (arr[j/m][j%m]>arr[(j+1)/m][(j+1)%m]) {
int temp = arr[(j+1)/m][(j+1)%m];
arr[(j+1)/m][(j+1)%m]=arr[j/m][j%m];
arr[j/m][j%m]=temp;
}//end of if
}//end of j loop
}//end of i loop
display();
}//end of without1d method
void display(){//for displaying array
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
System.out.print(arr[i][j]+" ");
}//end of j loop
System.out.println();
}//end of i loop

126 | P a g e
}//end of display method
}//end of class
//class for main method
class MatrixSortMain{
public static void main(String args[]){
MatrixSort ob=new MatrixSort();
//calling methods
ob.accept();
System.out.println("Sorted Matrix with 1d array");
ob.with1d();
ob.accept();
System.out.println("Sorted Matrix without 1d array");
ob.without1d();
}//end of main
}//end of class

D. OUTPUT: --

127 | P a g e
128 | P a g e
E. VARIABLE LISTING: --
Name Datatype Scope Purpose
r int MatrixSort{} Store the row of
the array
c int MatrixSort{} Store the column
of the array
arr[][] int MatrixSort{} Store the
elements as
entered by user
i int for() Loop counter
j int for() Loop counter
x int with1d() Position counter
s[] int with1d() To store elements
in 1d array
t int if() Swapping
purpose
n int without1d() Storing position
m int without1d() Storing position
temp int if() Swapping
purpose

----------------------------------- ***-----------------------------------

129 | P a g e
ASSIGNMENT 16
DATE: 18.08.22

A. PROGRAM DESCRIPTION: ---


Define a class Repeat which allows the user to add elements from one end (rear) and remove
elements from the other end (front) only. The following details of the class Repeat are given
below:
Class name: Repeat
Data Members/instance variables:
st[]: an array to hold a maximum of 100 integer elements
cap: stores the capacity of the array
f: to point the index of the front
r: to point the index of the rear
Member functions:
Repeat (int m): constructor to initialize the data members cap = m, f = 0, r = 0 and to create the
integer array
void pushvalue (int v): to add integer from the rear index if possible else display the message
(“OVERFLOW”)
int popvalue (): to remove and return element from the front. If array is empty then return -
9999
void disp (): Displays the elements present in the list

130 | P a g e
Specify the class Repeat giving details of the constructor (int), member function void pushvalue
(int). int popvalue () and void disp (). Write the main( ) function to test the program.

B. ALGORITHM: --
A class named Repeat is created with instance variables st[], cap, f, r
Constructor Repeat(int m):
Step 1: start
Step 2: value of m is stored in cap, f=0, r=0, and st is initialized with size cap
Step 3: end
Method void pushvalue(int v):
Step 1: start
Step 2: if r is less than cap-1 then go to step 3 else print “OVERFLOW”
Step 3: Update r=r+1 and value of position r of array st as v
Step 4: end
Method popvalue()
Step 1: start
Step 2: declare variable v
Step 3: if r not equal to f then go to step 4 else return -9999
Step 4: update f=f+1, v= value of position f of array st and then return v
Step 5: end

131 | P a g e
Method display():
Step 1: start
Step 2: if r not equal to f then go to step 3 else print “EMPTY”
Step 3: start a loop with initial value of loop control variable i=f+1, till i<=r and increment I by
+1 in every iteration
Step 4: Within the loop, print value of position i of array st
Step 5: End
Class named Repeat_main is created
Method main(String args[]):
Step 1: start
Step 2: declare a variable s and another variable an
Step 3: take input of s from user with proper message and check for s<=0 or not and repeat the
input if s<=0
Step 4: declare object ob of class Repeat
Step 5: start a do while loop with condition to repeat the iteration if an=’y’ or ‘Y’
Step 6: within loop, accept ch as 1 or 2 or 3 from user and print message “wrong choice” if
something else is chosen
Step 7: if choice is 1, start a for loop from i=0 to i<s with increment of +1 in every iteration and
within, accept value of x from user and call the pushvalue() function with x as parameter, using
object ob
Step 8: if choice is 2, print the value received by calling the function popvalue() using object ob
Step 9: if choice is 3, call the display() function using object ob
Step 10: accept value of an from the user
Step 11: end the do while loop
Step 12: end

132 | P a g e
C. SOURCE CODE: --
//Q16 : Adding and Removing elements repetitively
class Repeat
{
private int st[];
private int cap,f,r;
Repeat(int m)
{//constructor
cap=m;
f=0;

133 | P a g e
r=0;
st=new int[cap];
}//end of Repeat()

void pushvalue(int v)
{//to add integer from the rear index if possible
if((r)<cap-1)
{
r=r+1;
st[r]=v;
}
else
{
System.out.println("OVERFLOW");
}
}//end of pushvalue()

int popvalue()
{//to remove and return element from the front. If array is empty then return -9999

int v;
if(r!=f)
{
f=f+1;
v=st[f];
return v;

134 | P a g e
}
else
{
return -9999;
}

}//end of popvalue()

void display()
{//to display data
if(r!=f)
{
for(int i=f+1;i<=r;i++)
{
System.out.println(st[i]);
}
}
else
{
System.out.println("EMPTY");
}
}//end of display()
}//end of Repeat class

import java.util.*;
class Repeat_main{

135 | P a g e
public static void main(String args[]){//main method to create object and call methods
int s; char an ;
Scanner sc=new Scanner(System.in);
do{
System.out.println("enter the size of queue");
s=sc.nextInt();
}while(s<=0);
Repeat ob=new Repeat(s+1);
do{ System.out.println("press 1 for push , 2 for pop , 3 for display");
System.out.println("enter your choice");
int ch=sc.nextInt();
switch(ch){//switch for choice of push, pop or display
case 1: for(int i=0;i<s;i++){System.out.println("enter the element");
int x=sc.nextInt();
ob.pushvalue(x);
}
break ;
case 2: System.out.println(ob.popvalue());
break ;
case 3 : ob.display();
break ;
default: System.out.println("wrong choice");
}//end of switch case
System.out.println("Do you wants to continue(y/n)");
an=sc.next().charAt(0);
}while(an=='y' || an=='Y');

136 | P a g e
}//end of main()
}//end of class

D. OUTPUT: --

137 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
st[] int class Repeat An array to hold a
maximum of 100
integer elements
cap int class Repeat Stores the capacity of
the array
f int class Repeat To point the index of
the front
r int class Repeat to point the index of the
rear
m int Repeat() Parameter
v int pushvalue() Parameter
v int popvalue() Particular Element
s int main() Size input from user

an char main Choice(y/n)

ch int do-while loop Choice(1/2/3)


i int for loop Loop Control

----------------------------------- ***-----------------------------------

138 | P a g e
ASSIGNMENT 17
DATE: 14.09.22

A. PROGRAM DESCRIPTION: ---


A stack is a kind of data structure which can store elements with the restriction that an element
can be added or removed from the top only. The details of the class Stack is given below:
Class name: Stack
Data members/instance variables: st[]: the array to hold the names
size: the maximum capacity of the string array
top: the index of the topmost element of the stack
ctr: to count the number of elements of the stack
Member functions: Stack( ): default constructor
Stack(int cap): constructor to initialize size = cap and top = -1
void pushname(String n): to push a name onto the stack. If the stack is full, display the message
“OVERFLOW”
String popname(): removes a name from the top of the stack and returns it. If the stack is empty,
display the message “UNDERFLOW”

139 | P a g e
void display(): Display the elements of the stack.
Specify class Stack giving details of the constructors(), void pushname(String n), String
popname() and void display().Write the main() to test the program

B. ALGORITHM: --
A class named Stack is designed
STEP 1: start
STEP 2: declaration of class variables
STEP 3: end
Method Stack()
STEP 1: start
STEP 2: initialisation of class variables
STEP 3: end
Method Stack(…)
STEP 1: start
STEP 2: initalisation of class variables as input by user
STEP 3: end
Method pushname(…)
140 | P a g e
STEP 1: start
STEP 2: checking if the stack is completely full or not
STEP 3: if stack is not full than the top is pushed by 1
STEP 4: end
Method popname(…)
STEP 1: start
STEP 2: checking is the stack is empty or not
STEP 3: stack size decresed by 1
STEP 4: end
Method display()
STEP 1: start
STEP 2: if stack is empty then UNDERFLOW is printed
STEP 3: if stack contains information then the contents are displayed using for loop
STEP 4: end
A class named STmain is designed
Method main(String args[])
STEP 1: start
STEP 2: initialisation of scanner class
STEP 3: stack size is taken as input from user using do while loop so that the user doesnot input
invalid number
STEP 4: declaring and initialisation of stack to size input by user
STEP 5: do while loop initialised for running the program until user discontinues
STEP 6: user is asked for input for push, pop or display
STEP 7: user input is taken and thrown in switch case
STEP 8: if user chooses 1 for push than case 1 is activated and elements input is taken from user
and the method pushname is called
STEP 9: if user chooses 2 for pop than case 2 is activated popname method is called
STEP 10: if user chooses 3 for display than case 3 is activated and method display is called

141 | P a g e
STEP 11: if user chooses anyother number other than 1,2,3 than wring choice message is shown
by default
STEP 12: user is asked if he wants to continue with the program, if user wants he can continue
pressing y or he exit typing n
STEP 13: end

C. SOURCE CODE: --
//q17 data structure stack program
import java.util.*;
class Stack{//sstart of class
String st[];

142 | P a g e
int top;
int size;
int ctr;
Stack(){//start of constructor
size=ctr=top;
}//end of constructor
Stack(int cap){//start of parameterised constructure
size=cap;
st=new String[size];
ctr=size;
top=-1;
}//end of parameterised constructor
void pushname(String n){//start of method
if(top==ctr-1)
System.out.println("OVERFLOW");//printing overflow if the stack is fully filled
else
st[++top]=n;
}//end of method
String popname(){//start of method
if(top==-1)
System.out.println("UNDERFLOW");//displaying underflow if the stack is fully empty
return st[top--];
}//end of method
void display(){//start of method
if(top==-1)
System.out.println("UNDERFLOW");//displaying underflow if stack is empty
else
{ for(int i=top ; i>=0; i--)
143 | P a g e
System.out.println(st[i]);//printing contents of stack
}
}//end of method
}//end of class
//main method for stack
import java.util.*;
class STmain
{//start of class
public static void main(String args[]){//start of main method
int s; char an;
Scanner sc=new Scanner(System.in);//scanner class initalisation
do{
System.out.println("enter the size of stack");//taking input from user
s=sc.nextInt();
}while(s<=0);//checking if the given input is invalid or not
Stack ob=new Stack(s);//creation of stack
do{ System.out.println("Press 1 for push , 2 for pop , 3 for display");//asking user for choice
for the stack to do
System.out.println("Enter your choice");
int ch=sc.nextInt();//taking user choice
switch(ch){//using switch case to do the function as input from user
case 1: for(int i=0; i<s;i++){
System.out.println("Enter the element");//taking in inputs from user
String x=new Scanner(System.in).nextLine();
ob.pushname(x);//caling pushname method
}
break ;
case 2: System.out.println(ob.popname());//calling popname function

144 | P a g e
break ;
case 3 : ob.display();//calling display function
break ;
default: System.out.println("Wrong choice");//displaying message if input is wrong
}//end of switch case
System.out.println("Do you want to continue(y/n)");//asking user if they want ot continue
an=sc.next().charAt(0);//taking in user input
}while(an=='y' || an=='Y');//continuing the stack usage until user discontinues it
}//end of main
}//end of class

145 | P a g e
D. OUTPUT: --

146 | P a g e
E. VARIABLE LISTING: --
name datatype scope purpose
s int main Stores size of array
an char main Stores y/n for do
while
ob Stack main Stack used
ch int do-while Used to store user
input for push, pop
or display
i int for Loop counter
variable
top int Stack The index of the
topmost element of
the stack

147 | P a g e
st[] String Stack The array to hold the
names
size int Stack The maximum
capacity of the string
array
ctr int Stack To count the number
of elements of the
stack
cap int Stack Stores size of stack
as parameter
n String pushname Stores input names
as input
i int for Loop counter
variable
----------------------------------- ***-----------------------------------

ASSIGNMENT 18
DATE: 15.09.22

A. PROGRAM DESCRIPTION: ---

148 | P a g e
A node has Employye name , code , experience and salary. Use the single linked list concept to
do the following tasks .
a) Insert a new node in the single linked list
b) Display the single linked list
c) Update the salary by 10% of its original salary if experience is more than 10 years and display
the list
d) Delete the employee details if he leaves the job or is sacked.

Write the main() to test the above problem

149 | P a g e
B. ALGORITHM: --
A class is designed with the name Node and instance variables name, code, exp, salary and next
with their corresponding data types.

A class is designed with the name Employee and instance variable head of datatype Node class.
Method add():
Step 1: Start
Step 2: An object ob of Node class is created.
Step 3: The name, code, experience and salary are taken as input using Scanner class and stored.
Step 4: If head equals null then ob is initialized to head.
Step 5: Else a temporary object of Node class is created and head is stored in it.
Step 6: When temp is linking to null then it is linked to ob to link it.
Step 7: End
Method update():
Step 1: Start
Step 2: A temporary object of Node class is created and head is stored in it.
Step 3: While temp not equals null and if experience is greater than 10 then salary is 1.1 times
the previous salary.
Step 4: temp is linked to the next node.
Step 5: the display method is called.
Step 6: End
Method display():
Step 1: Start
Step 2: A temporary object of Node class is created and head is stored in it.
Step 3: While temp not equals null, the name, code, experience and salary is displayed and temp
is linked to the next node.
Step 4: End
Method delete():
150 | P a g e
Step 1: Start
Step 2: The name to be deleted is taken as in input and stored in n.
Step 3: if the name in head equals the input then head is linked to the next node.
Step 4: Else A temporary object of Node class is created and head is stored in it.
Step 5: While temp not equals null and if the next node’s name equals the input then next node
is ignored and the control from the loop is broken using return.
Step 6: temp is linked to the next node.
Step 7: If the control remains then name not found is displayed.
Step 8: End

A class is designed with the name EmployeeMain


Method main():
Step 1: Start
Step 2: An object ob of Employee class is created.
Step 3: A for loop is declared with loop variable i initialized with 1 and incremented by 1.
Step 4: The choice of operation is taken as input from the user and switch case is declared.
Step 5: If the user presses “I” then add method is called with the help of ob.
Step 6: If the user presses “P” then display method is called with the help of ob.
Step 7: If the user presses “U” then update method is called with the help of ob.
Step 8: If the user presses “D” then deletemethod is called with the help of ob.
Step 9: If the user presses “E” then program execution ends with a return statement.
Step 10: If the user inputs something other than that it is shown to be an invalid choice.
Step 11: End

151 | P a g e
C. SOURCE CODE: --
//Q18_Node Class
class Node{
String name;//name
String code;//code
int exp;//experience
double salary;//salary
Node next;//to link
}//end of class
//Update employee details
import java.util.Scanner;
class Employee{//start of class
private Node head;
void add(){//to add
Node ob = new Node();//object of Node class
System.out.println("Enter employee's name, code, experience, salary");
ob.name = new Scanner(System.in).nextLine();//name
ob.code = new Scanner(System.in).nextLine();//code
do{

152 | P a g e
ob.exp = new Scanner(System.in).nextInt();//experience
ob.salary = new Scanner(System.in).nextDouble();//salary
}while(ob.exp < 0 || ob.salary < 0);
if(head == null){
head = ob;
}
else{
Node temp = head;//temporary
while(temp.next != null)
temp = temp.next;//to link to the next node
temp.next = ob;//to set the link
}
}//end of add
void display(){//to display
Node temp = head;//temporary
while(temp != null){
System.out.println("Name: " + temp.name + " Code: " + temp.code + " Experience: " +
temp.exp + " Salary: " + temp.salary);
temp = temp.next;//to link
}
}///end of display
void update(){//to update salary
Node temp = head;//temporary
while(temp != null){
if(temp.exp > 10)//if experience is greater than 10
temp.salary = 1.1 * temp.salary;//updation
temp = temp.next;//to link
153 | P a g e
}
display();//display method is called
}//end of update
void delete(){//to delete
System.out.println("Enter name to be deleted");
String n = new Scanner(System.in).nextLine();//name to be deleted
if(head.name.equals(n))
head = head.next;//to link
else{
Node temp = head;//temporary
while(temp.next != null){
if(temp.next.name.equals(n)){
temp.next = temp.next.next;
return;//to breakk control
}
temp = temp.next;//to link
}
System.out.println("Name not found");
}
}//end of delete
}//end of class
//Initial class
import java.util.Scanner;
class EmployeeMain{
public static void main(String[] args){//start of main
Employee ob = new Employee();//object of the class is created

154 | P a g e
for(int i = 1; ; i++){
System.out.println("Enter choice of operation: I for insertion, P for print, U for updation,
D for deletion, E for exit");
char c = new Scanner(System.in).next().charAt(0);//user's choice
switch(c){
case 'i':
case 'I': ob.add();//to add
break;
case 'p':
case 'P': ob.display();//to display
break;
case 'u':
case 'U': ob.update();//to update
break;
case 'd':
case 'D': ob.delete();//to delete
break;
case 'e':
case 'E': System.out.println("Program execution ended");
return;//to terminate the program
default: System.out.println("Invalid choice of operation");
}
}
}//end of main
}//end of class

155 | P a g e
D. OUTPUT: --

156 | P a g e
157 | P a g e
E. VARIABLE LISTING: --
NAME PURPOSE DATATYPE SCOPE
name Name String Node
code Code String Node
exp Experience int Node
salary Salary double Node
next To link class Node
head Starting node class Employee
temp Temporary node to class add
store the head display
update
n Name to be deleted String delete()
c Choice char for loop
i Loop control int for loop
ob Object of class class add

----------------------------------- ***-----------------------------------

158 | P a g e
ASSIGNMENT 19
DATE: 21.09.22

A. PROGRAM DESCRIPTION: ---


Write a program which will accept a sentence in uppercase and must terminate with either . or ?
or !. Each of the word in the sentence can be separated with one or more spaces. Encrypt the
words in the sentence by extracting the vowels in the word, sort them alphabetically. Each of the
word must be encrypted by appending the sorted vowels and remaining characters of the word
without changing the sequence of other characters in the original word. For example
MECHANIC will be encrypted as AEIMCHNC. Finally display the updated sentence with the
encrypted words separated by single space and must terminate with the punctuation mark given
in original sentence. Details of the class declaration given below:

Example: Enter a sentence in upper case terminated by either ?/./!


COMPUTER APPLICATIONS IS A PART OF COMPUTER SCIENCE.
Updated sentence=EOUCMPTR AAIIOPPLCTNS IS A APRT OF EOUCMPTR EEISCNC.

Class name: Encrypt


Data members: sen: original sentence
nsen: updated sentence

Member method:
1. Encrypt(): default constructor used to initialize members of the class with default values.
2. void accept(): accept the sentence and perform possible checking required. (ASSUME THAT
THE SENTENCE IS TAKEN AS INPUT IN UPPERCASE.). Assume that accept() method is
already written.
3. void encrypt(): encrypt the words in the sentence with the logic given above and display the
final sentence.
4. char[] sort(char[]): sort the vowels in alphabetical order using bubble sort logic.
Write the main() to test the progtram

159 | P a g e
B. ALGORITHM: --
A class is designed with the name Encrypt and instance variables sen and nsen
Method Encrypt():
Step 1: Start
Step 2: wrd= “”
Step 3: nsen=””
Step 4: End
Method accept():
Step 1: Start
Step 2: A sentence is taken as the input in uppercase and ending with “./?/!” and stored in sen
using Scanner class.
Step 3: End
Method encrypt():
Step 1: Start
Step 2: The words are stored in w[] .
Step 3: A for loop is declared with loop variable i starting with 0 and less than length of w with
increment of 1.

160 | P a g e
Step 4: The variables c and d are initialized with 0.

Step 5: A for loop is declared with loop variable j starting with 0 and less than length of w[i]
with increment of 1.

Step 6: If the j th character of the word is a vowel then c is incremented by 1.

Step 7: A character array v is declared of size c.

Step 8: A for loop is declared with loop variable j starting with 0 and less than length of w[i]
with increment of 1.

Step 9: If the j th character of the word is a vowel then vowel is stored in v.

Step 10: The string equivalent of the character array returned after passing v to sort() method is
stored in nsen.

Step 11: A for loop is declared with loop variable j starting with 0 and less than length of w[i]
with increment of 1.

Step 12: If the j th character of the word is not a vowel then the character is added to nsen.

Step 13: The updated sentence is displayed.

Step 14: End

Method sort(char h[]):


Step 1: Start
Step 2: Start a loop from i=0 to i<length of h-1 and increment i by 1.
Step 3: Start a loop from j=0 to j<length of h-i-1 and increment j by 1.
Step 4: If h[j] is greater than h[j+1], t=h[j], h[j]=h[j+1] and h[j+1]=t.

Step 5: h is returned.

Step 6: End

161 | P a g e
A class is designed with the name Main_Encrypt
Method main(String args[]):
Step 1: Start
Step 2: Create an object ob of Encrypt class.
Step 3: Call accept() using ob.
Step 4: Call encrypt() using ob.
Step 5: End

C. SOURCE CODE: --
//Q19_Encryption
import java.util.*;
class Encrypt
{
String sen;
String nsen;
Encrypt()

162 | P a g e
{ //to initialize the instance variables
sen="";
nsen="";
}

void accept()
{//start of accept
System.out.println("Enter a sentence in upper case terminated by either ?/./!");
sen=new Scanner(System.in).nextLine();//to take the input
if(".?!".indexOf(sen.charAt(sen.length()-1))<0 || sen!=sen.toUpperCase())
{
System.out.println("INVALID SENTENCE");
System.exit(0);
}
}//end of accept

void encrypt()
{
char l=sen.charAt(sen.length()-1);//to store last character
sen=sen.substring(0,sen.length()-1).trim();
String w[]=sen.split("[ ]+");//to split words
for(int i=0;i<w.length;i++)
{
int c=0;int d=0;
for(int j=0;j<w[i].length();j++)
if("AEIOU".indexOf(w[i].charAt(j))>=0)

163 | P a g e
c++;
char v[]=new char[c];//to store vowels
for(int j=0;j<w[i].length();j++)
if("AEIOU".indexOf(w[i].charAt(j))>=0)
v[d++]=w[i].charAt(j);//to store vowels
nsen+=String.valueOf(sort(v));//to form the new string
for(int j=0;j<w[i].length();j++)
if("AEIOU".indexOf(w[i].charAt(j))<0)
nsen+=w[i].charAt(j);//storing the consonants
if(i!=w.length-1)
nsen+=" ";
}
System.out.println("Updated sentence="+nsen+l);
}//end of encrypt

char[] sort(char h[])


{
for(int i=0;i<h.length-1;i++)
{
for(int j=0;j<h.length-i-1;j++)
{
if(h[j]>h[j+1])
{
char t=h[j];//creating a temp to swap
h[j]=h[j+1];//swapping if h[j]>h[j+1]
h[j+1]=t;

164 | P a g e
}
}
}
return h;//returning the modified character array
}//end of sort
}//end of class
//Main for Encrypt
class Main_Encrypt
{
public static void main(String args[])
{//start of main
Encrypt ob=new Encrypt();//creating an object of class
ob.accept();//calling the method using the object
ob.encrypt();//calling the method using the object
}//end of main
}//end of class

165 | P a g e
D. OUTPUT: --

166 | P a g e
E. VARIABLE LISTING: --
NAME PURPOSE DATATYPE SCOPE
sen Sentence from user String Encrypt
nsen Updated sentence String Encrypt
l Last character char encrypt
w[] Words String encrypt
c Counter int for loop
d Counter String for loop
i Loop Control int for loop
j Loop control int for loop
h[] Array of vowels char sort

167 | P a g e
t Temporary to swap char for loop
----------------------------------- ***-----------------------------------

ASSIGNMENT 20
DATE: 23.09.22

A. PROGRAM DESCRIPTION: ---


The manager of a company wants to analyse the machine usage from the records to find the
utilization of the machine. He wants to know how long each user used the machine. When the

168 | P a g e
user wants to use the machine he must login to the machine and after finishing the work he must
log off the machine.
Each log record consists of: User identification number.
Login time and date.
Logout time and date.
Time consists of: Hours Minutes
Date consists of: Day Month

You may assume all logins and logouts are in the same year and there are 100 users at the
most. The time format is 24 hour machine hours and minutes.
Design a program: (a) To find the duration for which each user has logged. Output all records
along with the duration in hours (format hours: minutes).
(b) Output the record of the user who logged for the longest duration. You
may assume that no user will login for more than 48 hours. Test your program for the following
data values and some more random data.

SAMPLE DATA:
INPUT: Number of users: 3
USER LOGIN LOGOUT
IDENTIFICATION TIME & DATE TIME & DATE
149 20:10 20-12 2:50 21-12
173 12:30 20-12 12:30 21-12
142 16:20 20-12 16:30 20-12

OUTPUT:
USER LOGIN LOGOUT DURATION
IDENTIFICATION TIME & DATE TIME & DATE HOURS : MINUTES
149 20:10 20-12 2:50 21-12 6:40
173 12:30 20-12 12:30 21-12 24:00
142 16:20 20-12 16:30 20-12 00:10

B. ALGORITHM: --

169 | P a g e
A class is designed with the name Login and private instance variables n, id[], dhr[], dmin[], k,
itime[], idate[], otime[], odate[]
Method get():
STEP 1: Start
STEP 2: Start a do while loop with condition to iterate if n>100 and accept the value of n from
the user within the loop
STEP 3: Call the initial() function
STEP 4: End
Method initial():
STEP 1: Start
STEP 2: Initialize id with n size
STEP 3: Initialize itime with size n
STEP 4: Initialize idate with size n
STEP 5: Initialize otime with size n
STEP 6: Initialize odate with size n
STEP 7: Initialize dhr with size n
STEP 8: Initialize dmin with size n
STEP 9: End
Method input():
STEP 1: Start
STEP 2: Start a loop from i=0 to i<n and i increment by +1 in every iteration
STEP 3: Within loop accept value of position i of array id from user
STEP 4: Within loop accept value of position i of array itime from user
STEP 5: Within loop accept value of position i of array idate from user
STEP 6: Within loop accept value of position i of array otime from user
STEP 7: Within loop accept value of position i of array idate from user
STEP 8: End the loop

170 | P a g e
STEP 9: End
Method duration():
STEP 1: Start
STEP 2: Start a for loop from i=0 to i<n and increment i by +1 in every iteration and within loop
continue from step 3
STEP 3: Declare ic, id, oc, od, ihr, imin, ohr, omin, day, d1, d2
STEP 4: If value of position i of idate array is not equal to that of odate then convert value of
position i of idate to integer and store in d1 and do the same with position i of odate and store in
d2 and store day=(d2-d1)*24
STEP 5: Start an inner for loop from j=0 to j<length of itime[i] and increase j by +1 in every
iteration and continue from step 6
STEP 6: If the character at j of itime[i] is ‘:’ then ic=ic+character at j of itime[i] else
id=id+substring of j+1 of itime[i] and break from the statement and end the inner loop
STEP 7: Convert ic to integer and store in ihr and convert id to integer and store in imin
STEP 8: Start an inner for loop from j=0 to j<length of otime[i] and increase j by +1 in every
iteration and continue from step 9
STEP 9: If the character at j of otime[i] is ‘:’ then oc=oc+character at j of otime[i] else
od=od+substring of j+1 of otime[i] and break from the statement and end the inner loop
STEP 10: Convert oc to integer and store in ohr and convert od to integer and store in omin
STEP 11: ohr=ohr+day
STEP 12: If omin<imin then omin=omin+60 and ohr=ohr-1
STEP 13: If ohr<ihr then ohr=ohr+24
STEP 14: Value of position i of dhr is ohr-ihr
STEP 15: Value of position i of dmin is omin-imin
STEP 16: End the outer loop
STEP 17: End
Method convert() with parameter String arr:
STEP 1: Start
STEP 2: Declare x

171 | P a g e
STEP 3: Start a loop from i=0 to i<length of arr and increment I by +1 in every iteration and
continue from step 4
STEP 4: If character at i of arr is ‘-‘ then x=x+character at i of arr else return x
STEP 5: End the loop
STEP 6: Return “0”
STEP 7: End
Method output():
STEP 1: Start
STEP 2: Start a loop from i=0, i<n and increment i by +1 in every iteration
STEP 3: Print id[i], itime[i], idate[i], otime[i], odate[i], dhr[i], dmin[i] with proper spacing
STEP 4: If dhr[i]>=dhr[k] then k=i
STEP 5: If dhr[k]==dhr[i] and dmin[i]>=dmin[k] then k=i
STEP 6: End the loop
STEP 7: Print id[k], itime[k], idate[k], otime[k], odate[k], dhr[k], dmin[k] with proper spacing
and proper message
STEP 8: End
A class Login_main is designed
Method main():
STEP 1: Start
STEP 2: Create an object ob of Login class
STEP 3: Call get using ob
STEP 4: Call input using ob
STEP 5: Call duration using ob
STEP 6: Call output using ob
STEP 7: End

172 | P a g e
C. SOURCE CODE: --
//Q20 : Log In and Log Out Program
import java.util.*;
class Login
{
Scanner sc=new Scanner(System.in);
private int n,id[],dhr[],dmin[],k=0;
private String itime[],idate[],otime[],odate[];
public void get()
{
do
{
System.out.println("Enter number of users");
n=sc.nextInt();
}while(n>100);//end of while loop
initial();
173 | P a g e
}//end of get()

public void initial()


{
id=new int[n];
itime=new String[n];
idate=new String[n];
otime=new String[n];
odate=new String[n];
dhr=new int[n];
dmin=new int[n];
}//end of initial()

public void input()


{
System.out.println("USER LOGIN LOGOUT");
System.out.println("IDENTIFICATION TIME & DATE TIME & DATE");
for(int i=0;i<n;i++)
{
id[i]=sc.nextInt();
itime[i]=sc.next();
idate[i]=sc.next();
otime[i]=sc.next();
odate[i]=sc.next();
}//end of for loop
}//end of input()

174 | P a g e
public void duration()
{
for(int i=0;i<n;i++)
{
String ic="",id="",oc="",od="";
int ihr=0,imin=0,ohr=0,omin=0,day=0,d1=0,d2=0;
if(idate[i].equals(odate[i])==false)
{
d1=Integer.parseInt(convert(idate[i]));
d2=Integer.parseInt(convert(odate[i]));
day=(d2-d1)*24;
}//end of if
for(int j=0;j<itime[i].length();j++)
{
if(itime[i].charAt(j)!=':')
ic+=itime[i].charAt(j);
else
{
id+=itime[i].substring(j+1);
break;
}//end of else
}//end of inner for loop
ihr=Integer.parseInt(ic);
imin=Integer.parseInt(id);
for(int j=0;j<otime[i].length();j++)

175 | P a g e
{
if(otime[i].charAt(j)!=':')
oc+=otime[i].charAt(j);
else
{
od+=otime[i].substring(j+1);
break;
}//end of else
}//end of for loop
ohr=Integer.parseInt(oc);
omin=Integer.parseInt(od);
ohr+=day;
if(omin<imin)
{
omin+=60;
ohr-=1;
}//end of if
if(ohr<ihr)
ohr+=24;
dhr[i]=ohr-ihr;
dmin[i]=omin-imin;
}//end of for loop
}//end of duration()

public String convert(String arr)


{

176 | P a g e
String x="";
for(int i=0;i<arr.length();i++)
{
if (arr.charAt(i)!='-')
x+=arr.charAt(i);
else
return(x);
}//end of for loop
return("0");
}//end of convert()

public void output()


{
System.out.println("USER LOGIN LOGOUT
DURATION");
System.out.println("IDENTIFICATION TIME & DATE TIME & DATE
HOURS:MINUTES");
for(int i=0;i<n;i++)
{
System.out.println(id[i]+" "+itime[i]+" "+idate[i]+" "+otime[i]+"
"+odate[i]+" "+dhr[i]+":"+dmin[i]);
if(dhr[i]>=dhr[k])
k=i;
if(dhr[k]==dhr[i]&&dmin[i]>=dmin[k])
k=i;
}//end of for loop
System.out.println("THE USER WHO LOGGED IN FOR THE LONGEST DURATION");

177 | P a g e
System.out.println(id[k]+" "+itime[k]+" "+idate[k]+" "+otime[k]+"
"+odate[k]+" "+dhr[k]+":"+dmin[k]);
}//end of output()
}//end of class
class Login_main{
public static void main(String args[])
{
Login ob=new Login();//creating object
//calling methods
ob.get();
ob.input();
ob.duration();
ob.output();
}//end of main()
}//end of Login_main

178 | P a g e
D. OUTPUT: --

179 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
n int class Login Number of Users
id[] int class Login Input Date Array
dhr[] int class Login Hour Array
dmin[] int class Login Minute Array
k int class Login Array element
counter
itime[] String class Login Input Time Array in
String format
idate[] String class Login Input Date Array in
String format
otime[] String class Login Output Time Array
in String format

180 | P a g e
odate[] String class Login Output Date Array
in String format
i, j int for loop Loop Control
ic String for loop To add colon to time
in proper place in
input
id String for loop To add substring of
time in proper place
in input
oc String for loop To add colon to time
in proper place in
output
od String for loop To add substring of
time in proper place
in output
ihr int for loop Hour of input time in
integer format
imin int for loop Minute of input time
in integer format
ohr int for loop Hour of output time
in integer format
omin int for loop Minute of output
time in integer
format
day int for loop Day Number in
integer
d1 int for loop Converting input
date to integer
d2 int for loop Converting output
date to integer
x String convert() Proper format of
date with hyphen
----------------------------------- ***-----------------------------------
ASSIGNMENT 21
DATE: 27.09.22

A. PROGRAM DESCRIPTION: ---


The input in this problem will consist of a number of lines of English text consisting of the letters
of the English alphabet, the punctuation marks (‘) apostrophe, (.) full stop, (,) comma, (;)
181 | P a g e
semicolon, (:) colon and white space characters (blank, newline). Your task is to print the words
of the text in reverse order without any punctuation marks other than blanks. For example
consider the following input text:
This is a sample piece of text to illustrate this problem.
If you are smart you will solve this right.
The corresponding output would read as: right this solve will you smart are you If problem this
illustrate to text of piece sample a is This
Note: That is, the lines are printed in reverse order. Individual words are not reversed
Input format: The first line of input contains a single integer N ( < = 20), indicating the number
of lines in the input. This is followed by N lines of input text. Each line should accept a
maximum of 80 characters.
Output format Output the text containing the input lines in reverse order without punctuation
except blanks as illustrated above.
Test your program for the following data and some random data.
SAMPLE DATA
INPUT:
2
Emotions, controlled and directed to work, is character.
By Swami Vivekananda.
OUTPUT: Vivekananda Swami By character is work to directed and controlled Emotions
INPUT: 1
Do not judge a book by its cover.
OUTPUT: Cover its by book a judge not Do

B. ALGORITHM: --
A class names RevPrint is designed
182 | P a g e
STEP 1: Start
STEP 2: declaration of class variables
STEP 3: End
Method RevPrint()
STEP 1: Start
STEP 2: initilisation of class variables
STEP 3: End
Method input()
STEP 1: start
STEP 2: initialisation of scanner class
STEP 3: taling in number of lines as input from user
STEP 4: taking in input sentences from user inside for loop that will run n number of times as
inpu by the user
STEP 5: method add called to add the sentences as the logic given in the program
STEP 6: the returned words are added in reverse and stored in s1
STEP 7: method print is called with s1 as parameter
STEP 8: end
Method add(…)
STEP 1: start
STEP 2: string array a is initialised to the sixe of the array s2
STEP 3: checking is done to see if the inpit sentence contains any punctuation mark or any space
or not
STEP 4: the words that are separated out by a punction mark or not is stored in array
STEP 5: the words stored in the array is run from behind and concatenated so that all the words
add up in reverse order
STEP 6: the sentence in reverse order is returned
STEP 7: end
Method print
STEP 1: start

183 | P a g e
STEP 2: the sentence is printed
STEP 3: end
Class RPmaincall is designed
STEP 1: start
STEP 2: object lya is created of class RevPrint
STEP 3: object is used to call method input
STEP 4: end

184 | P a g e
C. SOURCE CODE: --
//printing sentence in reverse order
import java.util.*;
class RevPrint
{//start of class
private int n;
private String s;
private String s1;
RevPrint()//constructor method
{
n=0;
s="";
s1="";
}//end of constructor method
void input()//start of method
{
Scanner xy=new Scanner(System.in);
System.out.println();
n=xy.nextInt();//taking input from user
String x[]=new String[n];
for(int i=0;i<n;i++)
{
185 | P a g e
s=new Scanner(System.in).nextLine();//taking input from user using temporary scanner
class
x[i]=add(s);//calling add method
}
for(int i=n-1;i>=0;i--)//loop for adding the words back in reverse order
s1=s1+" "+x[i];
s1=s1.trim();
print(s1);//calling the print function to print the updated sentence
}
String add(String s2)
{//start of method
String a[]=new String[s2.length()];//arrau created to store words in reverse
String q="";
int c=0;
for(int i=0;i<s2.length();i++)
{
if(s2.substring(i,i+1)=="'" || s2.charAt(i)=='.' || s2.charAt(i)==',' || s2.charAt(i)==';' ||
s2.charAt(i)==':' || s2.charAt(i)==' ')
{//checking if the sentence contains any punction marks or space bar
a[c]=q;//putting word in the array
c++;
q="";
}
else
q=q+s2.charAt(i); //joing characters to form word
}
s2="";
for(int i=c-1;i>=0;i--)
s2=s2+" "+a[i];//adding words back in reverse order
186 | P a g e
return s2;//returning back the words in reverse order in form of a sentence
}//end of method
void print(String s5)
{//start of method
System.out.println(s5);//printing the sentence with's sentence in reverse order
}//end of method
}//end of class

//main method for RevPrint


class RPmainCall
{//start of class
public static void main(String args[])
{//start of main method
RevPrint lya=new RevPrint();//object formation of class RevPrint
lya.input();//method calling using object
}//end of main method
}//end of class

187 | P a g e
D. OUTPUT: --

188 | P a g e
189 | P a g e
E. VARIABLE LISTING: --
name datatype scope purpose
n int RevPrint Stores the number of
input from user
s String RevPrint Stores the sentence
given as input from
user
s1 String RevPrint Stores the new
updated sentence
x String input Array to store each
separate words from
the input sentence
i int for Loop counter
variable
i int for Loop counter
variable
a String add Array created to
store words
q String add Stores each word
c int add Counter variable
i int for Loop counter
variable
i int for Loop counter
variable
s2 String add Stores input
sentence
s5 String print Stores parameter
----------------------------------- ***-----------------------------------

190 | P a g e
ASSIGNMENT 22
DATE: 09.11.22

A. PROGRAM DESCRIPTION: ---


A Prime-Adam integer is a positive integer (without leading zeros) which is a prime as well as an
Adam number.
Prime number: A number which has only two factors, i.e. 1 and the number itself.
Example: 2, 3, 5, 7.. etc.
Adam number: The square of a number and the square of its reverse are reverse to each other.
Example: If n=13 and reverse of "n" =31, then, (13)^2 = 169 (31)^2 =961 which is reverse of
169 Thus 13, is an Adam number.
Accept two positive integers m and n, where m is less than n as user input. Display all Prime-
Adam integers that are in the range between m and n (both inclusive) and output them along with
the frequency, in the format given below:
Test your program with the following data and some random data:
Example 1 INPUT: m=5 n=100
OUTPUT: THE PRIME-ADAM INTEGERS ARE:11 13 31
FREQUENCY OF PRIME-ADAM INTEGERS IS:3
Example 2 INPUT: m=100 n= 200
OUTPUT: THE PRIME-ADAM INTEGERS ARE:101 103 113
FREQUENCY OF PRIME-ADAM INTEGERS IS:3
Example 3 INPUT:m= 50 n = 70
OUTPUT: THE PRIME-ADAM INTEGERS ARE:NIL

191 | P a g e
FREQUENCY OF PRIME-ADAM INTEGERS IS:0
Example 4 INPUT: m=700 n =450
OUTPUT: INVALID INPUT.

B. ALGORITHM: --
A class is designed with the name PrimeAdam
Method accept():
Step 1:Start
Step 2:Declare variables named m and n
Step 3:Declare a scanner class
Step 4:Display “m=”
Step 5:Take input from the user and store it in the variable named m
Step 6:Display “n=”
Step 7: Take input from the user and store it in the variable named n
Step 8:If the value stored in m and n is negative or zero or the value of m is greater than n then
go to step 4 else go to step 9
Step 9:Declare a variable named s and initialized to 0
Step 10:Display “Prime Adam numbers are:”
Step 11:Declare a for loop with i as its counter variable initialized to m and final value less than
or equal to n
Step 12:Pass i through a the method isPrime() and if the number is prime then go to step 13 else
go to step 15

192 | P a g e
Step 13:Pass i through the method isAdam() and if it is adam number then go to step 14 else go
to step 15
Step 14:Display the value stored in i and increase the value of s by 1
Step 15:Increase the value of i by 1
Step 16:Display “Frequency of prime adam numbers” along with the value stored in s
Step 17:End
Method isPrime(int a):
Step 1:Start
Step 2:Declare a variable named c and initialize it to 0
Step 3:Declare a for loop with i as its counter variable initialized to 1 and final value less than or
equal to a
Step 4:If a is divisible by i then increase the value of c by 1 else go to step 5
Step 5:Increase the value of i by 1
Step 6:If the value in c is equal to 2 then return true and go to step 7 else return false and go to
step 7
Step 7:End
Method isAdam(int a):
Step 1:Start
Step 2:Store the reverse of the number a in a variable named b
Step 3:If the square of the number stored in a and the reverse digit obtained after squaring the
number stored in b then return true and go to step 4 else return false and go to step 4
Step 4:End
Method reverse(int x):
Step 1:Start
Step 2:Declare a variable named n and initialize x to it and another variable named s and
initialize it to 0
Step 3:Declare a while loop with the condition being n greater than 0
Step 4:Declare a variable named y and store the last digit extracted in it

193 | P a g e
Step 5:Store the some of y and the product of s multiplied by 10 in s only
Step 6:Store the remainder of n divided by 10 in n only and go to step 3
Step 7:Return the value stored in s
Step 8:End
A class is declared with the name PrimeAdamMain
Method main():
Step 1:Start
Step 2:Create an instance of the class PrimeAdam
Step 3:Call the method accept()
Step 4:End

C. SOURCE CODE: --
//Q22 : Prime Adam Number
import java.util.*;
class PrimeAdam{
void accept(){//to accept data from user
int m,n;
Scanner sc=new Scanner(System.in);
System.out.print("m=");
m=sc.nextInt();
System.out.print("n=");
194 | P a g e
n=sc.nextInt();
if(m<=0 || n<=0 || m>=n){
System.out.println("INVALID INPUT");
System.exit(0);
}//invalid check
int s=0;
System.out.print("Prime Adam numbers are:");
for(int i=m;i<=n;i++){
if(isPrime(i)){
if(isAdam(i)){
System.out.print(i+" ");
s++;
}
}
}
if(s==0)
System.out.print("NIL");//if no primeadams are present
System.out.println();
System.out.println("Frequency of prime adam numbers is:"+s);
}//end of accept()
boolean isPrime(int a){//to check whether number is prime or not
int c=0;
for(int i=1;i<=a;i++){
if(a%i==0)
c++;
}

195 | P a g e
if(c==2)
return true;
else
return false;
}//end of isPrime()
boolean isAdam(int a){//to check adam number or not
int b=reverse(a);
if((a*a)==reverse(b*b))
return true;
else
return false;
}//end of isAdam()
int reverse(int x){//to reverse the number
int n=x,s=0;
while(n>0){
int y=n%10;
s=s*10+y;
n/=10;
}
return s;
}//end of reverse
}//end of class

class PrimeAdamMain{
public static void main (String args[]){//main method to create object and call methods

196 | P a g e
PrimeAdam ob=new PrimeAdam();
ob.accept();
}//end of main()
}//end of main class

197 | P a g e
D. OUTPUT: --

198 | P a g e
E. VARIABLE LISTING: --
Variable name Datatype Scope Purpose of the
variable
m int accept() To accept the
lower limit for
the range
n int accept() To accept the
upper limit for
the range
i int for() Loop counter
s int accept(),reverse() As a counter as
well as for
calculation
purpose
c int isPrime() Counter purpose
a int isAdam() As a formal
parameter for
calculation
b int isAdam() Checking purpose
x int reverse() As a formal
parameter for
calculation
n int reverse() As a substitute
variable for x
y int while() Calculation
purpose
----------------------------------- ***-----------------------------------
199 | P a g e
ASSIGNMENT 23
DATE: 16.08.22

A. PROGRAM DESCRIPTION: ---


Write a program to accept a paragraph containing TWO sentences only. The sentences may be
terminated by either „.‟, „?‟ or „!‟ only. Any other character may be ignored. The words are to
be separated by a single blank space and must be in UPPER CASE.
Perform the following tasks: (a) Check for the validity of the accepted paragraph for the number
of sentences and for the terminating character. (b) Separate the two sentences from the paragraph
and find the common words in the two sentences with their frequency of occurrence in the
paragraph. (c) Display both the sentences separately along with the common words and their
frequency, in the format given below:
Example 1 INPUT: IS IT RAINING? YOU MAY GET WET IF IT IS RAINING.
OUTPUT: IS IT RAINING?
YOU MAY GET WET IF IT IS RAINING.
COMMON WORDS FREQUENCY
IS 2
IT 2
RAINING 2
200 | P a g e
Example 2 INPUT: INDIA IS MY MOTHERLAND AND I AM PROUD OF MY
MOTHERLAND. ALL INDIANS ARE MY BROTHERS AND SISTERS.
OUTPUT: INDIA IS MY MOTHERLAND AND I AM PROUD OF MY MOTHERLAND.
ALL INDIANS ARE MY BROTHERS AND SISTERS.
COMMOM WORDS FREQUENCY
MY 3
AND 2
Example 3 INPUT: ARE YOU COMING? I AM GETTING LATE.
OUTPUT: ARE YOU COMING?
I AM GETTING LATE.
NO COMMON WORDS
Example 4 INPUT: AT LAST, THE TIGER WAS SAVED.
OUTPUT: INVALID INPUT

B. ALGORITHM: --
A class is designed with the name CommonWords.

Method accept():

Step 1: Start

Step 2: Using Scanner class to take the paragraph as input and storing it in variable s.

Step 3: Initializing two variables c and b with the value 0.

Step 4: A for loop is declared with loop variable i starting with 0 to (length of the paragraph -2)
with increment of 1.

Step 5: if the i th character of the string is “./!/?” then the counter c is incremented by 1 and d is
given the value of i.

Step 6: If the paragraph does not end with “./!/?” or if c is not equal to 1 then the input is invalid.

Step 7: The two sentences of the paragraph is displayed using substring.


201 | P a g e
Step 8: The two sentences are concatenated to form a new string s1.

Step 9: Using split function the words of the string s1 are put in a String array w.

Step 10: An integer array fr is declared with size same as the length of the array w.

Step 11: An integer variable v is declared with value -1.

Step 12: A for loop is declared with loop variable i starting with 0 and less than length of w with
increment of 1.

Step 13: The variable c is initialized to 1.

Step 14: A for loop is declared with loop variable j starting with (i+1) and less than length of w
with increment of 1.

Step 15: If the j th word and the i th word are equal then the c is incremented by 1 and v is stored
in j th position of fr.

Step 16: If the i th element of fr is not equal to v then the i th element of fr stores the value of c.

Step 17: A for loop is declared with loop variable i starting with 0 and less than length of fr with
increment of 1.

Step 18: If the i th element of fr not equals v and i th element of fr is greater than 1 then i th
element of w and fr is printed.

Step 19: End

A class is designed with the name Main_CommonWords


Method main(String args[]):
Step 1: Start
Step 2: Create an object ob of CommonWords class.
Step 3: Call accept() using ob.
Step 4: End

202 | P a g e
C. SOURCE CODE: --
//Q23_Common words
import java.util.*;
class CommonWords
{
void accept()
{//start of accept
String s=new Scanner(System.in).nextLine();
int c=0,d=0;
203 | P a g e
for(int i=0;i<s.length()-2;i++)
{
if(".!?".indexOf(s.charAt(i))>=0)
{
c++;
d=i;
}
}
if(".?!".indexOf(s.charAt(s.length()-1))<0 || c!=1)
{
System.out.println("INVALID PARAGRAPH");
System.exit(0);
}
System.out.println(s.substring(0,d+1));//printing first sentence
System.out.println(s.substring(d+2,s.length()));//printing second sentence
String s1=s.substring(0,d).trim()+" "+s.substring(d+2,s.length()-1).trim();//concatening the
two paragraphs
String w[]=s1.split(" ");
int fr[]=new int[w.length];//to store frequency
System.out.println("COMMON WORDS\t\t\t\t\tFREQUENCY");
int v=-1;
for(int i=0;i<w.length;i++)
{
c=1;
for(int j=i+1;j<w.length;j++)
if(w[i].equals(w[j]))//to check frequency
{
204 | P a g e
c++;
//To avoid counting same element again
fr[j] = v;
}
if(fr[i]!=v)
fr[i]=c;
}//end of outer for
for(int i=0;i<fr.length;i++){
if(fr[i]!=v && fr[i]>1)//if frequency greater than 1 then displaying
System.out.println(" " + w[i] + " \t\t\t\t\t " + fr[i]);
}
}//end of accept
}//end of class
//Main for CommonWords
class Main_CommonWords
{
public static void main(String args[])
{//start of main
CommonWords ob=new CommonWords();//creating an object of class
ob.accept();//calling the method using the object
}//end of main
}//end of class

D. OUTPUT: --

205 | P a g e
206 | P a g e
E. VARIABLE LISTING: --
NAME PURPOSE DATATYPE SCOPE
s Paragraph from user String accept()
c Counter int accept()
j Loop control int for loop
i Loop Control int for loop
w[] To store words String accept()
fr[] Frequency of words int accept()
v To store visited int accept()

----------------------------------- ***-----------------------------------

207 | P a g e
ASSIGNMENT 24
DATE: 21.11.22

A. PROGRAM DESCRIPTION: ---


A Fascinating number is one which when multiplied by 2 and 3 and then, after the results are
concatenated with the original number, the new number contains all the digits from 1 to 9 exactly
once. There can be any number of zeros and are to be ignored.

Example: 273

273 x 1 = 273
273 x 2 = 546
273 x 3 = 819

Concatenating the results we get, 273546819 which contains all digits from 1 to 9 exactly once.
Thus, 273 is a Fascinating number.

Accept two positive integers m and n, where m must be less than n and the values of both „m‟
and „n‟ must be greater than 99 and less than 10000 as user input. Display all Fascinating
numbers that are in the range between m and n (both inclusive) and output them along with the
frequency , in the format given below:
Test your program with the following data and some random data:
Example 1 INPUT m = 100 n = 500
OUTPUT: THE FASCINATING NUMBERS ARE:
192 219 273 327
FREQUECNY OF FASCINATING NUMBERES IS: 4
Example 2 INPUT m = 900 n = 5000

208 | P a g e
OUTPUT: THE FASCINATING NUMBERS ARE:
1902 1920 2019 2190 2703 2730 3027 3270
FREQUECNY OF FASCINATING NUMBERES IS: 8
Example 3 INPUT m = 400 n = 900
OUTPUT: THE FASCINATING NUMBERS ARE:
NIL
FREQUECNY OF FASCINATING NUMBERES IS: 0

B. ALGORITHM: --
A class is declared with the name Fascinating
Method accept():
Step 1:Start
Step 2: Declare variables named m and n
Step 3:Declare a scanner class
Step 4:Display “m=”
Step 5:Take input from the user and store it in the variable named m
Step 6:Display “n=”
Step 7: Take input from the user and store it in the variable named n
Step 8:If the value stored in m and n is negative or zero or the value of m is greater than n then
go to step 4 else go to step 9
Step 9:Declare a variable named s and initialized to 0
Step 10:Display “Fascinating numbers are:”
Step 11:Declare a for loop with i as its counter variable initialized to m and final value less than
or equal to n
Step 12:Pass i through a the method isFascinating() and if the number is Fascinating then go to
step 13 else go to step 15

209 | P a g e
Step 13: Display the value stored in i and increase the value of s by 1
Step 14:Increase the value of i by 1
Step 15:Display “Frequency of Fascinating numbers” along with the value stored in s
Step 16:End
Method isFascinating(int a):
Step 1:Start
Step 2:Declare a variable named multiply2 and store the product of 2 multiplied with the number
stored in a
Step 3: Declare a variable named multiply2 and store the product of 2 multiplied with the
number stored in a
Step 4: Declare a variable named multiply3 and store the product of 3 multiplied with the
number stored in a
Step 5:Declare a variable named str and store the number itself as well as the value stored in
multiply2 and multiply3 in a string format by concatenating them
Step 6:Declare a for loop with character variable ch initialized to ‘1’ and final value less than or
equal to ‘9’
Step 7:Declare a variable named count initialized to 0
Step 8:Declare a variable named i and final value less than the length of the string str
Step 9:Declare another character variable named ch2 and extract each character starting from the
1st index itself
Step 10:If the character in ch as well as in ch2 are equal then increase the value of count by 1
else go to step 11
Step 11:Increase the value of i by 1
Step 12:If the value in count is greater than 1 or equal to 0 then return false and go to step 15 else
go to step 13
Step 13:Increase the value of ch by 1
Step 14:Return true
Step 15:End
A class is declared with the name FascinatingMain

210 | P a g e
Method main():
Step 1:Start
Step 2:Create an instance of the class Fascinating
Step 3:Call the method accept()
Step 4:End

C. SOURCE CODE: --
//Q24 : Fascinating Number
import java.util.*;
class Fascinating{
void accept(){//to accept data from user
int m,n;
Scanner sc=new Scanner(System.in);
do{
System.out.print("m=");
m=sc.nextInt();
211 | P a g e
System.out.print("n=");
n=sc.nextInt();
}while(m<=0 || n<=0 || m>=n);//invalid check
int s=0;
System.out.print("Fascinating numbers are:");
for(int i=m;i<=n;i++){
if(isFascinating(i)){
System.out.print(i+" ");
s++;
}
}
if(s==0)
System.out.print("NIL");//if no fascinating numbers found
System.out.println();
System.out.println("Frequency of Fascinating numbers is:"+s);
}//end of accept()
boolean isFascinating(int a){//to check fascinating or not
int multiply2 = a * 2;
int multiply3 = a * 3;
String str = a+""+multiply2+multiply3;
for(char ch = '1'; ch <= '9'; ch++){
int count = 0;
for(int i = 0; i < str.length(); i++){
char ch2 = str.charAt(i);
if(ch2 == ch)
count++;

212 | P a g e
}
if(count > 1 || count == 0)
return false;
}
return true;
}//end of isFascinating
}//end of class
class FascinatingMain{
public static void main(String args[]){//main method to create object and call methods
Fascinating ob=new Fascinating();
ob.accept();
}//end of main
}//end of main class

D. OUTPUT: --

213 | P a g e
214 | P a g e
E. VARIABLE LISTING: --
Variable name Datatype Scope Purpose of the
variable
m int accept() To accept the
lower limit for
the range
n int accept() To accept the
upper limit for
the range
i int for() Loop counter
s int accept() As a counter as
well as for
calculation
purpose
multiply2 int isFascinating() To store the
product of 2 and
the number
multiply3 int isFascinating() To store the
product of 2 and
the number
str int isFascinating() To store the
concatenation
together in str
ch char for() Loop counter
count int for() Occurrence
counter
ch2 char for() Character
extracter
----------------------------------- ***-----------------------------------

215 | P a g e
ASSIGNMENT 25
DATE: 05.12.22

A. PROGRAM DESCRIPTION: ---


A mathematician who is working with extremely large integers them using a Single linked list.
For example, the number 7328 will be represented as the single linked list with four nodes, 7 3 2
8 The successor of the last node are null. Write a program that reads in two numbers (assume
they are integers for testing), converts them to the above representation, prints them out with
each digit separated by commas and checks whether the two numbers are equal or not. The
equality check should work on the representation and not on the integers. Here are sample
outputs.
Sample data:
Input:
Give the first number:34563
Give the second number:34562
Output:
First number:3,4,5,6,3
Second number:3,4,5,6,2
Unequal
Input:
Give the first number:56432
Give the second number:56432
Output:
First number:5,6,4,3,2
216 | P a g e
Second number:5,6,4,3,2
Equal

B. ALGORITHM: --
A class is designed with the name Node and protected instance variables data and link of Node
type
Method Node():
STEP 1: Start
STEP 2: Assign link=null, data=0
STEP 3: End
Method Node(int d, Node n):
STEP 1: Start
STEP 2: Assign data=d, link=n
STEP 3: End
Method setLink(Node n):
STEP 1: Start
STEP 2: Assign link=n
STEP 3: End
Method setData(int d):
STEP 1: Start
STEP 2: Assign data=d

217 | P a g e
STEP 3: End
Method getLink():
STEP 1: Start
STEP 2: return link
STEP 3: End
Method getData():
STEP 1: Start
STEP 2: return data
STEP 3: End
A class is designed with the name linkedList and protected instance variable start and st
Method linkedList():
STEP 1: Start
STEP 2: Assign start=null
STEP 3: End
Method isEmpty():
STEP 1: Start
STEP 2: Return start if start is null
STEP 3: End
Method Insert(int val):
STEP 1: Start
STEP 2: Declare nptr, ptr, save of Node type and assign save=null
STEP 3: Assign nptr by calling Node using val and null as parameters
STEP 4: Declare and assign ins=false
STEP 5: If start=null then start=nptr else call setLink() of nptr using start as parameter and then
start=nptr
STEP 6: End
Method print_num():
218 | P a g e
STEP 1: Start
STEP 2: Call print_num using start as parameter
STEP 3: If start not equal to null, print substring of st from position 2
STEP 4: End
Method print_num(Node head):
STEP 1: Start
STEP 2; If head not equal to null, st=st+”,”+getData() of head and call print_num() using
getLink() of head
STEP 3: End
Method getSize(Node a):
STEP 1: Start
STEP 2: Initialize sz
STEP 3: Start a while loop with condition to iterate if a not equal to null and continue from step
4:
STEP 4: Assign a as link of a and increase sz by +1
STEP 5: Outside the loop, return sz
STEP 6: End
Method push(Node head_ref, int new_data):
STEP 1: Start
STEP 2: Create object new_node of Node class
STEP 3: Assign data of new_node as new_data
STEP 4: Assign link of new_node as head_ref
STEP 5: head_ref=new_node
STEP 6: return head_ref
STEP 7: End
Method compare(Node a, Node b):
STEP 1: Start

219 | P a g e
STEP 2: Assign lenA by calling getSize() with parameter a
STEP 3: Assign lenB by calling getSize() with parameter b
STEP 4: If lenA>lenB return 1 else if lenB>LenA return -1
STEP 5: Start a while loop with condition to iterate if a not equal to null and b not equal to null
and continue from Step 6
STEP 6: If data of a>data of b then return 1 else if data of a<data of b then return -1 and set
a=link of a and b=link of b
STEP 7: Outside loop, return 0
STEP 8: End
A class is designed with the name Main and protected instance variables S and S1 of linkedList
type
Method main():
STEP 1: Start
STEP 2: Initialize num
STEP 3: Assign S as an object of linkedList()
STEP 4: Accept num from user and keep a copy of it in c and declare dig
STEP 5: Start a while loop condition num>0 to iterate and continue from step 6
STEP 6: dig=num mod 10, divide num by 10 and store it in num and call Insert of S using dig as
parameter and end the loop
STEP 7: Initialize num2
STEP 3: Assign S1 as an object of linkedList()
STEP 4: Accept num2 from user and keep a copy of it in c2 and declare dig2
STEP 5: Start a while loop condition num2>0 to iterate and continue from step 6
STEP 6: dig2=num mod 10, divide num2 by 10 and store it in num2 and call Insert of S1 using
dig2 as parameter and end the loop
STEP 7: Call print_num of S and print_num of S1 in consecutive lines
STEP 8: Declare Node a=null
STEP 9: Assign S as an object of linkedList()

220 | P a g e
STEP 10: Start a while loop with condition c>0 to iterate and within, a=push of S with a and c
mod 10 as parameters and divide c by 10
STEP 11: Declare Node b=null
STEP 12: Start a while loop with condition c2>0 to iterate and within, b=push of S with b and c2
mod 10 as parameters and divide c2 by 10
STEP 13: If compare of S with parameters a and b equals 0 then print “Equal” else print
“Unequal”
STEP 14: End

C. SOURCE CODE: --
//Q25 : Mathematician

221 | P a g e
class Node{
//nodal class
protected int data;
protected Node link;
public Node(){//creating node
link=null;
data=0;
}//end of Node()

public Node(int d, Node n){//data and link of node


data = d;
link = n;
}//end of Node()

public void setLink(Node n){//setting the link to node


link =n;
}//end of setLink()

public void setData(int d){//setting the data to node


data=d;
}//end of setData()

public Node getLink(){//returns the node link


return link;
}//end of getLink()

222 | P a g e
public int getData(){//returns the node data
return data;
}//end of getData()

}//end of Node class


class linkedList{
//linked list class
protected Node start;
protected String st=" ";
public linkedList(){//initialise start
start=null;
}//end of linkedList()

public boolean isEmpty(){//to check start is null or nor


return start==null;
}//end of isEmpty()

public void Insert(int val){//to insert values to linked list


Node nptr, ptr, save=null;
nptr=new Node(val,null);
boolean ins=false;
if(start==null)
start=nptr;
else{
nptr.setLink(start);
start=nptr;

223 | P a g e
}
}//end of Insert()

public void print_num(){//printing start


print_num(start);
if(start!=null)
System.out.print(st.substring(2));
}//end of print_num()

private void print_num(Node head){//to print all numbers in linked list


if(head!=null){
st=st+","+(head.getData());
print_num(head.getLink());
}
}//end of print_num()

int getSize(Node a)
{//to calculate the size of the linked list
int sz = 0;
while (a != null)
{
a = a.link;
sz++;
}
return sz;
}//end of getSize()

224 | P a g e
Node push(Node head_ref, int new_data)
{//to push values to the linked
Node new_node = new Node();//alocating node
new_node.data = new_data;//setting the data
new_node.link = head_ref;//Link the old list after the new node
head_ref = new_node;//Set the head to point to the new node
return head_ref;
}//end of push()

int compare(Node a,Node b)


{//to compare the two numbers
int lenA = getSize(a);
int lenB = getSize(b);
if (lenA > lenB)
{//check for lengths of number
return 1;
}
else if (lenB > lenA)
{//check for lengths of number
return -1;
}
while (a != null && b != null)
{//comparing when lengths are equal
if (a.data > b.data)
return 1;

225 | P a g e
else if (a.data < b.data)
return -1;
a = a.link;
b = b.link;
}
return 0;//returns zero when linked lists are equal
}//end of compare()
}//end of linkedList class
import java.util.*;
class Main{
//Main class to drive the program
protected static linkedList S;
protected static linkedList S1;
public static void main(String args[]){//main methods
int num;
S=new linkedList();
Scanner sc=new Scanner(System.in);
System.out.print("Give the first number: ");
num=sc.nextInt();
int c=num;
int dig=0;
while(num>0){//taking out digits of numbers and putting in linked list
dig=num%10;
num/=10;
S.Insert(dig);
}

226 | P a g e
int num2;
S1=new linkedList();
System.out.print("Give the second number: ");
num2=sc.nextInt();
int c2=num2;
int dig2=0;
while(num2>0){//taking out digits of numbers and putting in linked list
dig2=num2%10;
num2/=10;
S1.Insert(dig2);
}
System.out.print("First number: ");
S.print_num();
System.out.println();
System.out.print("Second number: ");
S1.print_num();
Node a = null;
S=new linkedList();
while(c>0){//pushing in linked list
a = S.push(a, c%10);
c/=10;
}
Node b = null;
while(c2>0){//pushing in linked list
b = S.push(b, c2%10);
c2/=10;

227 | P a g e
}
System.out.println();
if((S.compare(a, b))==0)//comparing the numbers
System.out.println("Equal");
else //comparing the numbers
System.out.println("Unequal");
}//end of main()
}//end of Main class

D. OUTPUT: --

228 | P a g e
229 | P a g e
E. VARIABLE LISTING: --
NAME DATATYPE SCOPE PURPOSE
data int Node class Data of linked list
d int Node() Parameter
d int setData() Parameter
st String linkedList To store the numbers
in string form with
commas
ins boolean Insert() To check true or false
sz int getSize() To get the size of the
linked list
lenA int compare() Length of first
number
lenB int compare() Length of second
number
num int main() First number

num2 int Second Number


c int main() Copy of first number

dig int main() Digits of 1st number


c2 int main() Copy of second
number
dig2 int main() Digits of 2nd number

----------------------------------- ***-----------------------------------

230 | P a g e

You might also like