0% found this document useful (0 votes)
20 views97 pages

Xii Comp Project Isc Final

The document outlines computer assignments for students Kamalika Sen and Suchana Bhattacharya from St. Xavier’s Institution, focusing on various sorting algorithms and data structures in Java. It includes detailed instructions for implementing Bubble Sort, Selection Sort, and Insertion Sort, along with class structures, methods, and sample outputs. Additionally, it describes the Mid Sort technique and other related programming tasks for the ISC 2025 curriculum.

Uploaded by

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

Xii Comp Project Isc Final

The document outlines computer assignments for students Kamalika Sen and Suchana Bhattacharya from St. Xavier’s Institution, focusing on various sorting algorithms and data structures in Java. It includes detailed instructions for implementing Bubble Sort, Selection Sort, and Insertion Sort, along with class structures, methods, and sample outputs. Additionally, it describes the Mid Sort technique and other related programming tasks for the ISC 2025 curriculum.

Uploaded by

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

St.

Xavier’s Institution, Panihati

ISC – 2025

COMPUTER ASSIGNMENT COPY


NAME: KAMALIKA SEN
SUCHANA BHATTACHARYA
CLASS: XII -C
XII-F
ROLL NO.: 14
48
UNIQUE ID: 7770923
7770976
SESSION: 2024-25
INDEX

Sl. No. Name Page Number


1 Bubble sort, Binary search – 1D Array 2–5
2 Selection Sort – 1D Array 6–8
3 Insertion Sort – 1D Array 9 – 12
4 Mid Sort – 1D Array 13 – 16
5 Stack – 1D Array 17 – 21
6 Queue – 1d Array 22 – 27
7 ISC Scores - Inheritance 28 – 32
8 Simple, Compound - Inheritance 33 – 37
9 Array transpose and symmetric - 2D Array 38 – 41
10 Amount - Object passing 42 – 44
11 Time - Object Passing 45 – 46
12 binadd - Object passing 47 – 49
13 Prime Adam Number 50 – 53
14 Gold Bach Number 54 – 56
15 Matrix Multiplication - 2D Array 57 – 60
16 Matrix Rotate - 2D Array 61 – 64
17 Panagram - String 65 – 68
18 No. of Days elapsed - Date 69 – 72
19 frequencyVowelsInSentence - String 73 – 74
20 Keystrokes - String 75 – 77
21 Unique Digit - Number 78 – 80
22 Matrix - 2D Array 81 – 85
23 Anagram - String 86 – 87
24 Shape - Interface 88 – 90
25 Recycle - Dequeue - 1D Array 91 – 96

1
QUESTION 1:

Design a class Binary_Search to sort a given array using Bubble Sort technique and search an
accepted element using Binary Search technique. A main class is to be created to give details of
the constructors and the member methods.
Data Members – int n -> To store the array size.
int sno -> To store the number to be searched.
int ar[] -> To store array elements.
Member Methods –
Binary_Search() -> To initialize all the data members to 0.
void accept() -> To store the size of the array and the elements of the array.
void Bubble_Sort() -> To sort the array using bubble sort technique.
void binary_search() -> To accept the user given number and search it using the binary search
technique.
void display() -> display the array.

The program will display the unsorted array as well as the sorted array.

//Algorithm
Step 1: Initialize variables n (array size) and sno (search number) to zero.
Declare an integer array ar to store the elements.
Step 2: Create a Scanner object sc to take user input.
Step 3: Method accept() : Prompt the user to enter the size of the array, and store it in n.
Initialize ar as an integer array of size n.
Step 4: Loop from 0 to n-1 to accept array elements from the user, and store each element in
ar[i].
Step 5: Method Bubble_Sort():
Step 6: Loop from 0 to n-2 with index i.
Step 7: For each i, loop from 0 to n-2-i with index j.
Step 8: If ar[j] is greater than ar[j+1], swap ar[j] and ar[j+1] to sort in ascending order. Print the
sorted array.
Step 9: Method binary_search(): Prompt the user to enter the number to search (sno).
Step 10: Initialize min to 0, max to n-1, mid to 0, and p (position indicator) to -1.
Step 11: While min is less than or equal to max and p is -1:
Step 12: Set mid as (min + max) / 2.
Step 13: If ar[mid] equals sno, set p to mid.
Else if ar[mid] is greater than sno, set max to mid - 1.
Else, set min to mid + 1.
Step 14: If p is not -1, print the position of sno as p + 1.
If p remains -1, print "NOT FOUND."
Step 15: Main Method (main):Create an instance ob of Bubble_Binary.
Step 16: Call accept() to input the array.

2
Step 17: Call Bubble_Sort() to sort the array.
Step 18: Call binary_search() to perform binary search on the sorted array.

//Program Code
import java.util.*;
class Bubble_Binary
{
int n,sno;
int ar[];
Scanner sc=new Scanner(System.in);
Bubble_Binary()
{
n=sno=0;
}

void accept()
{
System.out.println("ENTER SIZE OF THE ARRAY");
n=sc.nextInt();
ar=new int[n];
System.out.println("ENTER ARRAY ELEMENTS");
for(int i=0;i<n;i++) //accepting values from user
ar[i]=sc.nextInt();
}

void Bubble_Sort()
{
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(ar[j]>ar[j+1]) //sorting in ascending order
{
int t=ar[j];
ar[j]=ar[j+1];
ar[j+1]=t;
}
}
}
System.out.println("THE SORTED ARRAY IS:-");
for(int i=0;i<n;i++)
System.out.println(ar[i]);
}

3
void binary_search()
{
System.out.println("ENTER NUMBER TO BE SEARCHED");
sno=sc.nextInt();
int min=0,max=(n-1),mid=0,p=-1;
while(min<=max && p==-1) //searching the user given number
{
mid=(min+max)/2;
if(ar[mid]==sno)
p=mid;
else if(ar[mid]>sno)
max=mid-1;
else
min=mid+1;
}
if(p!=-1)
System.out.println("YES. THE POSITION IS "+(p+1));
else
System.out.println("NOT FOUND");
}

public static void main()


{
Bubble_Binary ob=new Bubble_Binary();
ob.accept();
ob.Bubble_Sort();
ob.binary_search();
} //end of main
} //end of class

Sample output
ENTER SIZE OF THE ARRAY
5
ENTER ARRAY ELEMENTS
11
33
22
66
55
THE SORTED ARRAY IS:-
11
22

4
33
55
66
ENTER NUMBER TO BE SEARCHED
55
YES. THE POSITION IS 4

//Variable description
Name Type Purpose
n int To store size of array
sno int To store the number to be searched

ar[] int To store array elements


mid int Mid position to search
max int Max position
min int Min position
p int Position where number found

Signature of Teacher

5
QUESTION 2:
Design a class “Selection_Sort” that inputs array from the user and sort it in ascending order
using selection sort technique. A class is declared to give the details of the constructor and
member methods.
Data Members –
int ar[] -> Integer array to store array members.
int n -> To store the length of the array.
Member Methods –
Selection_Sort() -> Constructor to initialize n to 0.
void readlist() -> To accept value of n and array elements from user.
int Index_Of_Min(int startindex) -> Return the index position of the smallest value.
void sort() -> To sort the array in ascending order using selection sort technique.
void display() -> To display the sorted array.

//ALGORITHM
STEP 1: Class Initialization (Selection_Sort)
STEP 2: Initialize an integer array ar and an integer n (to store the array size).
Create a Scanner object sc to take user input.
STEP 3: Method read_list(): Prompt the user to enter the size of the array, and store it in n.
STEP 4: Initialize ar as an integer array of size n.
STEP 5: Loop from 0 to n-1 to accept array elements from the user, storing each element in
ar[i].
STEP 6: Method Index_Of_Min(int startindex): Initialize p to startindex.
STEP 7: Loop from startindex + 1 to n - 1 with index j.
STEP 8: If ar[j] is less than ar[p], set p to j.
STEP 9: Return p, the index of the minimum element starting from startindex.
STEP 10: Method sort(): Loop from 0 to n - 1 with index i.
STEP 11: Call Index_Of_Min(i) to find the index of the minimum element starting from i, storing
the result in x.
STEP 12: Swap ar[i] with ar[x] to place the smallest element at the beginning of the unsorted
portion of the array.
STEP 13: Method display(): Print "THE SORTED ARRAY IS:-".
STEP 14: Loop through each element in ar and print it to display the sorted array.
STEP 15: Main Method (main): Create an instance ob of Selection_Sort.
STEP 16: Call read_list() to input the array.
STEP 17: Call sort() to sort the array using selection sort.
STEP 18: Call display() to print the sorted array.

6
//Program Code
import java.util.*;
class Selection_Sort
{
int ar[],n;
Scanner sc=new Scanner(System.in);
Selection_Sort()
{ n=0;}

void read_list() //initializing variables


{
System.out.println("ENTER SIZE OF THE ARRAY");
n=sc.nextInt(); ar=new int[n];
System.out.println("ENTER ARRAY ELEMENTS");
for(int i=0;i<n;i++)
ar[i]=sc.nextInt();
}

int Index_Of_Min(int startindex) //finding index position of smallest element


{
int p=startindex;
for(int j=startindex+1;j<n;j++)
{
if(ar[j]<ar[p])
p=j;
}
return p;
}

void sort()
{
for(int i=0;i<n;i++) // swapping the variables
{
int x=Index_Of_Min(i);
int t=ar[i];
ar[i]=ar[x];
ar[x]=t;
}
}

void display()
{
System.out.println("THE SORTED ARRAY IS :-");

7
for(int i=0;i<n;i++)
System.out.println(ar[i]);
}

public static void main()


{
Selection_Sort ob=new Selection_Sort();
ob.read_list();
ob.sort();
ob.display();
} //end of main
} //end of class

// Output
ENTER SIZE OF THE ARRAY
5
ENTER ARRAY ELEMENTS
33
22
44
11
66
THE SORTED ARRAY IS :-
11
22
33
44
66

// Variable description
Name Type Purpose

ar[] int To store array elements.


n int To store array length.
t int Temporary variable
x int Return of minimum number
i int Loop Variable
j int Loop Variable

Signature of Teacher

8
QUESTION 3:
Design a class Insertion_Sort that inputs an array from the user and sorts it in ascending order
using Insertion Sort technique. A main class is created to give details of the constructor and the
member methods.
Data Members – int ar[] -> Integer array to store numbers.
int l -> To store array length.
Member Methods –
Insertion_Sort() -> A constructor to initialize data members to 0.
void input() -> To input the array from the user and store it in ar[].
void sort() -> To sort ar[] in ascending order.
void display() -> To display the sorted array.

//Algorithm
STEP 1: class Initialization (Insertion_sort) : Initialize an integer array ar and an integer n (to
store the array size).
Create a Scanner object sc to take user input.
STEP 2: Method accept() : Prompt the user to enter the size of the array, and store it in n.
STEP 3: Initialize ar as an integer array of size n.
STEP 4: Loop from 0 to n-1 to accept array elements from the user, storing each element in
ar[i].
STEP 5: Method display1() : Print "ORIGINAL ARRAY IS:".
STEP 6: Loop through each element in ar and print it to display the original array.
STEP 7: Method sort() : Loop from 1 to n-1 with index i.
STEP 8: Set val to ar[i] (the element to be inserted into the sorted portion). Initialize p to i - 1.
STEP 9: While p is greater than or equal to 0 and ar[p] is greater than val:
STEP 10: Shift ar[p] to the right (set ar[p+1] = ar[p]).
STEP 11: Decrement p by 1.
STEP 12: Set ar[p+1] to val to insert val in the correct position within the sorted portion of the
array.
STEP 13: Method display2(): Print "THE SORTED ARRAY IS:".
STEP 14: Loop through each element in ar and print it to display the sorted array.
STEP 15: Main Method (main): Create an instance ob of Insertion_sort.
STEP 16: Call accept() to input the array.
STEP 17: Call display1() to print the original array.
STEP 18: Call sort() to sort the array using insertion sort.
STEP 19: Call display2() to print the sorted array.

9
//Program Code
import java.util.*;
class Insertion_sort
{
int ar[],n;
Scanner sc=new Scanner(System.in);
Insertion_sort()
{
n=0;
}

void accept() //initializing variables


{
System.out.println("ENTER SIZE OF ARRAY");
n=sc.nextInt();
ar=new int[n];
System.out.println("ENTER ARRAY ELEMENTS");
for(int i=0;i<n;i++)
{
ar[i]=sc.nextInt();
}
}

void display1() //display the original array


{
System.out.println("ORIGINAL ARRAY IS :");
for(int i=0;i<n;i++)
{
System.out.print(ar[i]+ " ");
}
System.out.println();
}

void sort() //sort the given array


{
int val,p;
for(int i=1;i<n;i++)
{
val=ar[i]; p=i-1;
while(p>=0 && ar[p]>val)
{
ar[p+1]=ar[p];
p--;
}

10
ar[p+1]=val;
}
}

void display2() //display the sorted array


{
System.out.println("THE SORTED IS :");
for(int i=0;i<n;i++)
{
System.out.print(ar[i]+ " ");
}
}

public static void main()


{
Insertion_sort ob=new Insertion_sort();
ob.accept();
ob.display1();
ob.sort();
ob.display2();
} //close of main()
} // close of class

// Output

ENTER SIZE OF ARRAY


5
ENTER ARRAY ELEMENTS
11
77
33
55
44
ORIGINAL ARRAY IS :
11 77 33 55 44
THE SORTED IS :
11 33 44 55 77

11
Variable description
Name Type Purpose
ar[] int To store array elements.
l int To store array length.
i int For-loop variable.
val int Acts as temporary variable.
p int Stores index of temporary variable.

Signature of Teacher

12
QUESTION 4:

Design a class Mid_Sort to sort a given array using Mid Sort technique keeping the highest
number in the middle and then the second highest to the right and third highest to the left and
so on. A main class is declared to give details of the constructor and the member methods.
Data Members – int left, right, mid -> To store array positions.
int count -> Acts as a counter variable.
int n -> To store array size.
int ar[] -> To create array to perform mid sort.

Member Methods – Mid_Sort() -> constructor that initializes data members to 0.


void input(int) -> accepts data from user.
void sort() -> sort the given array using mid sort technique.
void display() -> To display the array before and after sorting.

//ALGORITHM
STEP 1: Class Initialization (midsort) : Declare an integer array ar and variables: n (size of the
array), left, right, mid, and count.
STEP 2: Create a Scanner object sc for user input.
STEP 3: Method input() : Prompt the user to enter the size of the array and store it in n.
STEP 4: Initialize ar as an integer array of size n.
STEP 5: Prompt the user to enter the array elements, and store them in ar[i] for each index i
from 0 to n-1.
STEP 6: Method sort(): Calculate the middle index mid:
If n is even, set mid to (n - 1) / 2.
If n is odd, set mid to n / 2.
Set left to mid - 1 and right to mid + 1.
Step 7: Find the maximum element h in the array and its position hp.
Initialize h to ar[0] and hp to 0.
Loop through ar to find the largest element, updating h and hp if a larger element is
found.
Step 8: Place the maximum element in the middle.
Swap ar[hp] with ar[mid].
Set count to 2.
Step 9: Place remaining elements in descending order, alternating between the right and left of
mid.
STEP 10: Repeat until count is equal to n: Initialize nh to 0.
STEP 11: Find the next largest element in the array that is less than h, and store it in nh with its
position nhp.
STEP 12: If count is even: Place nh on the right side of mid:
Swap ar[right] with ar[nhp] and increment right.
STEP 13: If count is odd: Place nh on the left side of mid:

13
Swap ar[left] with ar[nhp] and decrement left.
STEP 14: Update h to nh and increment count.
STEP 15: Method display():
Print each element in ar separated by " | " to display the array contents.
STEP 16: Main Method (main):Create an instance ob of midsort.
STEP 17: Call input() to input the array.
STEP 18: Call display() to print the original array.
STEP 19: Call sort() to sort the array.
STEP 20: Call display() again to print the sorted array.

//Program Code
import java.util.*;
class midsort
{
int ar[],n,left,right,mid,count;
Scanner sc=new Scanner(System.in);
void input() //initializing variables
{
System.out.println("ENTER SIZE OF ARRAY");
n=sc.nextInt();
ar=new int[n];
System.out.println("ENTER ARRAY ELEMENTS");
for(int i=0;i<n;i++)
ar[i]=sc.nextInt();
}

void sort()
{
int h,i,hp=0,nh,nhp=0,temp;
if(n%2==0)
mid=(n-1)/2;
else
mid=n/2;
left=mid-1;
right=mid+1;
h=ar[0];
for(i=1;i<n;i++)
{
if(ar[i]>h)
{
h=ar[i];
hp=i;
}
}

14
temp=ar[hp];
ar[hp]=ar[mid];
ar[mid]=temp;
count=2;
while(count<=n)
{
nh=0;
for(i=0;i<n;i++)
{
if(ar[i]>nh && ar[i]<h)
{
nh=ar[i]; nhp=i;
}
}
if(count%2==0) //sorting in right side
{
temp=ar[right];
ar[right]=ar[nhp];
ar[nhp]=temp;
right++;
}
else //sorting in left side
{
temp=ar[left];
ar[left]=ar[nhp];
ar[nhp]=temp;
left--;
}
h=nh;
count++;
}
}

void display() //displaying the array


{
for(int i=0;i<n;i++)
{
System.out.print(ar[i]+" | ");
}
System.out.println();
}

public static void main()


{
midsort ob=new midsort();

15
ob.input();
System.out.println("ORIGINAL ARRAY");
ob.display();
ob.sort();
System.out.println("SORTED ARRAY");
ob.display();
}
}

// Output
ENTER SIZE OF ARRAY
5
ENTER ARRAY ELEMENTS
33
66
44
55
11
ORIGINAL ARRAY
33 | 66 | 44 | 55 | 11 |
SORTED ARRAY
11 | 44 | 66 | 55 | 33 |

Variable description
Name Type Purpose
right int To store array position.
left int To store array position.
mid int To store array position.
count int Acts as counter variable.
n int To store size of array.
ar[] int To store array elements.
h int Store the highest number of the array.
i int For loop variable.
hp int Store the index of the highest number of the array.
nh int Store the next highest number of the array.
nhp int Store the index of the next highest number of the array.
temp int To store a value temporarily.

Signature of Teacher

16
QUESTION 5:

A Stack is a linear data structure which enables the user to add and remove integers from one
end only i.e. on the top, using the concept of LIFO principle. Define a class Stack with the
following details :
Class Name : Stack
Data members :
a[] : array to hold elements.
size : to store the size of the array.
top : index of the topmost element of the stack .
Member methods :
Stack ( int s1 ) : parameterized constructor.
void push( int n ) : to push or insert argument n at the top location, if possible,
otherwise display “Stack Overflow”.
int pop( ) : to remove an integer from the top of the stack, if possible,
return the integer, otherwise display “Stack Underflow”.
void display( ) : to print the elements present in the stack, if possible,
otherwise display “Stack Underflow”.

//Program Code
Step 1: Set the maximum size of the stack.
Step 2: Initialize top to -1 (indicating an empty stack).
Step 3: Create an array a to hold the elements.
Step 4: Push Operation :Input an integer n to push onto the stack.
Step 5: If top is equal to size - 1, display "STACK OVERFLOW" (stack is full).
Otherwise: Increment top.
Step 6: Assign a[top] = n (add the element to the top of the stack).
Step 7: Pop Operation : Check if top is -1 (stack is empty).
Step 8: If empty, return a special value (e.g., -999) to indicate underflow.
Otherwise: Store a[top] in a variable d.
Step 9: Decrement top.
Step 10: Return d (the popped element).
Step 11: Display Operation :If the stack is empty (top == -1), display "STACK IS EMPTY."
Step 12: Otherwise, for each index i from top to 0, display a[i] (elements from top to
bottom).

Step 13: Menu-Driven Program in main


Step 14: Prompt the user with options to PUSH, POP, DISPLAY, or exit.
Based on the user’s choice:
Step 15: Call push(n) if the user chooses PUSH.
Step 16: Call pop() if the user chooses POP, and display the result.
Step 17: Call display() if the user chooses DISPLAY.
Step 18: Exit if the user inputs any other number.

17
ANSWER

import java.util.*;
class Stack
{
int a[ ];
int top,size;
Stack(int s1) //parameterized constructor
{
size=s1;
a=new int[size];
top=-1;
}
void push(int n)
{ //inserts elements into stack
if(top==size-1)
{
System.out.println("STACK OVERFLOW");
}
else
{
top++;
a[top]=n;
}
}
int pop( )
{ //deletes elements from stack
int d;
if(top==-1)
d=-999;
else
{
d=a[top];
top--;
}
return d;
}
void display( )
{ //displays final array
int i;
for(i=top;i>=0;i--)
{
System.out.println(a[i]);
}

18
}
public static void main( )
{
int ch;
Stack ob=new Stack(3); //creates a new object
Scanner sc=new Scanner(System.in);
do
{
System.out.println("MENU");
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.DISPLAY");
System.out.println("ANY OTHER NUMBER TO EXIT.");
System.out.println("ENTER YOUR CHOICE.");
ch=sc.nextInt( );
switch(ch)
{
case 1: System.out.println("ENTER VALUE TO PUSH");
int n=sc.nextInt( );
ob.push(n);
break;
case 2: int y= ob.pop( );
if(y!=-999)
System.out.println("DELETED ELEMENT IS:"+y);
break;
case 3: System.out.println("ELEMENTS OF STACK ARE:");
ob.display( );
break;
default: System.exit(0);
break;
}
}
while((ch>=1) && (ch<=32));
} //end of main
} //end of class

19
VARIABLE DESCRIPTION
VARIABLE TYPE PURPOSE
size Integer Size of the Array
a[ ] Integer An Array of ‘n’ elements
top Integer To control the indexes while working
s1 Integer Parameterized variable
n Integer Parameterized variable
i Integer For loop variable
t Integer Variable to hold the element to be deleted
ch Integer Variable to take user’s choice
y Integer Variable to invoke the functions

//SAMPLE OUTPUT

MENU
1.PUSH
2.POP
3.DISPLAY
ANY OTHER NUMBER TO EXIT.
ENTER YOUR CHOICE.
1
ENTER VALUE TO PUSH
2
MENU
1.PUSH
2.POP
3.DISPLAY
ANY OTHER NUMBER TO EXIT.
ENTER YOUR CHOICE.
1
ENTER VALUE TO PUSH
5
MENU
1.PUSH
2.POP
3.DISPLAY
ANY OTHER NUMBER TO EXIT.
ENTER YOUR CHOICE.
1
ENTER VALUE TO PUSH
7
MENU
1.PUSH
2.POP

20
3.DISPLAY
ANY OTHER NUMBER TO EXIT.
ENTER YOUR CHOICE.
3
ELEMENTS OF STACK ARE:
7
5
2
MENU
1.PUSH
2.POP
3.DISPLAY
ANY OTHER NUMBER TO EXIT.
ENTER YOUR CHOICE.
4

Signature of Teacher

21
QUESTION 6:

A Queue is a linear data structure which enables the user to add integers from
rear end and remove integers from the front end, using the concept of FIFO (Fist
In First Out) principle. Define a class Queue with the following details :
Class Name : Queue
Data members :
q[] : array to hold elements.
n : to store the size of the array.
f : to point the index of front end.
r : to point the index of rear end.
Member methods :
Queue( int n1) : parameterized constructor.
void addQueue( int x ) : to push or insert argument x at the rear location, if
possible, otherwise display “Queue Overflow”.
int deleteQueue( ) : to pop integer from the front location of the queue, if
possible, return the integer, otherwise display
“Queue Underflow” .
void display( ) : to print the elements present in the queue, if possible,
otherwise display “Queue Underflow”.

//Algorithm
Step 1: Define an array q to hold elements, and integers f (front), r (rear), and n
(size of queue) as instance variables.
Step 2: In the constructor, set n to the input size, initialize f and r to -1, and create
an array q of size n.
Step 3: Add to Queue (addQueue):
If r is at the last position (r == n - 1), print "Queue Overflow" (queue is full).
Step 4: Otherwise:If both f and r are -1 (queue is empty), set f and r to 0.
Step 5: Otherwise, increment r to the next position.
Step 6: Assign the input value to q[r] (enqueue the element).
Step 7: Delete from Queue (deleteQueue):If both f and r are -1 (queue is empty),
print "Queue Underflow" and return -1 to indicate an error.
Step 8: Otherwise:Store the value at q[f] (front element) in a temporary variable t.
Step 9: If f equals r, set both f and r back to -1 (queue becomes empty after
deletion).
Step 10: Otherwise, increment f to move the front position forward.

22
Step 11: Print and return t (dequeued element).
Step 12: Display Queue (display): If r is -1 or f is greater than r (queue is empty),
print "Queue Underflow".
Step 13: Otherwise, iterate from f to r and print each element in q.
Step 14: Main Program: Instantiate a Queue object with a fixed size (5 in this
example).
Step 15: Create an infinite loop to show a menu of operations (1. ADD, 2. DELETE,
3. DISPLAY, 4. EXIT).
Based on user choice:
1: Prompt for a value and call addQueue to add it.
2: Call deleteQueue, and if it returns a valid value, print the deleted element.
3: Call display to show all elements in the queue.
4: Print "EXIT" and terminate the program.
Print "Wrong choice" if the input doesn't match any of the menu options.

//program code

import java.util.*;

class Queue {
int[] q;
int f, r, n;

Queue(int n1) { // initializing variables


n = n1;
f = -1;
r = -1;
q = new int[n];
}

void addQueue(int x) { // adding an element in the queue


if (r == (n - 1))
System.out.println("Queue Overflow");
else {
if (f == -1 && r == -1) {
f = 0;
r = 0;
} else {

23
r++;
}
q[r] = x;
}
}

int deleteQueue() { // deleting an element from the queue


if (f == -1 && r == -1) {
System.out.println("Queue Underflow");
return -1; // Indicate underflow with a special value
} else {
int t = q[f];
if (f == r) {
f = -1;
r = -1;
} else {
f++;
}
System.out.println("DELETING " + t);
return t;
}
}

void display() { // displaying the queue elements


if (r == -1 || f > r) {
System.out.println("Queue Underflow");
} else {
System.out.print("ELEMENTS OF QUEUE ARE: ");
for (int i = f; i <= r; i++)
System.out.print(q[i] + " ");
System.out.println();
}
}

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
int ch, y;
Queue ob = new Queue(5);

24
while (true) {
System.out.println(" MENU ");
System.out.println(" 1. ADD ");
System.out.println(" 2. DELETE ");
System.out.println(" 3. DISPLAY ");
System.out.println(" 4. EXIT ");
System.out.println(" ENTER YOUR CHOICE ");
ch = sc.nextInt();

switch (ch) {
case 1:
System.out.println(" ENTER VALUE TO PUSH : ");
y = sc.nextInt();
ob.addQueue(y);
break;
case 2:
y = ob.deleteQueue();
if (y != -1)
{
System.out.println(y + " IS DELETED.");
}
break;
case 3:
ob.display();
break;
case 4:
System.out.println(" EXIT ");
System.exit(0);
break;
default:
System.out.println("Wrong choice");
}
}
}
}// end of class

25
//VARIABLE DESCRIPTION
VARIABLE TYPE PURPOSE
n int Size of the Array
q[ ] int An Array of ‘n’ elements
f int Front end
r int Rear end
n1 int Parameterized variable
x int Parameterized variable
i int For loop variable
t int Variable to hold the element to be deleted
ch int Variable to take user’s choice
y int Variable to invoke the functions

//SAMPLE OUTPUT
MENU
1. ADD
2. DELETE
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE
1
ENTER VALUE TO PUSH :
12
MENU
1. ADD
2. DELETE
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE
1
ENTER VALUE TO PUSH :
45
MENU
1. ADD
2. DELETE
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE
3
ELEMENTS OF QUEUE ARE: 12 45

26
MENU
1. ADD
2. DELETE
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE
4
EXIT

Signature of Teacher

27
QUESTION 7:

A class IscScores defines the scores of a candidate in six subjects and another class BestFour
defines the best four subjects.
Class name – IscScores.
Data Members – int number[6][2] -> To contain marks of six subjects and subject codes.
Member Methods –
IscScores() -> Constructor to assign 0 to array.
void inputmarks() -> To accept the marks and subject score to each subject.
int point(int) -> To return the point in each subject according to the following: -
Marks Point
>=90 1
80-89 2
70-79 3
60-69 4
50-59 5
40-49 6
<40 7

Class Name – BestFour.


Member Methods – void BestSubjects() – To display the total points and BestFour subject
codes using the concept of inheritance.

// Algorithm
Step 1: Define two classes: IscScores and BestFour.
Step 2: IscScores contains methods to input and process scores.
Step 3: BestFour extends IscScores and includes logic to identify the four best scores.
Step 4: Initialize IscScores Class: Create a number array of size [6][2] to store subject codes and
marks for six subjects.
Step 5: The constructor of IscScores sets all elements in number to 0.
Step 6: Input Marks in IscScores: inputMarks() method takes user input for six subjects, storing
each subject’s code and marks in the number array.
Step 7: Convert Marks to Rank in point(): The point() method converts marks to a rank based
on certain ranges:
90 and above → rank 1
80-89 → rank 2
70-79 → rank 3
60-69 → rank 4
50-59 → rank 5
40-49 → rank 6
Below 40 → rank 7

28
Step 8: Class BestFour Inherits from IscScores: BestFour extends IscScores, inheriting its
methods and data members.
Step 9: The bestFour() method in BestFour class performs the main functionality.
Step 10: Sort Subjects by Marks in Descending Order: In bestFour(), retrieve marks and sort
them in descending order based on marks using a bubble sort.
Step 11: Convert Top Marks to Ranks: Store the subject code and corresponding rank (using
point() method) of the sorted marks into the ar array.
Step 12: Display the Top Four Subjects with Ranks: Print the subject code and rank of the top
four subjects from the sorted list.

Step 13: Execution of the Program: main() method in BestFour creates an instance of BestFour,
which calls bestFour() to execute the steps above.

//Program Code
import java.util.*;
class IscScores
{
static Scanner sc=new Scanner(System.in);
int number[][]=new int[6][2];
IscScores()
{
for(int i=0;i<6;i++)
{
for(int j=0;j<2;j++)
{
number[i][j]=0;
}
}
}

void inputMarks()
{
//declaring data members
for(int i=0;i<6;i++) //initializing data members
{
for(int j=0;j<2;j++)
{
if(j%2==0)
System.out.print("ENTER CODE : ");
else
System.out.print("ENTER MARKS : ");
number[i][j]=sc.nextInt();

29
}
}
}

int point(int a) //converting marks to rank


{
if(a>=90) return 1;
else if(a>=80) return 2;
else if(a>=70) return 3;
else if(a>=60) return 4;
else if(a>=50) return 5;
else if(a>=40) return 6;
else return 7;
}
}

import java.util.*;
class BestFour extends IscScores
{
static Scanner sc=new Scanner(System.in);
void bestFour()
{
super.inputMarks();
int ar[][]=new int[6][2];
int t1,t2;
for(int i=0;i<6;i++)
{
for(int j=0;j<6-i-1;j++)
{
if(number[j][1]<number[j+1][1])
{
t1=number[j][1];
number[j][1]=number[j+1][1];
number[j+1][1]=t1;
t2=number[j][0];
number[j][0]=number[j+1][0];
number[j+1][0]=t2;
}
}
}
for(int i=0;i<6;i++)
{
ar[i][0]=number[i][0];
ar[i][1]=super.point(number[i][1]);
}

30
System.out.println("BEST FOUR SUBJECTS CODES AND RANKS ARE:-");
for(int i=0;i<4;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(ar[i][j]+"\t");
}
System.out.println();
}
}

public static void main()


{
BestFour ob=new BestFour();
ob.bestFour();
} //end of main
}

Variable description
Name Type Purpose
number[][] int To store subject code and marks.
i int For-loop variable.
j int For-loop variable.
a int To store marks and return rank.
ar[][] int To store subject code and rank.
t1 int Temporary variable.
t2 int Temporary variable.

//Sample output
ENTER CODE
1
ENTER MARKS
80
ENTER CODE
2
ENTER MARKS
98
ENTER CODE
3
ENTER MARKS

31
95
ENTER CODE
4
ENTER MARKS
92
ENTER CODE
5
ENTER MARKS
91
ENTER CODE
6
ENTER MARKS
100
BEST FOUR SUBJECTS CODES AND RANKS ARE:-
6 1
2 1
3 1
4 1

Signature of Teacher

32
QUESTION 8:

A base class called account is defined as follows:


Data Members – int acc_no -> To store account number.
double principal -> To store principal.
Member Methods –
account(int a1, double b1) -> To initialize acc_no and principle with a1 and b1.
void display() -> To display acc_no and principal.

A subclass called simple_interest is defined from this base.


Data Members – double rate -> To store rate of interest.
double time -> To store time for interest.
Member Methods –
simple_interest() -> A parameterized constructor to initialize rate and time.
double interest() -> To calculate and return simple interest.
void display() -> To display rate and time and simple interest.

A subclass called compound_interest is derived from this base class.


Data Members – double rate -> To store rate of interest.
double time -> To store time for interest.
Member Methods –
coumpound_interest() -> A parameterized constructor to initialize rate and time.
double interest() -> to calculate and return compound interest.
void display() -> To display rate and time and compound interest.

//Algorithm
Step 1: Import the java.util.* package for using utility classes like Scanner for input.
Step 2: Define account Class:
Step 3: Declare two protected variables:
acc_no (int) for the account number.
principal (double) for the principal amount.
Step 4: Define a constructor account(int a1, double b1) to initialize acc_no and principal with
values passed as parameters.
Step 5: Define a display() method to print the account number and principal.
Step 6: Define simple_interest Class (Subclass of account):
Step 7:Declare two additional variables:
rate (double) for the rate of interest.
time (double) for the time period.
Step 8: Define a constructor simple_interest(int a1, double b1, double c1, double d1):
Step 9: Call the superclass (account) constructor to initialize acc_no and principal.

33
Initialize rate and time with values passed as parameters.
Step 10: Define an interest() method to calculate simple interest using the
formula:simple interest=(principal×rate×time)/100
Return the calculated simple interest.
Step 11: Override the display() method:
Step 12: Call the superclass display() method to print account details.
Step 13: Calculate the simple interest by calling interest().
Print rate, time, and the calculated simple interest.
Step 13: Define compound_interest Class (Subclass of account):
Step 14: Declare a Scanner object (sc) for input collection.
Step 15: Declare additional variables:
rate (double) for the rate of interest.
time (double) for the time period.
Step 16: Define a constructor compound_interest(int a1, double b1, double c1, double d1):
Step 17: Call the superclass (account) constructor to initialize acc_no and principal.
Step 18: Initialize rate and time with values passed as parameters.
Step 19: Define an interest() method to calculate compound interest using the
Formula:compound interest=principalx(1+rate/100)^time−principal
Return the calculated compound interest.
Step 20: Override the display() method:
Step 21: Call the superclass display() method to print account details.
Step 22: Calculate compound interest by calling interest().
Print rate, time, and the calculated compound interest.
Step 23: Define main() Method in compound_interest Class:
Step 24: Collect user inputs for account number, principal, rate, and time.
Step 25: Create an object ob1 of simple_interest with the user-provided values.
Step 26: Create an object ob2 of compound_interest with the same values.
Step 27: Call display() on both ob1 and ob2 to print account details, rate, time, and calculated
interests (simple and compound).
Step 28: End Program

//Program Code

import java.util.*;
class account
{
protected int acc_no; protected double principal;
account(int a1,double b1) //initializing variable
{
acc_no=a1;
principal=b1;
}
void display()
{

34
System.out.println("ACCOUNT NUMBER IS :- "+acc_no);
System.out.println("PRINCIPLE AMOUNT IS :- "+principal);
}
}

class simple_interest extends account


{
double rate,time;
simple_interest(int a1,double b1,double c1,double d1)
{
super(a1,b1);
rate=c1;
time=d1;
}
double interest() //finding simple interest
{
double si=0.0;
si=(principal*rate*time)/100;
return si;
}
void display()
{
super.display();
double simp_int=interest();
System.out.println("RATE PERCENT IS :- "+rate);
System.out.println("TIME IS :- "+time);
System.out.println("SIMPLE INTEREST IS :- "+simp_int);
}
}

import java.util.*;
class compound_interest extends account
{
static Scanner sc=new Scanner(System.in);
double rate,time;
compound_interest(int a1,double b1,double c1,double d1)
{
super(a1,b1);
rate=c1;
time=d1;
}
double interest() //finding compound interest
{
double ci=0.0;
ci=(principal*(Math.pow((1+(rate/100)),time)))-principal;

35
return ci;
}
void display()
{
super.display(); double comp_int=interest();
System.out.println("RATE PERCENT IS :- "+rate);
System.out.println("TIME IS :- "+time);
System.out.println("COMPOUND INTEREST IS :- "+comp_int);
}
public static void main()
{
System.out.println("ENTER ACCOUNT NUMBER :-");
int a=sc.nextInt();
System.out.println("ENTER PRINCIPAL :-");
int b=sc.nextInt();
System.out.println("ENTER RATE :-");
double c=sc.nextInt();
System.out.println("ENTER TIME :-");
double d=sc.nextInt();
simple_interest ob1=new simple_interest(a,b,c,d);
compound_interest ob2=new compound_interest(a,b,c,d);
ob1.display();
ob2.display();
} //end of main
} //end of class

Sample Output

ENTER ACCOUNT NUMBER :-


1235
ENTER PRINCIPAL :-
1000
ENTER RATE :- 5
ENTER TIME :-
3
ACCOUNT NUMBER IS :- 1235
PRINCIPLE AMOUNT IS :- 1000.0
RATE PERCENT IS :- 5.0
TIME IS :- 3.0
SIMPLE INTEREST IS :- 150.0
ACCOUNT NUMBER IS :- 1235
PRINCIPLE AMOUNT IS :- 1000.0
RATE PERCENT IS :- 5.0
TIME IS :- 3.0
COMPOUND INTEREST IS :- 157.62500000000023

36
//Variable description
Name Type Purpose
acc_no int To store account number.
principal double To store principal.
a1 int To store account number and pass the value to acc_no.
b1 double To store principal and pass the value to principal.
rate double To store rate of interest.
time double To store time for interest.
c1 double To store rate of interest and pass the value to rate.
d1 double To store time for interest and pass the value to time.
si double To calculate simple interest.
simp_int double To store simple interest.
ci double To calculate compound interest.
comp_int double To store compound interest.
a int To store value of account number from user.
b int To store value of principal from user.
c double To store value of rate from user.
d double To store value of time from user.

Signature of Teacher

37
QUESTION 9:
The transpose of a matrix is found by interchanging the elements of rows and columns.
Design a class matrix that contains a 2D array of order [n * n ]. The maximum value possible for
n is 20. The details of some of the members of the class are given below
Class name : matrix
Data members:
int t[][] : to store the matrix
int n : integer to store the number of rows and columns
Member functions:
matrix(…..) : parameterized constructor to initialize n and to allocate memory to
member array
void fnGet() : to fill the member array
void fnDisplay() : to show the member matrix
matrix fnTrans(matrix A) : to store the transpose of the argument matrix in the current object
and return that.
void symmetric(matrix temp) : Check the matrix is symmetric or not.
Specify the class matrix giving the details of the above member data and methods only.

//Algorithm
Step 1: Import java.util.* for using Scanner to take input.
Step 2: Define matrix Class:
Step 3: Declare a 2D integer array t to store matrix elements.
Declare an integer n to store the size of the matrix (number of rows and columns).
Step 4: Define Constructor matrix(int n1):
Step 5: Initialize n with the value n1 (size of the matrix).
Step 6: Initialize t as a 2D array with dimensions n x n.
Step 7: Define Method get():
Step 8: Create a Scanner object sc to read user inputs.
Prompt the user to enter elements of the matrix.
Step 9: Use nested loops to read elements row by row into the matrix t.
Step 10: Define Method disp():
Step 11: Use nested loops to display the matrix.
Step 12: Print each element with a tab separator, and start a new line after each row.
Step 13: Define Method Trans(matrix o1):
Compute the transpose of the matrix o1.
Step 14: Use nested loops to assign the element at position [i][j] in t with the element at [j][i]
from o1.
Step 15: Return the current matrix instance (this).
Step 16: Define Method symmetric(matrix temp):
Initialize a variable flag to count mismatched elements.
Step 17: Use nested loops to compare each element in t with the corresponding element in
temp.

38
Step 18: If an element at position [i][j] in t is not equal to [i][j] in temp, increment flag.
Step 19: If flag remains 0, print that the matrix is symmetric; otherwise, print that the matrix is
not symmetric.
Step 20: Define main() Method:
Step 21: Create a Scanner object to read user inputs.
Step 22: Prompt the user for the size of the matrix and store it in size.
Step 23: Create two matrix objects: ob1 and ob2, both of size n x n.
Step 24: Call get() on ob1 to input matrix elements.
Step 25: Call disp() on ob1 to display the original matrix.
Step 26: Compute the transpose of ob1 by calling Trans(ob1) on ob2.
Step 27: Print the transposed matrix by calling disp() on ob2.
Step 28: Check if the original matrix is symmetric by calling symmetric(ob1) on ob2.
Step 29: End Program

//Program Code
import java.util.*;
class matrix
{
int t[][];
int n;

matrix(int n1)
{
n=n1;
t= new int [n][n];
}

void get()
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.println("Enter the elements in the array : ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
t[i][j]=sc.nextInt();
}
}
}

void disp()
{
int i,j;
for(i=0;i<n;i++)

39
{
for(j=0;j<n;j++)
{
System.out.print(t[i][j]+"\t");
}
System.out.println();
}
}

matrix Trans(matrix o1)


{
int i, j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
t[i][j]=o1.t[j][i];
return this;
}

void symmetric(matrix temp)


{
int flag=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(t[i][j]!=temp.t[i][j])
{
flag++;
}
}
}
if(flag==0) //symmetric check
System.out.println("THE MATRIX IS SYMMETRIC");
else
System.out.println("THE MATRIX IS NOT SYMMETRIC");
}

public static void main(String args[])


{
Scanner sc= new Scanner(System.in);
int size;
System.out.print("Enter size of array : ");
size=sc.nextInt();
matrix ob1=new matrix(size);

40
matrix ob2=new matrix(size);
ob1.get();
ob1.disp();
ob2=ob2.Trans(ob1);
System.out.println("Transpose of matrix");
ob2.disp();
ob2.symmetric(ob1);
}
}

// Output

Enter size of array : 2


Enter the elements in the array :
12
21
1 2
2 1
Transpose of matrix
1 2
2 1
THE MATRIX IS SYMMETRIC

VARIABLE DESCRIPTION:
Name Type Purpose
t int[][] A 2D array that stores the elements of the matrix.
n int Stores the size of the matrix (number of rows and columns).
i int Loop variable for iterating over rows of the matrix.
j int Loop variable for iterating over columns of the matrix.
A flag variable used in the symmetric() method to track if the matrix is
flag int
symmetric.

Signature of Teacher

41
QUESTION 10:

A class called Amount is defined which will add two Amount objects and return the sum
Amount object. The details of the class is given below
Class name Amount
Data member
int r , p to store rupees and paise
Amount(int a, int b) to initialize r as a and p as b.
Amount add(Amount , Amount) to calculate amount.
void display() void display()

//Algorithm
Step 1: This class represents an amount in rupees (r) and paise (p).
It contains methods to add two Amount objects and to display the amount.
Step 2: Declare Variables:
r stores rupees, and p stores paise.
A Scanner object sc is used for input.
Step 3: Define the Constructor:
Amount(int a, int b) initializes the r and p values for an Amount object.
Step 4: Define the add() Method:
This method takes two Amount objects as arguments (A1 and A2) and returns a new Amount
object (A3).
Step 5: Calculate the total rupees (x) and paise (y):
x is calculated by adding the rupees of both objects and adding any extra rupee from the paise
addition.
y is calculated as the remainder when the sum of paise values is divided by 100 (since 100 paise
= 1 rupee).
Step 6: Set A3.r and A3.p with values of x and y.
Return A3.
Step 7: Define the display() Method:
This method prints the rupees and paise of an Amount object in the format: "X RUPEES AND Y
PAISE".
Step 8: Define the main() Method:
Step 9: Create a Scanner object for input.
Step 10: Prompt the user to input the rupees and paise for two Amount objects.
Step 11: Read the rupees (a) and paise (b) for the first object.
Read the rupees (c) and paise (d) for the second object.
Step 12: Create two Amount objects, A with values a and b, and B with values c and d.
Create a third Amount object C initialized to 0 rupees and 0 paise.
Step 13: Display the values of A and B.
Step 14: Add A and B using the add() method and store the result in C.
Step 15: Display the total amount stored in C.

//Program Code

42
import java.util.*;
class Amount
{
Scanner sc = new Scanner(System.in);
int r,p;
Amount(int a, int b)
{
r=a;
p=b;
}

Amount add(Amount A1, Amount A2)


{
Amount A3=new Amount(0,0);
int x= A1.r+A2.r+(A1.p+A2.p)/100;
int y= (A1.p+A2.p)%100;
A3.r=x; A3.p=y;
return A3;
}

void display()
{
System.out.println(r+" RUPEES AND "+p+" PAISE");
}

public static void main(String args[])


{
Scanner sc = new Scanner(System.in); System.out.println("ENTER RUPEES OF THE
FIRST OBJECT");
int a=sc.nextInt();
System.out.println("ENTER PAISE OF THE FIRST OBJECT");
int b=sc.nextInt();
System.out.println("ENTER RUPEES OF THE SECOND OBJECT");
int c=sc.nextInt();
System.out.println("ENTER PAISE OF THE SECOND OBJECT");
int d=sc.nextInt();
Amount A=new Amount(a,b);
Amount B=new Amount(c,d);
Amount C=new Amount(0,0);
System.out.print("FIRST AMOUNT IS :");
A.display();
System.out.print("SECOND AMOUNT IS :");
B.display();
C=C.add(A,B);
System.out.print("TOTAL AMOUNT IS :");

43
C.display();
}
}

VARIABLE DESCRIPTION

Name Type Purpose


r int To store rupees
p int To store paise
a int Constructor variable to store copy of r
b int Constructor variable to store copy of p
x int Calculates amount
y int Calculates amount

Output
ENTER RUPEES OF THE FIRST OBJECT
456
ENTER PAISE OF THE FIRST OBJECT
23
ENTER RUPEES OF THE SECOND OBJECT
87
ENTER PAISE OF THE SECOND OBJECT
55
FIRST AMOUNT IS :456 RUPEES AND 23 PAISE
SECOND AMOUNT IS :87 RUPEES AND 55 PAISE
TOTAL AMOUNT IS :543 RUPEES AND 78 PAISE

Signature of Teacher

44
QUESTION 11:
A class Time is defined which will calculate the difference between two time objects. The class description is given
below :

Class name Time


Member data
int hh,mm To denote time in hour and minute
Member methods
Time () Constructor to initialize hour and minute to 0
void readTime() To accept time as hour and minute
int TimeToMinute(time ob) To convert the time object to minute and return the result
void minute ToTime(int n) To convert time in minute to hour and minute
void diff(time endtime , time starttime) To find difference between two time objects
void displaytime () To display time as hh:mm
public static void main() To create object and call other methods

//Algorithm

Step 1: This class represents a time in hours (hh) and minutes (mm).
It includes methods to read time, convert time to minutes, convert minutes to time, find the difference between two times, and
display the time.
Step 2: Declare Variables: hh stores hours, and mm stores minutes.
Step 3: Constructor Initialization: Time() initializes hh and mm to 0.
Step 4: Define readTime() Method: This method reads hh and mm values from user input using a Scanner object.
Step 5: Define displaytime() Method:This method prints the time in the format "hh".
Step 6: Define TimetoMinute() Method: This method takes a Time object ob as a parameter.
Step 7: It calculates the total minutes by converting hours to minutes and adding the minutes component (hh * 60 + mm).
Step 8: Return the calculated total minutes.
Step 9: Define minutesToTime() Method: This method takes an integer n representing minutes as a parameter. It converts
minutes back to hours and minutes:
hh is set to n / 60 (integer division for hours).
mm is set to n % 60 (remainder for minutes).
Step 10: Define diff() Method: This method calculates the difference between two Time objects, endtime and starttime.
Step 11: Convert both times to minutes using TimetoMinute().
Step 12: Calculate the difference in minutes (dm = m1 - m2).
Step 13: Convert the difference in minutes (dm) back to hours and minutes using minutesToTime().
Step 14: Define main() Method: Create three Time objects: ob1 (start time), ob2 (end time), and ob3 (difference).
Step 15: Prompt the user to enter start and end times in hours and minutes.
Step 16: Read start time into ob1 and end time into ob2.
Step 17: Call diff() on ob3, passing ob2 (end time) and ob1 (start time) to calculate the time difference.
Step 18: Display the time difference stored in ob3 using displaytime().

//Program Code

import java.util.*;
class Time
{ int hh,mm;
Time()
{ hh=mm=0; }
void readTime() // accept
{
Scanner sc = new Scanner(System.in);
hh = sc.nextInt();
mm = sc.nextInt();
}
void displaytime()
{
System.out.println(hh + ":" + mm);

45
}
int TimetoMinute(Time ob) // object to minute
{
int m = ob.hh*60 + ob.mm;
return m;
}
void minutesToTime(int n) // minute to time object
{
hh = n/60; mm = n%60;
}
void diff(Time endtime , Time starttime) // difference of time object
{
int m1 = TimetoMinute(endtime);
int m2 = TimetoMinute(starttime);
int dm = m1 - m2;
minutesToTime(dm);
}
public static void main()
{
Time ob1 = new Time();
Time ob2 = new Time();
System.out.println("START TIME as hour and minute");
ob1.readTime();
System.out.println("END TIME as hour and minute");
ob2.readTime();
Time ob3 = new Time();
ob3.diff(ob2,ob1);
ob3.displaytime();
}
}

VARIABLE DESCRIPTION

Name Type Purpose


1. hh int Stores hours
2. mm int Stores minutes
3. m int Converts Time to minute
4. m1 int Invokes TimeToMinute function to store endtime
5. m2 int Invokes TimeTo Minute function to store starttime
6. dm int Stores the subtraction of starttime from endtime

Output :

START TIME as hour and minute


2
50
END TIME as hour and minute
4
25
1:35
Signature of Teacher

46
QUESTION 12:
Design a class binadd in which two binary numbers are taken and added using Object Passing
Technique. A main class is created to call the class binadd giving details of the constructor and
methods and to find total time. The following data members are taken as inputs for this object
passing program.

Class name binadd


Member Data
int pos To store binary number position
int num store binary number
int tar[] To store the digits of binary number in array
Member functions
binadd() To initialize pos and num to 0

void accept() Take binary number from user


binadd addition(binadd t1, binadd t2) Calculate and returns the object
void display() To display the binary numbers

//Algorithm

Step 1: Create a class binadd with member variables num (to store the binary number as an integer) and pos (to track the
position in the result array).
Step 2: Create an array ar of fixed size to store the sum of each bit position.
Step 3: Input Binary Numbers:Define an input() method to accept binary input from the user and store it in num.
Step 4: Binary Addition: Define an addition(binadd ob2) method to perform binary addition with another binadd object (ob2).
Step 5: Initialize carry to 0 and an array ar to store the sum.
Step 6: Determine which of this.num or ob2.num is larger; assign the larger to big and the smaller to small.
Step 7: Use a while loop to iterate through each bit of big and small:
Step 8: Extract the last digit (d1 and d2) of small and big using modulus operation.
Step 9: Add d1, d2, and carry. Determine the result bit (sum) and the new carry: If the sum of the digits and carry is 0 or 1,
store sum as the result and set carry to 0.
If the sum is 2, set sum to 0 and carry to 1.
If the sum is 3, set sum to 1 and carry to 1.
Step 10: Divide big and small by 10 to shift to the next digit.
Step 11: Store sum in ar at position pos, then increment pos.
Step 12: After the loop, if carry is still 1, store it in ar at position pos.
Step 13: Display Result: Define a display() method to output the final binary sum stored in ar.
Iterate through ar in reverse (starting from pos-1), printing each bit to display the binary sum.
Step 14: Main Method: In binadd_Main, create three objects obm1, obm2, and obm3.
Step 15: Take input for two binary numbers using obm1.input() and obm2.input().
Step 16: Call the addition method with obm2 as the argument for obm1, storing the result in obm3.
Step 17: Display the result with obm3.display().

Program 12
import java.util.*;
class binadd
{
int num,pos;
int ar[]=new int[10];
Scanner sc=new Scanner(System.in);
binadd()
{
pos=num=0; }

void input()

47
{
System.out.print("ENTER BINARY NUMBER : ");
num=sc.nextInt(); }

binadd addition(binadd ob2)


{
binadd ob1=new binadd();
int big,small,d1=0,d2=0,sum=0,carry=0,s=0,pos=0;
if(this.num>ob2.num)
{
big=this.num;
small=ob2.num;
}
else
{
big=ob2.num;
small=this.num;
}
while(big>0)
{
d1=small%10;
d2=big%10;
s=d1+d2+carry;
big/=10;
small/=10;
if(s==0||s==1)
{ sum=s; carry=0; }
else if(s==2)
{
sum=0;
carry=1;
}
else if(s==3)
{
sum=1;
carry=1;
}
else
{
System.out.println("ERROR");
System.exit(0);
}
ob1.ar[ob1.pos]=sum;
ob1.pos++;
}
if(carry==1)
ob1.ar[ob1.pos++]=carry;
return ob1;
}

void display()
{
System.out.println("RESULT :-");
for(int i=this.pos-1;i>=0;i--)
System.out.print(this.ar[i]);
System.out.println();
}

48
public static void main()
{
binadd obm1=new binadd();
binadd obm2=new binadd();
binadd obm3=new binadd();
System.out.println("FIRST INPUT :- ");
obm1.input();
System.out.println("SECOND INPUT :- ");
obm2.input();
obm3=obm1.addition(obm2);
obm3.display();
}
}

//Output
FIRST INPUT :-
ENTER BINARY NUMBER : 1010
SECOND INPUT :-
ENTER BINARY NUMBER : 111
RESULT :-
10001

VARIABLE DESCRIPTIONS

Method/Variable Name Data Type Description


pos int To store binary number position
num int To store binary number
ar[] int To store the digits of binary number
big int To store greater binary number
small int To store smaller binary number
d1 int To store remainder of small
d2 int To store remainder of big
carry int To store carry value
sum int To store sum value
s int To store sum of d1, d2 and carry
i int Loop Variable

Signature of Teacher

49
QUESTION 13:
/*A Prime-Adam integer is a positive integer (without leading zeroes) 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’ is 31, then, 132 = 169, and 312 = 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
Frequency of Prime-Adam integers is: 0
Example 4:
INPUT:
m = 700
n = 450
OUTPUT:
Invalid Input.
*/

50
//Algorithm
Step 1: Prompt the user to input two integers, m and n, where m is the lower limit and n is the
upper limit of the range.
Step 2: If m is greater than or equal to n, print "Invalid input" and terminate the program.
Step 3: Initialize Variables: Set a counter count to zero to keep track of the number of Prime-
Adam integers.
Step 4: Loop through the Range: For each integer i from m to n:
Step 5: Check if i is a prime number using the isPrime function.
Step 6: If i is a prime: Reverse the digits of i using the reverse function, storing the result in rev.
Step 7: Calculate the square of i (s1 = i * i) and the square of rev (s2 = rev * rev).
Step 8: Reverse the digits of s1 using the reverse function and compare it with s2.
Step 9: If reverse(s1) equals s2, then i is a Prime-Adam integer.
Step 10: Print i as a Prime-Adam integer (if it's the first, print without a comma; otherwise, add
a comma before it).
Increment count by 1.

Step 11: Display Results: After looping through all numbers from m to n:
If no Prime-Adam integers are found (count is 0), print "NIL."
Otherwise, print a new line.
Print the frequency of Prime-Adam integers found (i.e., the value of count).

Step 12: isPrime Function: Accepts an integer n and returns true if n is prime:
Step 13: Initialize a counter f for the number of factors.
Step 14: For each integer from 1 to n, check if it divides n evenly.
Step 15: If n has exactly two divisors (1 and n), it is prime; otherwise, it is not.
Step 16: reverse Function: Accepts an integer n and returns its reverse:
Initialize rev to 0.
Step 17: While n is greater than 0:
Step 18: Set rev = rev * 10 + (n % 10) to add the last digit of n to rev.
Step 19: Remove the last digit from n by integer division (n /= 10).
Return rev.

//Program code

import java.util.*;
class PrimeAdam
{
public static void main(String args[])
{
Scanner sc= new Scanner (System.in);
System.out.print("m = ");
int m = sc.nextInt();
System.out.print("n = ");
int n = sc.nextInt();

51
if(m >= n)
{
System.out.println("Invalid input.");
return;
}
int count = 0;
System.out.println("The Prime-Adam integers are:");
for(int i = m; i <= n; i++)
{
if(isPrime(i))
{
int rev = reverse(i);
int s1 = i * i;
int s2 = rev * rev;
if(reverse(s1) == s2)
{
if(count == 0)
System.out.print(i);
else
System.out.print(", " + i);
count++;
}
}
}
if(count == 0)
System.out.println("NIL");
else
System.out.println();
System.out.println("Frequency of Prime-Adam integers is: " + count);
}

public static boolean isPrime(int n)


{
int f = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0)
f++;
}
if(f==2)
return true;
else
return false;
}

public static int reverse(int n)

52
{
int rev = 0;
for(int i = n; i > 0; i /= 10)
rev = rev * 10 + i % 10;
return rev;
}
}

//Output
m = 100
n = 400
The Prime-Adam integers are:
101, 103, 113, 211, 311
Frequency of Prime-Adam integers is: 5

VARIABLE DESCRIPTION:
Name Type Purpose
m int Stores the lower bound of the range to search for Prime-Adam integers.
n int Stores the upper bound of the range to search for Prime-Adam integers.
count int Tracks the number of Prime-Adam integers found in the given range.
i int Loop variable used for iterating through numbers from m to n.
rev int Stores the reversed value of i during the check for Prime-Adam integers.
s1 int Stores the square of i (used for checking the Prime-Adam condition).
s2 int Stores the square of the reversed number rev (used for checking the Prime-
Adam condition).
f int Used in isPrime method to count the number of divisors of a number.
i int Loop variable used for checking if a number is prime.

Signature of Teacher

53
QUESTION 14:
A Goldbach number is a positive even integer that can be expressed as the sum of two odd
primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.

Example:
6=3+3
10 = 3 + 7
10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime pairs, i.e. 3 and 7, 5
and 5.
Write a program to accept an even integer 'N' where N>4 and N<100. Find all the odd prime
pairs whose sum is equal to the number 'N'.
Test your program with the following data and some random data:

Example 1
INPUT:
N = 14

OUTPUT:
PRIME PAIRS ARE:
3, 11
7, 7

Example 2
INPUT:
N = 30

OUTPUT:
PRIME PAIRS ARE:
7, 23
11, 19
13, 17

Example 3
INPUT:
N = 17

OUTPUT:
INVALID INPUT. NUMBER IS ODD.

Example 4
INPUT:
N = 126

54
OUTPUT:
INVALID INPUT. NUMBER OUT OF RANGE.

//Algorithm
Step 1: Define isPrime Function:
Step 2: Accept an integer num.
Step 3: Initialize a counter c to count the number of divisors of num.
Step 4: For each integer from 1 to num, check if it divides num evenly.
Step 5: If the total count of divisors (c) is exactly 2, num is prime, so return true. Otherwise,
return false.
Step 6: Main Function: Prompt the user to enter an even integer n between 10 and 99.
Step 7: Input Validation: If n is not within the range (less than 10 or greater than 99), print
"Invalid Input. Number Out Of Range." and terminate the program.
If n is odd (i.e., n % 2 != 0), print "Invalid Input. Number Is Odd." and terminate the program.
Step 8: Prime Pair Generation: Print a header "The Prime Pairs Are:" to indicate the start of
output.
Step 9: Initialize a to 3 (the smallest odd prime).
Step 10: Use a while loop to iterate a through all odd integers up to n / 2:
Step 11: Calculate b as n - a.
Step 12: Check if both a and b are prime using the isPrime function.
If both a and b are prime, print the pair (a, b) as a valid Goldbach pair.
Increment a by 2 to move to the next odd integer.

//Program Code

import java.util.*;
class GoldbachNumber
{
public static boolean isPrime(int num)
{
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
return c == 2;
}

public static void main(String args[])


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Value Of N: ");

55
int n = sc.nextInt();
if (n <= 9 || n >= 100)
{
System.out.println("Invalid Input. Number Out Of Range.");
return;
}
if (n % 2 != 0)
{
System.out.println("Invalid Input. Number Is Odd.");
return;
}
System.out.println("The Prime Pairs Are:");
int a = 3;
int b = 0;
while (a <= n / 2)
{
b = n - a;
if (isPrime(a) && isPrime(b))
{
System.out.println(a + ", " + b);
}
a += 2;
}
}
}

//output
Enter The Value Of N: 10
The Prime Pairs Are:
3, 7
5, 5

//Variable Description

Name Type Purpose


num int Represents the number being checked for primality in the isPrime method.
c int Counts the number of divisors of num to determine if it is prime.
n int The user input number, for which the prime pairs are found.
a int Loop variable that starts from 3 and checks numbers less than or equal to n /
2 for prime pairs.
b int The complement of a such that a + b = n, used to check if both a and b are
prime pairs.

Signature of Teacher

56
QUESTION 15:
Class Name – multiplication
Data Members – int m[][],n[][],p[][], s;
Member Methods –
multiplication(int size)->To input size of matrix and to declare it.
void fillarray()-> To accept the matrix.
void product()-> It will return the product of matrices
void display() -> It will display all 3 matrices.

//Algorithm

Step 1: Class Definition:


m[][], n[][], p[][]: These are 2D arrays to store the matrices.
s: An integer to hold the size of the square matrices.
Step 2: Constructor (multiplication(int size)): The constructor initializes the size s and creates
2D arrays m, n, and p with dimensions s x s.
Step 3: Method fillarray(): This method prompts the user to input elements for two square
matrices m and n of size s x s using the Scanner class.
It asks for input for matrix m, followed by matrix n.
Step 4: Method product(): This method computes the product of two matrices m and n, storing
the result in matrix p.
Step 5: The multiplication of matrices is performed using the standard matrix multiplication
rule, where element p[i][j] is computed as: m[i][k]×n[k][j]
This is implemented using three nested for loops.
Step 6: Method display(): This method prints the matrices m, n, and p (input matrices and the
result of their multiplication) to the console in a formatted manner.
Step 7: Main Method (main(String[] args)): In the main() method, the user is prompted to enter
the size of the matrices (size), and the multiplication object is created.
Step 8: The fillarray(), product(), and display() methods are called sequentially to fill matrices,
compute their product, and display the matrices and the result.

Answer
import java.util.*;
class multiplication
{
int m[][],n[][],p[][];
int s;
multiplication(int size)
{
s=size;
m=new int[s][s];
n=new int[s][s];
p=new int[s][s];

57
}

void fillarray()
{
Scanner sc= new Scanner(System.in);
int i,j;
System.out.println("Enter elements in the 1st array : ");
for(i=0;i<s;i++)
{
for(j=0;j<s;j++)
{
System.out.print("Enter a number : ");
m[i][j]=sc.nextInt();
}
}
System.out.println("Enter elements in the 2nd array : ");
for(i=0;i<s;i++)
{
for(j=0;j<s;j++)
{
System.out.print("Enter a number : ");
n[i][j]=sc.nextInt();
}
}
}

void product()
{
int i,j,k;
for(i=0;i<s;i++)
{
for(j=0;j<s;j++)
{
p[i][j]=0;
for(k=0;k<s;k++)
{
p[i][j]=p[i][j]+(m[i][k]*n[k][j]);
}
}
}
}

void display()
{
int i,j;

58
for(i=0;i<s;i++)
{
for(j=0;j<s;j++)
{
System.out.print(m[i][j]+"\t");
}
System.out.println();
}
System.out.println();
for(i=0;i<s;i++)
{
for(j=0;j<s;j++)
{
System.out.print(n[i][j]+"\t");
}
System.out.println();
}
System.out.println();
for(i=0;i<s;i++)
{
for(j=0;j<s;j++)
{
System.out.print(p[i][j]+"\t");
}
System.out.println();
}
}
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int size;
System.out.println("Enter the size : ");
size=sc.nextInt();
multiplication ob = new multiplication(size);
ob.fillarray();
ob.product();
ob.display();
}
}
//Output
Enter the size :
2
Enter elements in the 1st array :
Enter a number : 1
Enter a number : 2

59
Enter a number : 3
Enter a number : 4
Enter elements in the 2nd array :
Enter a number : 5
Enter a number : 6
Enter a number : 7
Enter a number : 8
First Array
1 2
3 4
Second Array
5 6
7 8
Final Array
19 22
43 50

Variable description
Name Type Purpose
m int[][] 2D array that stores elements of the first matrix.
n int[][] 2D array that stores elements of the second matrix.
p int[][] 2D array that stores the product of the two matrices.
s int Stores the size of the matrices (number of rows and columns, assumed
square matrices).
i int Loop variable used for iterating over the rows of the matrices.
j int Loop variable used for iterating over the columns of the matrices.
k int Loop variable used in the product method for matrix multiplication.
size int Stores the size of the matrix entered by the user in the main method.

Signature of Teacher

60
QUESTION 16:
Write a program to declare a matrix A [ ] [ ] of order (M N) where ‘M’ is the number of rows
and ‘N’ is the number of columns such that both M and N must be greater than 2 and less
than10. Allow the user to input integers into this matrix. Display appropriate error message for
an invalid input.
Perform the following tasks on the matrix.
Test your program for the following data and some random data:
Example 1
INPUT: M =3
N=4
Enter elements in the matrix:
100 90 87 76
200 500 167 998
77 567 89 254
OUTPUT: FORMED MATRIX AFTER ROTATING:
200 500 167 998
77 567 89 254
100 90 87 76
Highest element: 998 ( Row: 0 and Column: 3 )
Example 2
INPUT: M =4
N=3
Enter elements in the matrix:
54 120 187
78 55 289
134 67 89
63 341 122
OUTPUT: FORMED MATRIX AFTER ROTATING:
78 55 289
134 67 89
63 341 122
54 120 187
Highest element: 341 ( Row: 2 and Column: 1 )
Example 3
INPUT: M = 2
N=3
OUTPUT: SIZE IS OUT OF RANGE. INVALID ENTRY

Algorithm:
Step 1: Create a Scanner object to handle user input.
Step 2: Prompt the user to input the number of rows (M) and columns (N).
Step 3: Validate that M and N are within the range (3 to 9). If not, print an error message and
exit.

61
Step 4: Declare a 2D array matrix of size M x N.
Step 5: Prompt the user to enter elements to fill the matrix.
Step 6: Use nested loops to read and store each element in matrix.
Step 7: Print the original matrix using nested loops to display each element.
Step 8: Declare another 2D array r_Matrix of size M x N to store the rotated matrix.
Step 9: For each row i in r_Matrix, set it to the row (i + 1) % M of matrix, effectively rotating
rows upwards.
Step 10: Initialize variables maxElement, maxRow, and maxCol to track the highest value and
its position in r_Matrix.
Step 11: Traverse r_Matrix using nested loops to find the maximum element.
Step 12: Update maxElement, maxRow, and maxCol whenever a higher element is found.
Step 13: Print the rotated matrix r_Matrix using nested loops to display each element.
Step 14: Print maxElement along with its row (maxRow) and column (maxCol) position.

Program Code
import java.util.*;
class Matrix_Rotate {
public static void main() {
Scanner sc = new Scanner(System.in);
// Input rows (M) and columns (N) with validation
System.out.print("Enter number of rows (M): ");
int M = sc.nextInt();
System.out.print("Enter number of columns (N): ");
int N = sc.nextInt();
if (M <= 2 || M >= 10 || N <= 2 || N >= 10)
{
System.out.println("SIZE IS OUT OF RANGE. INVALID ENTRY");
return;
}
// Declare and populate the matrix
int matrix[][] = new int[M][N];
System.out.println("Enter elements in the matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = sc.nextInt();
}
}

// Display the input matrix


System.out.println("Input Matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();

62
}

// Shift each row one step upwards


int r_Matrix[][] = new int[M][N];
for (int i = 0; i < M; i++)
{
r_Matrix[i] = matrix[(i + 1) % M];
}

// Find the highest element and its location


int maxElement = r_Matrix[0][0];
int maxRow = 0;
int maxCol = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (r_Matrix[i][j] > maxElement) {
maxElement = r_Matrix[i][j];
maxRow = i;
maxCol = j;
}
}
}

// Display the rotated matrix


System.out.println("FORMED MATRIX AFTER ROTATING:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Display the highest element and its position


System.out.println("Highest element: " + maxElement + " ( Row: " + maxRow + " and
Column: " + maxCol + " )");
}
}

//Variable description
Name Data Type Description
i int Loop variable
j int Loop variable
M int Number of rows
N int Number of cols

63
maxElement int Highest element
maxRow int Position of highest element rowwise
maxCol int Position of highest element colwise
matrix[][] int 2d Array
r_Matrix[][] int 1d Array used to shift each row one step
upwards

// Output
Enter number of rows (M): 3
Enter number of columns (N): 3
Enter elements in the matrix:
123456789
Input Matrix:
123
456
789
FORMED MATRIX AFTER ROTATING:
123
456
789
Highest element: 9 ( Row: 1 and Column: 2 )

Signature of Teacher

64
QUESTION 17:
Write a program to accept a sentence which may be terminated by either ‘.’ ,‘?’or ‘!’ only. The
words may be separated by a single blank space and should be case-insensitive.
Perform the following tasks:
[A Pangram is a sentence that contains every letter of the alphabet at least once.]
Example: "The quick brown fox jumps over the lazy dog"

Test your program for the following data and some random data:
Example 1
INPUT: Pack my box with five dozen liquor jugs.
OUTPUT: IT IS A PANGRAM
LONGEST WORD: dozen
SHORTEST WORD: my
Example 2
INPUT: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
OUTPUT: IT IS A PANGRAM
LONGEST WORD: QUICK
SHORTEST WORD: THE
Example 3
INPUT: Hello my World.
OUTPUT: IT IS NOT A PANGRAM
LONGEST WORD: Hello
SHORTEST WORD: my
Example 4
INPUT: Alas ! it failed #
OUTPUT: INVALID INPUT

Algorithm:
Step 1:Create a Scanner object to handle user input.
Step 2:Prompt the user to enter a sentence (referred to as sen) terminated by one of the
following punctuation marks: '.', '?', or '!'.
Step 3:Store the trimmed sentence in the variable sen.
Step 4:Retrieve the last character of sen.If the last character is not '.', '?', or '!', print "INVALID
INPUT" and exit.
Step 5:Remove the ending punctuation mark from sen.Convert sen to lowercase for uniform
processing.
Step 6:Call the helper method checkPangram, passing sen as an argument.
Step 7:checkPangram checks if all 26 letters of the English alphabet are present in sen.
Step 8:Initialize a boolean array lettersPresent of size 26 (for each letter of the alphabet) and
uniqueLetterCount to zero.

65
Step 9:If the character is a letter, find its position in the alphabet (e.g., 'a' maps to index 0, 'b'
to index 1).
Step 10:If the letter has not been marked in lettersPresent, mark it as true and increment
uniqueLetterCount.
Step 11:Return true if uniqueLetterCount is 26 (indicating all letters are present), otherwise
return false.
Step 12:Print "IT IS A PANGRAM" if checkPangram returns true, otherwise print "IT IS NOT A
PANGRAM".
Step 13:Create a StringTokenizer object to split sen into individual words.
Step 14:Initialize l_word (longest word) to an empty string.Initialize s_word (shortest word) to
the first token (word).
Step 15:Use a while loop to traverse through each token in sen:
Step 16:If the length of the current word is greater than l_word, update l_word.
Step 17:If the length of the current word is less than s_word, update s_word.
Step 18:Print "LONGEST WORD: " followed by l_word and "SHORTEST WORD: " followed by
s_word. column (maxCol) position.

//Program Code
import java.util.*;
class Panagram
{
public static void main()
{
Scanner sc = new Scanner(System.in);
// Accept the sen input from the user
System.out.print("Enter a sen (terminated by '.', '?' or '!'): ");
String sen = sc.nextLine().trim();
// Check if the sen ends with '.', '?' or '!'
char lastChar = sen.charAt(sen.length() - 1);
if (lastChar != '.' && lastChar != '?' && lastChar != '!') {
System.out.println("INVALID INPUT");
return;
}
// Remove the ending punctuation and convert to lowercase for processing
sen = sen.substring(0, sen.length() - 1);
sen = sen.toLowerCase();
// Check if the sen is a pangram
boolean isPangram = checkPangram(sen);
System.out.println(isPangram ? "IT IS A PANGRAM" : "IT IS NOT A PANGRAM");
// Use StringTokenizer to find the longest and shortest words
StringTokenizer st = new StringTokenizer(sen, " ");
String l_word = ""; // Initialize with space
String s_word = st.nextToken(); // Initialize with the first word

while (st.hasMoreTokens()) {

66
String word = st.nextToken();
if (word.length() > l_word.length()) {
l_word = word;
}
if (word.length() < s_word.length()) {
s_word = word;
}
}

// Display the longest and shortest words


System.out.println("LONGEST WORD: " + l_word);
System.out.println("SHORTEST WORD: " + s_word);
}

// Helper method to check if a sen is a pangram


public static boolean checkPangram(String sen) {
boolean[] lettersPresent = new boolean[26]; // To track each letter
int uniqueLetterCount = 0;

for (int i=0;i<sen.length();i++) {


char ch=sen.charAt(i);
if (Character.isLetter(ch)) {
int index = ch - 'a'; // Get index for letter 'a' as 0, 'b' as 1, ..., 'z' as 25
if (!lettersPresent[index]) {
lettersPresent[index] = true;
uniqueLetterCount++;
}
}
}

return uniqueLetterCount == 26; // All 26 letters present


}
}

VARIABLE DESCRIPTION:
Name Data type Description
sen String Input the sentence
l_word String Longest word
s_word String Smallest word
Store true / false if
lettersPresent[] boolean[]
alphabet is present or not
Character extracted from
ch char
sen
Counter for number of
uniqueLetterCount int
alphabet

67
Index position of the
index int
alphabet found

//Output
Example 1
INPUT: Pack my box with five dozen liquor jugs.
OUTPUT: IT IS A PANGRAM
LONGEST WORD: dozen
SHORTEST WORD: my
Example 2
INPUT: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
OUTPUT: IT IS A PANGRAM
LONGEST WORD: QUICK
SHORTEST WORD: THE
Example 3
INPUT: Hello my World.
OUTPUT: IT IS NOT A PANGRAM
LONGEST WORD: Hello
SHORTEST WORD: my
Example 4
INPUT: Alas ! it failed #
OUTPUT: INVALID INPUT

Signature of Teacher

68
QUESTION 18:
Write a program in JAVA to accept day number (between 1 and 366) and year (yyyy) from the
user and display the corresponding date. Also accept ‘N’ from the user where (1<=N<=100) to
compute and display the future date ‘N’ days after the given date. Display error message if the
value of the day number or ‘N’ are not within the limit. Day number is calculated taking 1st
January of the given year as 1.
Test your program with given set of data and some random data
Example 1
INPUT: DAY NUMBER: 50
YEAR: 2024
N: 25
OUTPUT: ENTERED DATE: FEBRUARY 19, 2024
25 DAYS LATER: MARCH 15, 2024
Example 2
INPUT: DAY NUMBER: 321
YEAR: 2024
N: 77
OUTPUT: ENTERED DATE: NOVEMBER 16, 2024
77 DAYS LATER: FEBRUARY 1, 2025
Example 3
INPUT: DAY NUMBER: 400
YEAR: 2024
N: 125
OUTPUT: INCORRECT DAY NUMBER
INCORRECT VALUE OF ‘N’

//Algorithm :
Step 1:Create a Scanner object to handle user input.
Step 2:Prompt the user to enter the day number (d_num), the year (year), and the number of
days (N) to add.
Store these inputs as d_num, year, and n, respectively.
Step 3:Check if d_num is between 1 and 366, and if n is between 1 and 100.
If either validation fails, print error messages ("INCORRECT DAY NUMBER" and "INCORRECT
VALUE OF 'N'") and exit.
Step 4:Check if the year is a leap year using the conditions:
A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400.
Store the result in a boolean variable isLeapYear.
Step 5:If the year is not a leap year and d_num is greater than 365, print "INCORRECT DAY
NUMBER" and exit.

69
If the year is a leap year and d_num is greater than 366, print "INCORRECT DAY NUMBER" and
exit.
Step 6:Create an array daysInMonth to store the number of days in each month, adjusting
February's days based on isLeapYear.
Create an array monthNames to store the names of the months for easy display.
Step 7:Initialize month to zero and iterate over daysInMonth to determine the correct month
and day.
Step 8:For each month, subtract its days from d_num until d_num is less than or equal to the
days of the current month.
Step 9:Display the entered date as "ENTERED DATE: [Month Name] [Day], [Year]".
Step 10:Initialize futureDay to d_num + n, futureMonth to month, and futureYear to year.
Step 11:While futureDay is greater than the days in the current month
(daysInMonth[futureMonth]):
Step 12:Subtract the days in the current month from futureDay.
Step 13:Increment futureMonth.
Step 14:If futureMonth exceeds 11 (December), reset it to 0 (January), increment futureYear,
and update isLeapYear and daysInMonth[1] for the new year.
Step 15:Print "N DAYS LATER: [Month Name] [Day], [Year]" to show the date after adding N
days.

//Program Code
import java.util.*;
class Date_Calculator {
public static void main() {
Scanner sc = new Scanner(System.in);
// Input day number, year, and N from the user
System.out.print("Enter Day Number (1-366): ");
int d_num = sc.nextInt();
System.out.print("Enter Year: ");
int year = sc.nextInt();
System.out.print("Enter N (1-100): ");
int n = sc.nextInt();

// Validate the day number and N


if (d_num < 1 || d_num > 366 || n < 1 || n > 100)
{
System.out.println("INCORRECT DAY NUMBER");
System.out.println("INCORRECT VALUE OF 'N'");
return;
}

// Check if the year is a leap year


boolean isLeapYear = false;
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
boolean isLeapYear = true;

70
// Validate day number based on leap year status
if ((!isLeapYear && d_num > 365) || d_num > 366)
{
System.out.println("INCORRECT DAY NUMBER");
return;
}

// Array to store the number of days in each month


int ly= isLeapYear ? 29 : 28;
int[] daysInMonth = {31, ly , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] monthNames = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};

// Find the date corresponding to the day number


int month = 0;
while (d_num > daysInMonth[month]) {
d_num -= daysInMonth[month];
month++;
}
System.out.println("ENTERED DATE: " + monthNames[month] + " " + d_num + ", " + year);

// Calculate future date by adding N days


int futureDay = d_num + n;
int futureMonth = month;
int futureYear = year;

while (futureDay > daysInMonth[futureMonth]) {


futureDay -= daysInMonth[futureMonth];
futureMonth++;
if (futureMonth >= 12) { // If month goes beyond December, increment year and reset
month
futureMonth = 0;
futureYear++;
// Recheck leap year status for the new year and update February days
isLeapYear = (futureYear % 4 == 0 && futureYear % 100 != 0) || (futureYear % 400 ==
0);
daysInMonth[1] = isLeapYear ? 29 : 28;
}
}

System.out.println(n + " DAYS LATER: " + monthNames[futureMonth] + " " + futureDay + ",
" + futureYear);
}
}

71
// Output
Example 1
INPUT: DAY NUMBER: 50
YEAR: 2024
N: 25
OUTPUT: ENTERED DATE: FEBRUARY 19, 2024
25 DAYS LATER: MARCH 15, 2024
Example 2
INPUT: DAY NUMBER: 321
YEAR: 2024
N: 77
OUTPUT: ENTERED DATE: NOVEMBER 16, 2024
77 DAYS LATER: FEBRUARY 1, 2025
Example 3
INPUT: DAY NUMBER: 400
YEAR: 2024
N: 125
OUTPUT: INCORRECT DAY NUMBER
INCORRECT VALUE OF ‘N’

VARIABLE DESCRIPTION:

Name Type Purpose


d_num int Stores the day number (1 to 366) entered by the user.
year int Stores the year entered by the user.
n int Stores the number of days to be added to the given date (1 to
100).
isLeapYear boolean A flag to determine if the entered year is a leap year.
ly int Stores the number of days in February (28 or 29) based on leap
year status.
daysInMonth int[] Array storing the number of days in each month for the given year.
monthNames String[] Array storing the names of the months to convert month index to
name.
month int Stores the current month index (0 to 11).
futureDay int Stores the future day after adding n days to the given day.
futureMonth int Stores the future month index (0 to 11) after adding n days.
futureYear int Stores the future year after adding n days (in case the year
changes).

Signature of Teacher

72
QUESTION 19:
Write a program to print the frequency of vowels in given sentence using recursion
Class Name : frequencyVowelsInSentence
Data Member :
Stirng sen
char ch
Methods :
frequencyVowelsInSentence(String) : Constructor to initialize sen
int FrequencyOfVowels(String sen,int i,int count) : Recursive method to return the frequency of
vowels.
void display() : Invokes method FrequencyOfVowels() and prints sen & frequency of the vowels

//Algorithm
Step 1:Define a class frequencyVowelsInSentence with the following:
Step 2:A String variable sen to store the input sentence.
Step 3:A char variable ch initialized to a space character for temporarily storing each character
during processing.
Step 4:Create a constructor that takes a sentence s as an argument and assigns it to the
instance variable sen.
Initialize ch to a space character.
Step 5:Define a recursive method FrequencyOfVowels that takes three parameters:
String sen: The sentence to analyze.
int i: The current index position in the sentence.
int count: The cumulative count of vowels found so far.
Step 6:Base Case: If i is equal to or greater than the length of sen, return count (end of
recursion).
Step 7:Recursive Case: Otherwise, set ch to the character at the i-th position in sen.
Step 8:Check if ch is a vowel ('a', 'e', 'i', 'o', or 'u').
Step 9:If ch is a vowel, increment count by 1.
Step 10:Call FrequencyOfVowels recursively with the updated index (i + 1) and the current
count.
Step 11:Define a display method to output the results:
Step 12:Print the original sentence stored in sen.
Step 13:Print "FREQUENCY OF VOWELS: " followed by the result of FrequencyOfVowels when
called with initial values i = 0 and count = 0.
Step 14:Create a Scanner object to handle user input in Main Method:
Step 15:Prompt the user to enter a sentence and store it as a lowercase string in str.
Step 16:Create an instance of frequencyVowelsInSentence using str as an argument.
Step 17:Call the display method on the instance to print the sentence and the vowel frequency.

//Program Code
import java.util.*;
class frequencyVowelsInSentence
{

73
String sen;
char ch;
frequencyVowelsInSentence(String s)
{
sen=s;
ch=' ';
}
int FrequencyOfVowels(String sen,int i,int count)
{

if(i< sen.length())
{
ch=sen.charAt(i);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
{
count++;

}
return FrequencyOfVowels(sen,i+1,count);
}
else
{
return count;
}
}
void display()
{
System.out.println("Sentence is : "+ sen);
System.out.println("FREQUENCY OF VOWELS : "+FrequencyOfVowels(sen,0,0));
}
public static void main()
{

Scanner sc=new Scanner(System.in);


System.out.println("ENTER THE SENTENCE");
String str=sc.nextLine().toLowerCase();
frequencyVowelsInSentence ob=new frequencyVowelsInSentence(str);
ob.display();
}
}
// Output
ENTER THE SENTENCE
India is my country.
Sentence is : india is my country.
FREQUENCY OF VOWELS : 6

74
QUESTION 20:
Most (NOT ALL) cell phone keypads look like the following arrangement (the letters are above
the respective number)

For sending text / SMS the common problem is the number of keystrokes to type a particular
text.
For example, the word "STOP", there are a total of 9 keystrokes needed to type the word. You
need to press the key 7 four times, the key 8 once, the key 6 three times and the key 7 once to
get it.
Develop a program code to find the number of keystrokes needed to type the text.
For this problem, accept just one word without any punctuation marks, numbers or white
spaces and the text message would consist of just 1 word.
Test your data with the sample data and some random data :
Example 1:
INPUT: DEAR
OUTPUT: Number of keystrokes = 7
Example 2:
INPUT: Thanks
OUTPUT: Number of keystrokes = 12
Example 3:
INPUT: Good-Bye
OUTPUT: INVALID ENTRY

//Algorithm
Step 1: Create a Scanner object to handle user input.
Step 2: Define an integer array typing to represent the number of keystrokes needed for each
letter from 'A' to 'Z'
For example:
Letters 'A', 'B', 'C' require 1, 2, and 3 keystrokes, respectively (representing the 2 key).
Letters 'D', 'E', 'F' require 1, 2, and 3 keystrokes, respectively (representing the 3 key).
This pattern continues for all letters, with each group of letters corresponding to a specific key.
Step 3:Prompt the user to enter a word without spaces or punctuation.
Step 4:Convert the input word to uppercase and store it in the variable word.

75
Step 5:Initialize an integer variable totaltyping to 0. This will accumulate the total number of
keystrokes required for the word.
Step 6:Calculate Total Keystrokes: Loop through each character ch in word:
Step 7:Check if ch is between 'A' and 'Z':
Step 8:If ch is a valid alphabet character, determine its index in the typing array as ch - 'A'.
Step 9:Add typing[ch - 'A'] to totaltyping.
Step 10:If ch is not an alphabetic character, print "INVALID ENTRY" and exit the program.
Step 11: Repeat Step 6 to Step 10 unless all the characters are extracted
Step 12: Print "Number of typing = " followed by the value of totaltyping.

//Program Code
import java.util.*;
class type
{
public static void main() {
Scanner sc = new Scanner(System.in);
// Array to hold keystrokes for each character from 'A' to 'Z'
int[] typing = {
1, 2, 3, // A, B, C -> 2 key
1, 2, 3, // D, E, F -> 3 key
1, 2, 3, // G, H, I -> 4 key
1, 2, 3, // J, K, L -> 5 key
1, 2, 3, // M, N, O -> 6 key
1, 2, 3, 4, // P, Q, R, S -> 7 key
1, 2, 3, // T, U, V -> 8 key
1, 2, 3, 4 // W, X, Y, Z -> 9 key
};
// Input word from user
System.out.print("Enter a word (without spaces or punctuation): ");
String word = sc.nextLine().toUpperCase();

// Initialize total typing counter


int totaltyping = 0;
// Calculate typing by accessing the typing array based on character positions
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if(ch>='A' && ch <='Z')
totaltyping += typing[ch - 'A'];
else
{ // Validate input for alphabetic characters only
System.out.println("INVALID ENTRY");
System.exit(0);
}
}
// Display the total number of typing

76
System.out.println("Number of typing = " + totaltyping);
}
}

//Output
Example 1:
Enter a word (without spaces or punctuation): India
Number of typing = 10

Example 2:
Enter a word (without spaces or punctuation): Kolkata - 700115
INVALID ENTRY

VARIABLE DESCRIPTION:

Name Type Purpose


d_num int Stores the day number (1 to 366) entered by the user.
year int Stores the year entered by the user.
Stores the number of days to be added to the given date (1 to
n int
100).
isLeapYear boolean A flag to determine if the entered year is a leap year.
Stores the number of days in February (28 or 29) based on leap
ly int
year status.
daysInMonth int[] Array storing the number of days in each month for the given year.
Array storing the names of the months to convert month index to
monthNames String[]
name.
month int Stores the current month index (0 to 11).
futureDay int Stores the future day after adding n days to the given day.
futureMonth int Stores the future month index (0 to 11) after adding n days.
Stores the future year after adding n days (in case the year
futureYear int
changes).

Signature of Teacher

77
QUESTION 21:
A unique-digit integer is a positive integer (without leading zeros) with no duplicate digits. For
example, 7, 135, 214 are all unique-digit integers whereas 33, 3121, 300 are not.
Given two positive integers m and n, where m < n, write a program to determine how many
unique-digit integers are there in the range between m and n (both inclusive) and output
them.
The input contains two positive integers m and n. Assume m < 30000 and n < 30000. You are to
output the number of unique-digit integers in the specified range along with their values in the
format specified below:
Test your program for the following data and some random data.
Example 1
INPUT: m = 100
n = 120
OUTPUT: THE UNIQUE-DIGIT INTEGERS ARE:
102, 103, 104, 105, 106, 107, 108, 109, 120
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 9
Example 2
INPUT: m = 2505
n = 2525
OUTPUT: THE UNIQUE-DIGIT INTEGERS ARE:
2506, 2507, 2508, 2509, 2510, 2513, 2514, 2516, 2517, 2518, 2519
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 11
Example 3
INPUT: m = 2520
n = 2529
OUTPUT: THE UNIQUE-DIGIT INTEGERS ARE: NIL
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 0.

//Algorithm
Step 1: Create a Scanner object to handle user input.
Step 2: Declare integer variables m, n, count, and i.
Step 3: m and n will store the number of row and cols.
Step 4: count will track the number of unique-digit integers in the range.
Step 5: Prompt the user to enter two integers, m and n, which represent the range boundaries.
Store the inputs in variables m and n.
Step 6: Check if m is greater than n or if either m or n is greater than or equal to 30,000.
If the range is invalid, print "INVALID RANGE" and exit the program.
Step 7: Print Header for Unique-Digit Integers:
Step 8: Print "THE UNIQUE-DIGIT INTEGERS ARE: " to prepare for displaying the unique-digit
numbers in the range.
Step 9: Loop through each integer i from m to n.
For each integer i, call the helper function isUnique(i) to check if it has all unique digits.
Step 10: isUnique function:Convert integer n to a string s.
Step 11: Loop through each character ch in s up to the second-to-last position:

78
Step 12: Extract a substring sub starting from the position after ch.
Step 13: If sub contains ch, return false (indicating a non-unique integer).
Step 14: If no duplicate digits are found, return true.
Step 15: Print Unique-Digit Integers: If isUnique(i) returns true, print the integer i:
Step 16: If count is 0 (first unique-digit integer), print i on a new line.
Otherwise, print i separated by a comma.
Step 17: Increment count to track the number of unique-digit integers.
Step 18: After the loop, if count is still 0, print "NIL" to indicate no unique-digit integers in the
range.
Step 19: Display Frequency: Print "FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: " followed by
the value of count.

//Program Code
import java.util.*;
class Unique_Digits
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int m,n,count=0,i;
System.out.print("m = ");
m = sc.nextInt();
System.out.print("n = ");
n = sc.nextInt();
if(m > n || m >= 30000 || n >= 30000)
{
System.out.println("INVALID RANGE");
return;
}

System.out.print("THE UNIQUE-DIGIT INTEGERS ARE: ");


for(i = m; i <= n; i++)
{
if(isUnique(i)){
if(count == 0)
System.out.print("\n" + i);
else
System.out.print(", " + i);
count++;
}
}
if(count == 0)
System.out.print("NIL");
System.out.println("\nFREQUENCY OF UNIQUE-DIGIT INTEGERS IS: " + count);
}

79
public static boolean isUnique(int n)
{
String s = Integer.toString(n);
String sub;
char ch;
int i;
for(i = 0; i < s.length() - 1; i++)
{
ch = s.charAt(i);
sub = s.substring(i + 1);
if(sub.indexOf(ch) >= 0)
return false;
}
return true;
}
}

//Output
Example 1:
m = 10
n = 20
THE UNIQUE-DIGIT INTEGERS ARE:
10, 12, 13, 14, 15, 16, 17, 18, 19, 20
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 10

Example 2:
m = 400000
n = 5678
INVALID RANGE

VARIABLE DESCRIPTION:
Name Type Purpose
m int Stores the starting number of the range entered by the user.
n int Stores the ending number of the range entered by the user.
count int Tracks the number of unique-digit integers found within the specified range.
i int Loop variable used for iterating through the range from m to n.
s String Converts the integer n to a string in the isUnique method to check its digits.
sub String Substring used to check for repeating digits in isUnique method.
Holds a character from the string representation of the number to check for
ch char
uniqueness.

Signature of Teacher

80
QUESTION 22:
Write a program to declare a matrix A [ ] [ ] of order (M x N) where ‘M’ is the number of rows
and ‘N’ is the number of columns such that both M and N must be greater than 2 and less than
20. Allow the user to input integers into this matrix. Perform the following tasks on the matrix:
Perform the following tasks on the matrix.
(a) Display the input matrix
(b) Find the maximum and minimum value in the matrix and display them along with their
position.
(c) Sort the elements of the matrix in descending order using any standard sorting technique
and rearrange them in the matrix.
(d) Output the rearranged matrix.

Test your program for the following data and some random data:
Example 1
INPUT: M = 3
N=4
Enter elements of the matrix:
8793
-2 0 4 5
1 3 6 -4

OUTPUT: ORIGINAL MATRIX


8793
-2 0 4 5
1 3 6 -4
LARGEST NUMBER: 9
ROW = 0
COLUMN = 2
SMALLEST NUMBER: -4
ROW = 2
COLUMN = 3
REARRANGED MATRIX
-4 -2 0 1
3345
6789

//Algorithm
Step 1:Create a Scanner object to take user input.
Step 2:Prompt the user to enter the values of m (number of rows) and n (number of columns).
Store these values in m and n, respectively.
Step 3:Validate Matrix Dimensions: Check if m and n are within the specified range: both
should be greater than 2 and less than 20.
If the dimensions are out of range, print "SIZE OUT OF RANGE" and terminate the program.
Step 4:Input Matrix Elements: Declare a 2D array a of size m x n to hold the matrix elements.

81
Step 5:Prompt the user to enter the elements of each row.
Step 6:Use nested loops to fill each element of the matrix.
Step 7:Initialize variables l and s to hold the largest and smallest elements, initially set to the
first element of the matrix.
Step 8:Use lrow, lcol, srow, and scol to store the positions (row and column) of the largest and
smallest elements.
Step 9:Loop through each element in the matrix:
Step 10:Print each element as part of displaying the original matrix.
Step 11:If the current element is larger than l, update l, lrow, and lcol.
Step 12:If the current element is smaller than s, update s, srow, and scol.
Step 13:After the loop, print: "LARGEST NUMBER" followed by l and its position and "SMALLEST
NUMBER" followed by s and its position.
Step 14:Declare a 1D array temp of size m * n to hold all matrix elements in a single list.
Step 15:Step 1:Copy each element of the matrix into temp.
Step 16:Use a bubble sort algorithm on temp to sort the elements in ascending order.
Step 17:Copy the sorted elements from temp back into the original 2D array a row by row.
Step 18:Loop through the matrix a and print each element row by row as the sorted matrix.

//Program Code
import java.util.*;
class ArraySort
{
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF M: ");
int m = sc.nextInt();
System.out.print("ENTER THE VALUE OF N: ");
int n = sc.nextInt();

if (m <= 2 || m >= 20 || n <= 2|| n >= 20) {


System.out.println("SIZE OUT OF RANGE.");
return;
}

int a[][] = new int[m][n];


int l,s,lrow=0,lcol=0,srow=0,scol=0;
System.out.println("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++) {
System.out.println("ENTER ELEMENTS OF ROW " + (i+1) + ":");
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}
l=a[0][0];
s=a[0][0];

82
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] + " ");
if(l<a[i][j])
{ l=a[i][j];lrow=i;lcol=j;}
if(s>a[i][j])
{ s=a[i][j];srow=i;scol=j;}
}
System.out.println();
}
System.out.println("LARGEST NUMBER:"+l);
System.out.println("ROW = "+ lrow);
System.out.println("COLUMN = "+lcol);
System.out.println("SMALLEST NUMBER: "+s);
System.out.println("ROW = "+srow);
System.out.println("COLUMN = "+scol);

int temp[]=new int[m*n];


int t=0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n ; j++)
{
temp[t++]=a[i][j];
}
}
for (int i = 0; i < t-1; i++)
for (int j = 0; j <t-i- 1; t++) {
if (temp[j]>temp[j+1]) {
int ts = temp[j];
temp[j] = temp[j+1];
temp[j+1] = ts;
}
}

t=0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n ; j++)
{
a[i][j]=temp[t++];
}
}
System.out.println("MATRIX AFTER SORTING ROWS");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {

83
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}

//Output
ENTER THE VALUE OF M: 3
ENTER THE VALUE OF N: 3
ENTER ELEMENTS OF MATRIX:
ENTER ELEMENTS OF ROW 1:
1
7
5
ENTER ELEMENTS OF ROW 2:
9
8
3
ENTER ELEMENTS OF ROW 3:
5
-2
7
ORIGINAL MATRIX
175
983
5 -2 7
LARGEST NUMBER:9
ROW = 1
COLUMN = 0
SMALLEST NUMBER: -2
ROW = 2
COLUMN = 1
MATRIX AFTER SORTING ROWS
175
983
5 -2 7

VARIABLE DESCRIPTION:

Name Type Purpose


m int Stores the number of rows in the matrix, entered by the user.
n int Stores the number of columns in the matrix, entered by the user.
a int[][] 2D array (matrix) to store the elements entered by the user.
l int Stores the largest number found in the matrix.

84
s int Stores the smallest number found in the matrix.
lrow int Stores the row index of the largest number.
lcol int Stores the column index of the largest number.
srow int Stores the row index of the smallest number.
scol int Stores the column index of the smallest number.
temp int[] Array used to store all elements of the matrix for sorting.
t int Temporary variable used as the index for the temp array during sorting.
i int Loop variable used for iterating over rows of the matrix.
j int Loop variable used for iterating over columns of the matrix.
ts int Temporary variable used to swap elements while sorting the temp array.

Signature of Teacher

85
QUESTION 23:
Write a program to check if a given string is an Anagram of another string. Two strings are
anagrams if they can be rearranged to form the same string. For example, "listen" and "silent"
are anagrams.
Accept two strings from the user and check if they are anagrams of each other. Ensure that the
comparison is case-insensitive and ignores spaces. Display an appropriate message based on
whether they are anagrams or not. If any of the strings contain invalid characters (e.g.,
numbers or special characters), generate an error message.
Test your program with the following data and some random data:
Example 1
INPUT: Enter first string: Listen Enter second string: Silent
OUTPUT: STRINGS ARE ANAGRAMS
Example 2
INPUT: Enter first string: Dormitory Enter second string: Dirty room
OUTPUT: STRINGS ARE ANAGRAMS
Example 3
INPUT: Enter first string: Hello Enter second string: World
OUTPUT: STRINGS ARE NOT ANAGRAMS
Example 4
INPUT: Enter first string: Test123 Enter second string: 321tset
OUTPUT: INVALID CHARACTERS IN STRING. INVALID INPUT

import java.util.*;
class anagram
{
public static String wordsort(String w)
{
int i,j,len;
char ch;
len=w.length();
String nw="";
for(i=65;i<=90;i++)
{
for(j=0;j<len;j++)
{
ch=w.charAt(j);
if(ch==(char)i)
{
nw=nw+ch;
}
if(!(ch>='A' && ch<='Z'))

86
{
return "Invalid";
}
}
}
return nw;
}

public static void main()


{
Scanner sc= new Scanner(System.in);
String w1,w2,nw1,nw2;
System.out.println("Enter 2 words :");
w1=sc.next().toUpperCase();
w2=sc.next().toUpperCase();
nw1=wordsort(w1);
nw2=wordsort(w2);
if(!(nw1.equals("Invalid") || nw2.equals("Invalid")))
{
if(nw1.equals(nw2))
System.out.println("STRINGS ARE ANAGRAMS");
else
System.out.println("STRINGS ARE NOT ANAGRAMS");
}
else
{
System.out.println("INVALID CHARACTERS IN STRING. INVALID INPUT");
}
}
}

//Output
Example 1:
Enter first string: Listen Enter second string: Silent
STRINGS ARE ANAGRAMS

Example 2:
Enter 2 words :
test123
321test
INVALID CHARACTERS IN STRING. INVALID INPUT

87
QUESTION 24:
Create the classes Circle and Rectangle which implement the interface Shape.
The details of the interface and both the classes are given below:

Interface Name : Shape


Member methods :
double area( ) : returns the area of the implementing shape.

Class Name : Circle


Data members : radius : to store radius of the circle in decimal.
Member functions/methods :
Circle( int r ) : parameterized constructor to initialize r to radius.
double area( ) : to calculate area of the circle.

Class Name : Rectangle


Data members : length : to store length of the rectangle in decimal.
breadth : to store breadth of the rectangle in decimal.
Member methods :
Rectangle( int l, int b ) : parameterized constructor to initialize l to length and b to breadth.
double area( ) : to calculate the area of the rectangle.

//Algorithm
Step 1: Define an interface Shape with a method area() which returns a double value.
This interface will be implemented by any shape class that calculates its area.
Step 2: Define a class Circle that implements the Shape interface.
Step 3: Declare a radius attribute.
Step 4: Create a constructor for Circle that takes the radius as a parameter.
Step 5: Implement the area() method in Circle to calculate the area as π * radius^2.
Step 6: Define a main method in Circle to create a Circle object using the given radius.
Step 7: Call the area() method and print the radius and calculated area.
Step 8: Define a class Rectangle that implements the Shape interface.
Step 9: Declare length and breadth attributes.
Step 10: Create a constructor for Rectangle that takes length and breadth as parameters.
Step 11: Implement the area() method in Rectangle to calculate the area as length * breadth.
Step 12: Define a main method in Rectangle to create a Rectangle object using the given length
and breadth.
Step 13: Call the area() method and print the length, breadth, and calculated area.
Step 14: Stop

//Program Code
import java.util.*;
interface Shape
{
public double area();

88
}
import java.util.*;
class Circle implements Shape
{ //start of class
double radius;
Circle(double r)
{
radius=r;
}
public double area() //calculating area of Circle
{
return 3.14*radius*radius;
}
public static void main(double r)
{ //start of main
Circle ob=new Circle(r);
System.out.println("CIRCLE:-");
System.out.println("Radius: \n"+r+"\nArea: \n"+ob.area());
} //end of main
} //end of class
import java.util.*;
class Rectangle implements Shape
{ //start of class
double length,breadth;
Rectangle(double l,double b)
{
length=l;
breadth=b;
}
public double area() //calculating area of Rectangle
{
return length*breadth;
}
public static void main(double l,double b)
{ //start of main
Rectangle ob=new Rectangle(l,b);
System.out.println("RECTANGLE:-");
System.out.println("LENGTH: \n"+l+"\nBREADTH: \n"+b+"\nArea: \n"+ob.area( ));
} //end of main
} //end of class

//Output
CIRCLE:-
Radius:
2.0

89
Area:
12.56

RECTANGLE:-
LENGTH:
5.0
BREADTH:
2.0
Area:
10.0

VARIABLE DESCRIPTION
VARIABLE TYPE PURPOSE
radius Integer To store radius of the circle
r Integer Parameterized Variable
length Integer To store length of the rectangle
breadth Integer To store breadth of the rectangle
l Integer Parameterized Variable
b Integer Parameterized Variable

Signature of Teacher

90
QUESTION 25:
Recycle is an entity which can hold at most 100 integers. The chain enables the user to add and
remove integers from both the ends i.e. front and rear.
Define a class Recycle with the following details:
Class name: Recycle
Data members/instance variables:
ele[]: the array to hold the integer elements
cap: stores the maximum capacity of the array
front: to point the index of the front
rear: to point the index of the rear
Methods/Member functions:
Recycle(int max): constructor to initialize the data cap = max, front = rear = 0 and to
create the integer array
void pushFront(int v): to add integers from the front index if possible else display the
message “full from front”.
int popFront(): to remove and return elements from front. If array is empty then return -
999.
void pushRear(int v): to add integers from the front index if possible else display the
message “full from rear”.
int popRear(): to remove and return elements from rear. If the array is empty then
return -999.

(i) Specify the class Recycle giving details of the functions void pushFront(int) and popRear().
Assume that the other functions have been defined. The main() functions and algorithm need
not be written.

//Algorithm
Step 1: Initialize an integer array ele to hold elements. Define cap to store the capacity of the
array, front as the index for the front of the deque, and rear as the index for the rear of the
deque.
Step 2: Initialize front and rear to -1 to indicate an empty deque.
Step 3: Under Constructor (Recycle(int max)): Set cap to the provided maximum size max.
Initialize the array ele with a size of cap. Set both front and rear to -1.
Step 4: Create Method to Add Element at Front (pushFront(int v)):
Step 5: Check if the deque is full: If front is 0 and rear is cap - 1, or if front is equal to rear + 1,
then the deque is full. Print "full from front" and exit.
Step 6: If the deque is empty (i.e., front is -1): Set front and rear to 0.
Step 7: If front is 0, wrap around to the end of the array by setting front to cap - 1.
Step 8: Otherwise, decrement front.
Step 9: Insert the element v at ele[front].
Step 10: Method to Remove Element from Front (popFront()):
Step 11: Check if the deque is empty by checking if front is -1: If empty, return -999.
Step 12: Store the element at ele[front] in removedElement.
Step 13: If front and rear are equal, reset both front and rear to -1 (deque becomes empty).

91
Step 14: If front is at the last position (cap - 1), wrap around to the start by setting front to 0.
Step 15: Otherwise, increment front.
Step 16: Return removedElement.
Step 17: Create Method to Add Element at Rear (pushRear(int v)):
Step 18: Check if the deque is full: If front is 0 and rear is cap - 1, or if front is equal to rear + 1,
then the deque is full. Print "full from rear" and exit.
Step 19: If the deque is empty (i.e., rear is -1): Set front and rear to 0.
Step 20: If rear is at the last position (cap - 1), wrap around to the start by setting rear to 0.
Step 21: Otherwise, increment rear.
Step 22: Insert the element v at ele[rear].
Step 23: Create Method to Remove Element from Rear (popRear()):
Step 24: Check if the deque is empty by checking if front is -1: If empty, return -999.
Step 25: Store the element at ele[rear] in removedElement.
Step 26: If front and rear are equal, reset both front and rear to -1 (deque becomes empty).
Step 27: If rear is at the start (0), wrap around to the end by setting rear to cap - 1 Otherwise,
decrement rear.
Step 28: Return removedElement.
Step 29: Use a Scanner to get the deque capacity from the user and initialize a Recycle object
with that capacity.
Step 30: Display a menu with options:
1: Push an element to the front.
2: Pop an element from the front.
3: Push an element to the rear.
4: Pop an element from the rear.
5: Exit the program.
Step 31: Use a loop and switch statement to handle the menu options:
For each push operation, read an integer value and call the respective push method.
For each pop operation, call the respective pop method, display the result, and handle the -999
return value if deque is empty.
Step 32: Exit the loop if the user chooses an invalid option or chooses to quit.

//Program Code

import java.util.*;
class Recycle
{
int[] ele; // Array to hold integer elements
int cap; // Maximum capacity of the array
int front; // Index pointer for the front
int rear; // Index pointer for the rear

// Constructor to initialize data members

Recycle(int max) {
cap = max;

92
ele = new int[cap];
front = -1; // Initialize front and rear to -1 indicating an empty state
rear = -1;
}

// Method to add an element from the front end


void pushFront(int v)
{
if ((front == 0 && rear == cap - 1) || (front == rear + 1)) {
// Queue is full
System.out.println("full from front");
} else {
if (front == -1) { // Queue is initially empty
front = rear = 0;
} else if (front == 0) { // Wrap around to the end
front = cap - 1;
} else {
front--;
}
ele[front] = v;
}
}

// Method to remove and return element from the front end


int popFront() {
if (front == -1) { // Queue is empty
return -999;
}
int removedElement = ele[front];
if (front == rear) { // Queue has only one element
front = rear = -1;
} else if (front == cap - 1) { // Wrap around to the start
front = 0;
} else {
front++;
}
return removedElement;
}

// Method to add an element from the rear end


void pushRear(int v) {
if ((front == 0 && rear == cap - 1) || (front == rear + 1)) {
// Queue is full
System.out.println("full from rear");
} else {

93
if (rear == -1) { // Queue is initially empty
front = rear = 0;
} else if (rear == cap - 1) { // Wrap around to the start
rear = 0;
} else {
rear++;
}
ele[rear] = v;
}
}

// Method to remove and return element from the rear end


int popRear()
{
if (front == -1) { // Queue is empty
return -999;
}
int removedElement = ele[rear];
if (front == rear) { // Queue has only one element
front = rear = -1;
} else if (rear == 0) { // Wrap around to the end
rear = cap - 1;
} else
{
rear--;
}
return removedElement;
}

public static void main()


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Dequeue capacity: ");
int c = sc.nextInt();
Recycle obj = new Recycle(c);
while(true)
{
System.out.println("1. Push front");
System.out.println("2. Pop front");
System.out.println("3. Push rear");
System.out.println("4. Pop rear");
System.out.println("5. Display");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
switch(choice)

94
{
case 1:
System.out.print("Element to be pushed: ");
int v = sc.nextInt();
obj.pushFront(v);
break;
case 2:
v = obj.popFront();
if(v == -999)
System.out.println("empty from front");
else
System.out.println(v + " popped from front");
break;
case 3:
System.out.print("Element to be pushed: ");
v = sc.nextInt();
obj.pushRear(v);
break;
case 4:
v = obj.popRear();
if(v == -999)
System.out.println("empty from rear");
else
System.out.println(v + " popped from rear");
break;
default:
System.out.println("Bye");
return;
}
}
}
}

//Output
Enter Dequeue capacity: 5
1. Push front/2. Pop front/3. Push rear/4. Pop rear
Enter your choice: 1
Element to be pushed: 56
1. Push front/2. Pop front/3. Push rear/4. Pop rear
Enter your choice: 3
Element to be pushed: 77
1. Push front/2. Pop front/3. Push rear/4. Pop rear
Enter your choice: 2
56 popped from front
1. Push front/2. Pop front/3. Push rear/4. Pop rear

95
Enter your choice: 4
77 popped from rear
1. Push front/2. Pop front/3. Push rear/4. Pop rear
Enter your choice: 7
Bye

VARIABLE DESCRIPTION
Name Type Purpose
ele int[] Array that holds the elements of the deque (double-ended queue).
cap int Maximum capacity of the deque.
front int Index pointer for the front of the deque. Initially set to -1 (empty).
rear int Index pointer for the rear of the deque. Initially set to -1 (empty).
c int Stores the capacity value entered by the user.
Stores the menu option selected by the user for performing deque
choice int
operations.
v int Temporary variable to store values for insertion into the deque or removal.

Signature of Teacher

96

You might also like