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

ISC Computer Record Batch 2020-2021

The class change converts decimal numbers to hexadecimal and vice versa. It contains an array a[] to store the hexadecimal digits. The constructor initializes a[] to 0. The method void input() accepts a decimal number from the user. The method void hexadeci() converts the decimal number to hexadecimal by dividing and storing the remainders in a[]. The method void decihexa() converts the hexadecimal number back to decimal by multiplying the digits with the appropriate powers of 16 and adding them.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
636 views

ISC Computer Record Batch 2020-2021

The class change converts decimal numbers to hexadecimal and vice versa. It contains an array a[] to store the hexadecimal digits. The constructor initializes a[] to 0. The method void input() accepts a decimal number from the user. The method void hexadeci() converts the decimal number to hexadecimal by dividing and storing the remainders in a[]. The method void decihexa() converts the hexadecimal number back to decimal by multiplying the digits with the appropriate powers of 16 and adding them.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

COMPUTER

SCIENCE RECORD

Name : Rowhith K
Class : XII
Register Number : 7383027/13
Batch : 2020-2021
School : Good Earth School
1
INDEX

S.No. Date Title Page No.


1 30/06/20 Sum of the Series 3
2 03/07/20 Convert to hexadecimal 7
3 07/07/20 Longest word in the string 11
4 10/07/20 Toggle Case 14
5 14/07/20 Index Array 17
6 17/07/20 Prime Factors 21
7 21/07/20 Combining two arrays into one 24
8 24/07/20 Transpose of an array 28
9 28/07/20 Symmetric Matrix 31
10 31/07/20 Prime Numbers 35
11 04/08/20 Matrix 38
12 07/08/20 Fibonacci Series 42
13 11/08/20 String Palindrome 45
14 14/08/20 Expressing digits in words 48
15 18/08/20 Bank Account 51
16 21/08/20 Calendar 55
17 25/08/20 Duplicate characters 59
18 28/08/20 Bookmarks in a Stack 62
19 01/09/20 Word Pile 65
20 04/09/20 Queue 68

2
Date: 30/06/20
1
Sum of the Series
Question:
Sum= 1 + x/1! + x3/2! + x5/3! +……..+ x2n-1/n!
A class seriessum has been defined to calculate the sum of the above series. Some of the members of
the class are given below:
Class name : seriessum
Data members
x
n : int
sum : double
Member
functions
sumseries() : constructor
int factorial(int : calculates and returns the factorial of n( n!) where
n) n!=1 x 2 x 3 x 4 x....x n.
double term(int p, int q): Calculates and returns the value of p/q! by making
use of factorial(int).
void accept() : Inputs the value of member data x,n
void : displays the value of member data sum.
displaysum()
double calsum() : calculates the sum of the given series using the
appropriate data and other member functions.
Specify the class sumseries giving details of the constructor, int factorial(int), double term(int,int), void
displaysum(). You may assume that other member functions are written for you. Write the main
function to access the member functions.

Algorithm:
1. Start
2. Initialise the data members x, n and sum
3. Open constructor seriessum() and assign values for the data members
4. Open method int factorial(int n)
5. Initialise fact=0 and i=1
6. Run for loop with the condition (i=1;i<=n;i++)
7. fact=fact*1
8. Return the value of fact
9. Open method double term(int p, int q)
10. Return the value of p/factorial(q)
11. Open method void accept()
12. Accept the values of x and n from the user in the form of int

3
13. Open method void displaysum()
14. Display the sum to the user
15. Open method double calsum()
16. Run for loop with the condition (int i=1;i<=n;i++)
17. Store the value of p as x^2n-1 using the Math.pow() function and of q as factorial of i
18. Convert the value of q in double d
19. double r=term(p,d);
sum=sum+r;
20. Return the value of sum
21. Open main method and call all the other methods
22. Stop

Program Listing:
import java.util.*;
public class seriessum{
int x;
int n;
double sum;

public seriessum(){
x=0;
n=0;
sum=0.0;
}
public int factorial(int n){
int fact=1;
int i= 0;
for(i=1;i<=n;i++){
fact=fact*i;
}
return fact;
}
public double term(int p,int q){
return p/factorial(q);
}
public void accept(){
Scanner s= new Scanner(System.in);
System.out.println("Enter the value for x and n:");

4
x=s.nextInt();
n=s.nextInt();
}
public void displaysum(){
System.out.println("The sum is : "+sum);
}
public double calsum(){
for(int i=1;i<=n;i++){
double p=Math.pow(x,((2*n)-1));
int q=factorial(i);
double d=q;
double r=term(p,d);
sum=sum+r;
}
return sum;
}
public static void main(String[]args){
seriessum p = new seriessum();
p.accept();
p.calsum();
p.displaysum();
}}

Output:
Enter the value for x
1
Enter the value for n
2
sum4.0

5
Variable Name Variable Type Variable Description
x int User defined value
n int User defined value
sum double Sum of the series
i int Used in for loop
k int Used in for loop
fact int Used to find factorial
Used to find value of p/q! and
p, q int
to calculate sum of series
r, d double Used to calculate sum of series

6
Date: 03/07/20
2
Convert to hexadecimal
Question:
Design a class change to convert a decimal number to its equivalent in base 16 and to convert it back
to its decimal form. Eg. (i) The decimal number 35 is 23 in base 16. (ii) The decimal number 107 is 6B
in base 16.

Some of the members of the class are given below:

Class name : change


Data members
a[] : integer type array.
n : integer to be converted to base 16.
Member functions

change() : constructor to assign 0 to instance variables.


void input() : accepts integer to be converted to base 16.
voidhexadeci(int) : to convert decimal integer to hexadecimal
form.
voiddecihexa() : to convert hexadecimal number back to
decimal form.

Specify the class change giving the details of the constructor and the functions void input(),
void hexadeci(int) and void decihexa(). The main function needs to be written.

Algorithm:
1. Start
2. Initialize data members a[] and n
3. Open constructor and assign values to data members
4. Open method void input() and recieve input from the user
5. Open method void hexadeci(int n)
6. Do the following steps to convert decimal integer to hexadecimal form
int r,i=9;
while(n>16){
r=n%16;
n=n/16;
a[i--]=r;

7
}
a[i]=n;
for(int k=i;k<=9;k++){
if(a[k]>9){
int t=a[k]-10;
System.out.print((char)(65+t));
}
else {
System.out.print(a[k]);
}
System.out.println();
}
7. Open method void decihexa()
8. Do the following steps to convert hexadecimal number back to decimal form
int s=0,i;
for(i=0;i<=9;i++){
if(a[i]>0)
break;
}
if(i<10){
for(int k=i;k<=9;k++){
s=s+a[k]*((int) Math.pow(16,9-k));
}
System.out.println(s);
}
9. Stop

Program Listing:
import java.io.*;
public class change{
int a[];
int n;
change(){
a=new int [10];

8
n=0;
for(int i=0;i<=9;i++){
a[i]=0;
}}
void input() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number to be converted to hexadecimal");
n=Integer.parseInt(br.readLine());
}
void hexadeci(){
int r,i=9;
while(n>16){
r=n%16;
n=n/16;
a[i--]=r;
}
a[i]=n;
for(int k=i;k<=9;k++){
if(a[k]>9){
int t=a[k]-10;
System.out.print((char)(65+t));
}
else{
System.out.print(a[k]);
}
System.out.println();
}}
void decihexa(){
int s=0,i;
for(i=0;i<=9;i++){
if(a[i]>0)
break;
}
if(i<10){

9
for(int k=i;k<=9;k++){
s=s+a[k]*((int) Math.pow(16,9-k));
}
System.out.println(s);
}}}

Output:
Enter the number to be converted to hexadecimal
52369
CC91
52369

Variable Name Variable Type Variable Description


Used to store the entered
a[] int
number
n int User defined value
i int Used in for loop
k int Used in for loop
Used in conversion from
r int
decimal to hexadecimal
Converted decimal number
s int
from hexadecimal

10
Date: 07/07/20
3
Longest word in the string
Question:
A class Mystring has been defined for the following methods:

Class name : Mystring


Data members
str : to store a string
len : length of the given
string.
Member functions
Mystring() : constructor
void readstring() : reads the given string from input. Returns Unicode for character at
position
int code(int index): index.
void word() : displays the longest word in the string.

Algorithm:
1. Start
2. Initialize data members str and len
3. Open constructor and assign values to data members
4. Open method void readstring()
5. Accept string from user and assign len to its length
6. Open method int code(int index)
7. Check if the index is valid or not
8. Open method void word()
9. Check the length of each word and print the longest word.
10. Stop

Program Listing:
import java.util.*;
class Mystring{
String str;
int len;
int i=0;
Mystring(){
str="";
len=0;
}
void readString(){
Scanner s = new Scanner(System.in);
System.out.println("Enter a string");

11
str=s.nextLine();
len=str.length();
}
int code(int index){
int code=str.charAt(index);
return(code);
}
void word(){
StringTokenizer nt=new StringTokenizer(str);
int nw=nt.countTokens();
String word[]=new String[nw];
while(nt.hasMoreTokens()){
word[i++]=nt.nextToken();
}
String longword = word[0];
int len=word.length;
for(int i=1; i<len;i++){
if(word[i].length()>longword.length())
longword=word[i];
}
System.out.println("longest word: "+longword);
}
public static void main(String args[]){
Scanner sxc = new Scanner(System.in);
Mystring obj=new Mystring();
obj.readString();
int n=sxc.nextInt();
int h=obj.code(n);
System.out.println("code:"+h);
obj.word();
}}

Output:

12
Enter a string
it i sgood
2
code:32
longest word: sgood

Variable Name Variable Type Variable Description


str String To store a string
len int Length of the given string
index int Position index in string
Extract each character in
r char
string
Used to find longest word in
s, t String
string

13
Date: 10/07/20
4
Toggle Case

Question:
A class stringop is designed to handle string related operations. Some members of the class are given
below:
Date member
txt : to store the given string of maximum length 100.
Member function
stringop() : constructor
void readstring() : to accept the string
char caseconvert(char): to convert the letter to other case
void circular : to decode the string by replacing each letter by converting
decode() it to opposite case and then by the next character in a
circular way. Hence “AbZ” will decode “bCa”.

Algorithm:
1. Start
2. Initialise data member txt
3. Open constructor and call txt
4. Open method void readstring()
5. Accept string from user
6. Confirm the maximum length of txt using if statement
7. Open method char caseconvert(char ch)
8. Convert all uppercase letters to lowercase letters and vice versa
9. Open method void circulardecode()
10. Initialise s=""
11. Run for loop with the condition (int i = 0; i < txt.length(); i++) and do step 12
12. Call the method caseconvert(ch) and decode the string using the following:
if(ch == 'Z')
s += 'A';
else if(ch == 'z')
s += 'a';
else if(Character.isLetter(ch))
s += (char)(ch + 1);
else
s += ch;
13. Close for loop
14. Print s

14
15. Open main method and call the required functions in logical order
16. Stop

Program Listing:
import java.io.*;
class Stringop{
String txt;
public Stringop(){
txt = "";
}
public void readstring()throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the string: ");
txt = br.readLine();
if(txt.length() > 100)
txt = txt.substring(0, 100);
}
public char caseconvert(char ch){
if(Character.isUpperCase(ch))
return Character.toLowerCase(ch);
return Character.toUpperCase(ch);
}
public void circulardecode(){
String s = "";
for(int i = 0; i < txt.length(); i++){
char ch = txt.charAt(i);
ch = caseconvert(ch);
if(ch == 'Z')
s += 'A';
else if(ch == 'z')
s += 'a';
else if(Character.isLetter(ch))
s += (char)(ch + 1);
else

15
s += ch;
}
System.out.println(s);
}
public static void main(String args[])throws IOException{
Stringop obj = new Stringop();
obj.readstring();
obj.circulardecode();
}}

Output:
Enter the string: It is I who did so.
jU JT j XIP EJE TP.

Variable Name Variable Type Variable Description


To store the given string of
txt String
maximum length 100.
Used to convert the letter to
ch char
other case
i int Used in for loop
s String Used to decode the string

16
Date: 14/07/20
5
Index Array
Question:
Class indexedarray contains the employee code of 100 employees. Some of the members are given
below:-
Class name : indexedarray
Data member
arr[] : int array
Member functions
indexedarray() : to assign the code to 0.
void fillarray() : to input the code in the arr[].
void sortarr() : to sort the array variable using selection sort
technique.
int binarysearch(int[],int) : to search and return 1 if an employee code is
found in the array object otherwise returns 0.

Specify the class indexedarray giving details of the constructor, void sortarr(), int binarysearch(). You
may assume that other member functions are written for you. Write the main function and call the
functions in Logical sequence.

Algorithm :
1. Start
2. Initialise array int arr[] with class size 10
3. Create a constructor to assign the code to 0
4. Create a function void fillarray() to input the code into arr[]
5. Create a function void sortarray() to sort the array variable
6. Declare int i,j,temp,small,pos
7. Run a for loop with the condition for( i=0;i<10;i++)
8. Initialise small=arr[i] and pos=i
9. Run an inner for loop with the condition for(j=i+1;j<9;j++)
10. If(arr[j]<small) then small=arr[j] and pos =j
11. Close the inner for loop
12. Initialise temp=arr[i], arr[i]=arr[pos] and arr[pos]=temp
13. Close the outer for loop and the function
14. Create a function int binarysearch(int a[],int n)
15. Initialise int l = 0, u = 9, m = 0
16. Run while loop with the condition while(l<=u)
17. m = (l+u)/2
18. if(n > a[m]) then l=m+1
19. else if(n < a[m]) then u = m-1
20. else return 1
21. Close the function and return 0
22. Open main method ,create an object and call the functions

17
23. Accept the code to be searched
24. int q = obj.binarysearch(arr, num)
25. if q==1,print “code is present” else print “ code is not present”
26. Stop

Program Listing:
import java.util.*;
class indexedarray{
static int arr[]=new int[10];
indexedarray(){
for(int i=0;i<10;i++)
arr[i]=0;
}
void fillarray(){
System.out.println("enter codes");
Scanner sc=new Scanner(System.in);
for(int i=0;i<10;i++)
arr[i]=sx.nextInt();
}
void sortarray(){
int i,j,temp,small,pos;
for( i=0;i<10;i++){
small=arr[i];
pos=i;
for(j=i+1;j<9;j++){
if(arr[j]<small){
small=arr[j];
pos=j;
}}
temp=arr[i];
arr[i]=arr[pos];
arr[pos]=temp;
}}
int binarysearch(int a[],int n){
int l = 0, u = 9, m = 0;

18
while(l<=u){
m = (l+u)/2;
if(n > a[m])
l=m+1;
else if(n < a[m])
u = m-1;
else
return 1;
}
return 0;
}
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
indexedarray obj = new indexedarray();
obj.fillarray();
obj.sortarray();
System.out.print("enter the code you want to search: ");
int num = sc.nextInt();
int q = obj.binarysearch(arr, num);
if(q==1)
System.out.println(" code is present ");
else
System.out.print(" code is not present ");
}}

Input:
enter codes
12345
125465
577
457
4668
973
345

19
8788
23456
9876
enter the code you want to search:8788
Output:
Code is present

Variable name Data type Description

arr[] int To store the employee code

temp int Used reaarrange

j int Used in the for loop

i int To run the for loop

pos int To store the duplicate of i

q int Used to call binarysearch()

Used as the lowerbound for


l int
binary search

Used as the upperbound for


u int
binary search

To store the number accepted


num int
from the user

To store the position of the


m int
searched element

Used as a parameter in the


n int
function binarysearch

Used as a parameter in the


a[] int
function binarysearch

small int To store the duplicate of arr[i]

20
Date: 17/07/20
6.
Prime Factors
Question:
A class PrimeFac has been defined for the following methods:
Class name : PrimeFac
Data members
num[] : array to store integers.
Freq[] : array to store the frequency of prime factors of numbers.
Member functions
PrimeFac() : constructor to initialize array elements to 0.
Void enter() : to enter values into array num[]
voidfrefac() : to determine the frequency of prime factors of the numbers stored in
num[] and assign it to freq[].
Voiddisp() : to display both the arrays.
Specify the class Mystring giving details of the constructor and void readstring(), int code(int index),
void word() only. The main function needs to be written.

Algorithm:
1. Start
2. Initialise the data members
3. Open constructor and assign a value to the data members
4. Open method void enter() and receive the values for the array from the user
5. Open method void frefac(), determine the frequency of the prime factors of num[] and store it
in freq[]
6. Open method void display() and print both the arrays
7. Open main method, create an object and call each function accordingly
8. Stop

Program Listing:
import java.util.*;
class PrimeFac{
int num[]=new int[50];
int freq[]=new int [50];
PrimeFac(){
for(int i=0;i<5;i++){
num[i]=0;

21
freq[i]=0;
}}
void enter(){
System.out.println("enter");
Scanner sx=new Scanner(System.in);
for(int i=0;i<5;i++){
num[i]=sx.nextInt();
}}
void frefac(){
int i,ctr=0,n;
for(int j=0; j<5; j++){
n=num[j];
for( i=1;i<=n;i++){
if(n% i == 0) {
int k;
for(k = 2; k < i ; k++){
if(i%k == 0)
break;
}
if (k == i)
ctr++;
}}
freq[j]=ctr;
ctr = 0;
}}
void disp(){
for(int i=0;i<10;i++){
System.out.print(num[i]+"---->\t");
System.out.println(freq[i]);
}}
public static void main(String [] args){
PrimeFac obj = new PrimeFac();
obj.enter();
obj.frefac();

22
obj.disp();
}}

Input:
enter
1 2 34 14 10 21 6
Output:
1----> 0
2----> 1
34----> 2
14----> 2
10----> 2
0----> 0
0----> 0
0----> 0
0----> 0
0----> 0

Variable Name Variable Type Variable Description


num[] int Array to store integers
Array to store the frequency
freq[] int
of prime factors of numbers
i, j, k, l int Used in for loop
Used to check if entered
c int
number is a prime number

23
Date: 21/07/20
7
Combining two arrays into one

Question:
A class Combine contains an array of integers which combines two arrays into a single array
including the duplicate elements, if any, and sorts the combined array. Some of the members of the
class are given below:
Class Name : Combine
Data members
com[ ] : integer array
size : size of the array
Member functions/methods
Combine(intnn) : parameterized constructor to assign size = nn
void inputarray( ) : to accept the array elements
void sort() : sorts the elements of combined array in
ascending
order using the selection sort technique.
void mix(Combine A, Combine B) : combines the parameterized object arrays
and stores
the result in the current object array along
with the
duplicate elements , if any.
void display( ) : displays the array elements.
Specify the class Combine giving details of the constructor(int ), void inputarray( ), void sort(), void
mix(Combine, Combine) and void display( ). Also define the main function to create an object and
call the methods accordingly to enable the task.

Algorithm:
1. Start
2. Create class Combine and constructor, declare variables int com[] and int size
3. Create method inputArray() and recieve the input for com[]
4. Create method sort() and sort the array in ascending order using selection sort
5. Create method mix()
6. Stop

Program Listing:
import java.io.*;

24
class Combine{
int com[];
int size;
public Combine(int num){
size = num;
com = new int[size];
}
public void inputArray()throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < size; i++)
com[i] = Integer.parseInt(br.readLine());
}
public void sort(){
for(int i = 0; i < size; i++){
int small = com[i];
int pos = i;
for(int j = i + 1; j < size; j++){
if(small > com[j]){
small = com[j];
pos = j;
}}
int temp = com[i];
com[i] = small;
com[pos] = temp;
}}
public void mix(Combine a, Combine b){
int index = 0;
for(int i = 0; i < a.size; i++)
this.com[index++] = a.com[i];
for(int i = 0; i < b.size; i++)
this.com[index++] = b.com[i];
}
public void display(){
for(int i = 0; i < size; i++)

25
System.out.print(com[i] + "\t");
System.out.println();
}
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("First array size: ");
int size1 = Integer.parseInt(br.readLine());
System.out.print("Second array size: ");
int size2 = Integer.parseInt(br.readLine());
Combine obj1 = new Combine(size1);
Combine obj2 = new Combine(size2);
Combine obj3 = new Combine(size1 + size2);
System.out.println("Enter first array elements:");
obj1.inputArray();
System.out.println("Enter second array elements:");
obj2.inputArray();
System.out.println("First array elements:");
obj1.display();
System.out.println("Second array elements:");
obj2.display();
obj3.mix(obj1, obj2);
obj3.sort();
System.out.println("Combined array:");
obj3.display();
}}

Output:
First array size: 2
Second array size: 2
Enter first array elements:
1
3
Enter second array elements:
9

26
46
First array elements:
1 3
Second array elements:
9 46
Combined array:
1 3 9 46

Variable Name Variable Type Variable Description


num[] int Array to store integers
Array to store the frequency of
freq[] int
prime factors of numbers
i, j, k, l int Used in for loop
Used to check if entered
c int
number is a prime number

27
Date: 24/07/20
8.
Transpose of an array
Question:
A transpose of an array is obtained by interchanging the elements of rows and columns. A class
Transarray contains a two dimensional integer array of order [ m x n]. The maximum value possible for
both ‘m’ and ‘n’ is 20. Design a class Transarray to find the transpose of a given matrix. The details of
the members of the class are given below:
Class name : Transarray
Data members
arr[][] : stores the matrix elements
m : integer to store the number of rows.
n : integer to store the number of columns.
Member functions
Transarray() : default constructor.
Transarray(int mm,int nn) : to inititalize the size of the matrix, m=mm,n=nn.
void fillarray() : to enter elements into the matrix.
void transpose(Transarray A) : to find the transpose of a given matrix.
void disaparray() : displays the array in a matrix form.
Specify the class Transarray giving details of the constructors, void fillarray(), void
transpose(Transarray) and void disparray(). Also write the main method and create an object for
Transarray class and call the functions in logical order.

Algorithm:
1. Create a method and accept the data to fill the array arr[][].
2. Create method transpose and do steps 3 to 4
3. for(int i = 0; i < m; i++) do steps 4
4. Open an inner for loop for(int j = 0; j < n; j++) and switch the element of row and columns.
5. Create a function dipArray and print the matrix.
6. Create main method and get the size of the array.
7. Swap the sizes of the original array and create a transpose array.
8. Call all the required function in order/
9. Stop.

Program Listing:
import java.util.*;
class Transarray{
int arr[][];
int m;

28
int n;
int trans[][];
Transarray(){
m=0;
n=0;
}
Transarray(int mm, int nn){
m=mm;
n=nn;
arr = new int[m][n];
trans =new int [m][n];
}
void fillArray(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter matrix elements:");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
arr[i][j] = sc.nextInt();
}}}
void transpose()
{
for(int i =0;i <m;i++){
for(int j =0;j<n;j++){
trans[i][j]=arr[j][i];
}}}
void disparray(){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
System.out.print(trans[i][j]);
}
System.out.println();
}}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);

29
System.out.print("enter number of rows: ");
int m = sc.nextInt();
System.out.print("enter number of columns: ");
int n = sc.nextInt();
Transarray obj1 = new Transarray(m,n);
Transarray obj2 = new Transarray(m,n);
obj1.fillArray();
System.out.println("Transposed Matrix:");
obj1.transpose();
obj1.disparray();
}}

Input:
Number of rows: 3
Number of columns: 2
Enter matrix elements:
245678
Output:
Transposed Matrix:
24
56
78

Variable Name Variable Type Variable Description


arr[] int Stores the matrix elements
m int To store the number of rows
To store the number of
n int
columns
i, j int Used in for loop

30
Date: 28/07/20
9
Symmetric Matrix
Question:
Write a program to declare a square matrix A[ ] [ ] of order (M x M) where ‘M’ is the number of rows and
the number of columns such that M must be greater than 2 and less than 10. Accept the value of M as user
input. Display an appropriate message for an invalid input. Allow the user to input integers into this
matrix. Perform the following tasks:
(a) Display the original matrix.
(b) Check if the given matrix is Symmetric or not.
A square matrix is said to be Symmetric, if the element of the ith row and jth column is equal to
the element of the jth row and ith column.
(c) Find the sum of the elements of the left diagonal and the sum of the elements of the right diagonal
of the matrix and display them.
Test your program with the sample data and some random data:
Example 1
INPUT : M=3
1 2 3
2 4 5
3 5 6
OUTPUT :
ORIGINAL MATRIX
1 2 3
2 4 5
3 5 6
THE GIVEN MATRIX IS SYMMETRIC
The sum of the left diagonal = 11
The sum of the right diagonal = 10

Algorithm:
1. Start
2. Receive input for n from user to create n*n matrix
3. Receive all the elements from user for the matrix
4. Using nested for loops, check whether the elements of ith row and jth column are equal to the
elements of jth row and ith column
5. If true, print that matrix is symmetric. Else, print that matrix is not symmetric
6. Add the left diagonal elements and right diagonal elements and print them
7. Stop

31
Program Listing:
import java.util.*;
public class Symmat{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to create a square materix minimum of 2 and maximum of
10 ");
int n=sc.nextInt();
int m[][]=new int[n][n];
int i=0;
int j=0;
int flag=0;
System.out.println("Enter the numbers for the square matrix");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
m[i][j]=sc.nextInt();
}}
for(i=0;i<n;i++){
for(j=0;j<=i;j++){
if(m[i][j]==m[j][i]);
else{
flag=1;
break;
}}}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.print(m[i][j]+" ");
}
System.out.println("");
}
if(flag==0){
System.out.println("it is a symmetric matrix");
}
else

32
System.out.println("It is not a symmetric matrix");
int sumr=0;
int sumc=0;
int k=0;
for(i=0;i<n;i++){
sumr=sumr+m[i][i];
}
for(i=0;i<n;i++){
sumc+=m[i][k];
k++;
}
System.out.println("left diagonal sum "+sumr);
System.out.println("right diagonal sum "+sumc);
}}

Output:
Enter a number to create a square materix minimum of 2 and maximum of 10
4
Enter the numbers for the square matrix
7
3
8
6
3
5
4
9
8
4
2
1
6
9
1

33
7
7386
3549
8421
6917
it is a symmetric matrix
6
4
4
6
left diagonal sum 21
right diagonal sum 20

Enter the numbers for the square matrix


3
6
5
2
36
52
It is not a symmetric matrix
left diagonal sum 5
right diagonal sum 11

Variable Name Variable Type Variable Description


Number of rows and
n int
columns for square matrix
Stores user defined values in
m[][] int
the matrix
i, j int Used in for loop
Used to determine if the
flag int
matrix is symmetric
Sum of right diagonal and
sumr, sumc int
left diagonal of matrix

34
Date:31/07/20
10
Prime Numbers
Question:
Write a Program in Java to fill a 2-D array with the first ‘m*n’ prime numbers, where ‘m’ is the
number of rows and ‘n’ is the number of columns. For example: If rows = 4 and columns = 5, then the
result should be:

Algorithm:
1. Start
2. Open method boolean isPrime(int n) and find all the prime numbers
3. Open main method and receive the number of rows and columns from user
4. Introduce 2 arrays, 1D and 2D, and fill the 2D array with prime numbers
5. Print the filled array
6. Stop

Program Listing:
import java.util.*;
class PrimeArr{
boolean isPrime(int n){
int c = 0;
for(int i = 1; i<=n; i++){
if(n%i == 0)
c++;
}
if(c == 2)
return true;

35
else
return false;
}
public static void main(String args[]){
PrimeArr ob = new PrimeArr();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int r1 = sc.nextInt();
System.out.print("Enter the number of columns: ");
int c1 = sc.nextInt();
int A[][]=new int[r1][c1];
int B[] = new int [r1*c1];
int i = 0, j;
int k = 1;
while(i < r1*c1){
if(ob.isPrime(k)==true){
B[i] = k;
i++;
}
k++;
}
int x = 0;
for(i=0;i<r1;i++){
for(j=0;j<c1;j++){
A[i][j] = B[x];
x++;
}}
System.out.println("The Filled Array is :");
for(i=0;i<r1;i++){
for(j=0;j<c1;j++){
System.out.print(A[i][j]+"\t");
}
System.out.println();
}}}

36
Output:
Enter the number of rows: 6
Enter the number of columns: 4
The Filled Array is :
2 3 5 7
11 13 17 19
23 29 31 37
41 43 47 53
59 61 67 71
73 79 83 89

Variable Name Variable Type Variable Description


Used to determine if the
c int
element is prime
r1 int Number of rows
c1 Number of columns
A[][] int Filled array
B[] int Used to fill array
i, j, k, x int Used in for and while loops

37
Date: 04/08/20
11
Matrix
Question:
A class Matrix contains a two dimensional integer array of order [ m x n ]. The maximum value
possible for both m and n is 25. Design a class Matrix to find the difference of the two matrices. The
details of the members of the class are given below:
Class name : Matrix
Data members
arr[][] : stores the matrix element
m : integer to store the number of rows
n : integer to store the number of columns
Member functions:
Matrix(int mm, int nn) : to initialize the size of the matrix m=mm and n=nn
void fillarray() : to enter the elements of the matrix
Matrix SubMat(Matrix A) : subtract the current object from the matrix of parameterized object
and return the resulting object.
void display() : display the matrix elements.
Specify the class Matrix giving details of the constructor(int,int), void fillarray(), Matrix
SubMat(Matrix) and void display(). Define the main() function to create an object and call the
functions accordingly to enable the task.

Algorithm:
1. Start
2. Initialise all instance variables.
3. Create a method fillarray and get all the elements of the array.
4. Create a method and subtract one matrix from another using two for loops.
5. Create main method and accept all required details regarding the array.
6. Call required functions in order and print the result.
7. Stop.

Program Listing:
import java.io.*;
class Matrix{
static BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
int arr[][];
int m,n;
Matrix(int mm, int nn) {

38
m=mm;
n=nn;
arr=new int[m][n];
}
void fillarray()throws IOException{
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
System.out.print("Enter Element at ["+i+"]["+j+"] : ");
arr[i][j]=Integer.parseInt(br.readLine());
}}}
Matrix SubMat(Matrix A){
Matrix C=new Matrix(m,n);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
C.arr[i][j]=A.arr[i][j]-this.arr[i][j];
}}
return C;
}
void display(){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}}
public static void main(String args[])throws IOException{
System.out.print("Enter the number of Rows: ");
int r=Integer.parseInt(br.readLine());
System.out.print("Enter the number of Columns: ");
int c=Integer.parseInt(br.readLine());
if(r>25 || c>25)
System.out.println("Out of Range");
else{
Matrix X=new Matrix(r,c);

39
Matrix Y=new Matrix(r,c);
Matrix Z=new Matrix(r,c);
System.out.println("\nEnter the 1st Matrix");
X.fillarray();
System.out.println("\nEnter the 2nd Matrix");
Y.fillarray();
System.out.println("\nThe 1st Matrix");
X.display();
System.out.println("\nThe 2nd Matrix");
Y.display();
Z=X.SubMat(Y);
System.out.println("\nThe Resultant Matrix");
Z.display();
}}}

Output:
Enter the number of Rows: 2
Enter the number of Columns: 3

Enter the 1st Matrix


Enter Element at [0][0] : 5
Enter Element at [0][1] : 6
Enter Element at [0][2] : 9
Enter Element at [1][0] : 4
Enter Element at [1][1] : 3
Enter Element at [1][2] : 8

Enter the 2nd Matrix


Enter Element at [0][0] : 4
Enter Element at [0][1] : 3
Enter Element at [0][2] : 1
Enter Element at [1][0] : 7
Enter Element at [1][1] : 3
Enter Element at [1][2] : 5

40
The 1st Matrix
5 6 9
4 3 8

The 2nd Matrix


4 3 1
7 3 5

The Resultant Matrix


-1 -3 -8
3 0 -3

Variable Name Variable Type Variable Description


arr[][] int stores the matrix element
integer to store the number
m int
of rows
integer to store the number
n int
of columns
i, j int Used in for loop
Number of rows and
r, c int
columns

41
Date: 07/08/20
12
Fibonacci Series

Question:
A class recursion has been defined to find the Fibonacci series upto a limit. Some of the members of
the class are given below:
Class Name : recursion
Data Members
a
b
c
limit : int
Member functions
recursion() : constructor to assign a,b,c with appropriate values.
void input() : to accept the limit of the series.
int fib(int n) : to return the nth Fibonacci term using recursive technique.
void genearatefibseries() : to generate the Fibonacci series upto the given limit. Specify the class
recursion giving details of the constructor, int fib() , void generatefibseries(). You may assume other
functions are written for you and you need not write the main function

Algorithm:
1. Start
2. Initialize the data members a, b, c, limit
3. Open constructor and assign values to all data members
4. Open method void input()
5. Accept limit of the series from the user
6. Open method int fib(int n)
7. Run the following:
if(n<=1)
return a;
else if(n==2)
return b;
else
return (fib(n-1)+fib(n-2));
8. Open method void generatefibseries()
9. Print the Fibonacci series upto the limit input by the user
10. Stop

42
Program Listing:
import java.util.*;
class recursion{
int a,b,c,limit;
recursion(){
a=0;
b=1;
c=0;
limit=0;
}
void input(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the limit : ");
limit = sc.nextInt();
}
int fib(int n){
if(n<=1)
return a;
else if(n==2)
return b;
else
return (fib(n-1)+fib(n-2));
}
void generatefibseries(){
System.out.println("The Fibonacci Series is:");
for(int i=1;i<=limit;i++){
c=fib(i);
System.out.print(c+" ");
}}}

Output:
Enter the limit : 5
The Fibonacci Series is:
0 1 1 2 3

43
Variable Name Variable Type Variable Description
a, b, c int Initial value of series
i int Used in for loop

44
Date: 11/08/20
13
String Palindrome
Question:
A class Revstr defines a recursive function to reverse a string and check whether it is a palindrome.
The details of the class are given below:

Class name : Revstr


Data members
Str : stores the string.
Revst : stores the reverse of the string.
Member functions
void getStr() : to accept the string.
void recReverse(int) : to reverse the string using recursive technique.
void check() : to display the original string, its reverse and
whether the string is a palindrome or not.

Specify the class Revstr giving details of the functions void getStr(), void recReverse(int) and void
check(). Also write the main method.

Algorithm:
1. Start
2. Initialize data members Str and Revst
3. Open constructor and assign values to data members
4. Open method void getStr()
5. Accept string from user
6. Open method void recReverse(int x)
7. Reverse the string using recursive technique
8. Open method void check()
9. Display actual string and reversed string and check if the reversed string is a palindrome
10. Open main method
11. Call each function in a logical order
12. Stop

Program Listing:
import java.util.*;
public class revstr{
String str;
String revst;
revstr(){
str=" ";
revst="";
}

45
public void getstr(){
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
try{
str= sc.next();
}
catch(Exception e){
System.out.println(e);
}
revst="";
}
void recreverse(int i){
if(i==0){
return;
}
else{
revst=revst+str.charAt(i-1);
recreverse(i-1);
}}
public void check(){
System.out.println(str);
System.out.println(revst);
if(str.equals(revst))
System.out.println(“\””+str+”\” is a palindrome”);
else
System.out.println("\”"+str+"\” is not a palindrome");
}
public static void main(String[]args){
Revstr p = new Revstr();
p.getstr();
p.recreverse(int x);
p.check();
}}

46
Input:
enter a sentence:
was it a cat i saw
Output:
was it a cat i saw
was it a cat i saw
“was it a cat i saw” is a palindrome

Variable Name Variable Type Variable Description


Str String The string
Revstr String The reverse of the string
length int Length of string

47
Date:14/08/20
14
Expressing digits in words
Question:
Class Convert has been defined to express digits of an integer in words. The details of the class are
given below:
Class name : Convert
Data members
n : integer whose digits are to be
expressed in words.
Member functions
Convert() : constructor to assign 0 to n.
void inpnum() : to accept the value of n.
void extdigit(int) : to extract the digits of n using
recursive technique.
void num_to_words(int) : to display the digits of an integer
in words.

Algorithm:
1. Start
2. Declare int n
3. Creat a constructor and initialise n=0
4. Create a function void inpnum()
5. Accept n
6. Create a function void extdigit(int a)
7. int x = a%10 to extract the last digit
8. a =a/ 10 to store the remaining digits
9. if(a!=0) then ,extdigit(a)
10. After the if condition Convert.num_to_words(x)
11. Create a function static void num_to_words(int a)
12. Create switch(a) and print the corresponding number in words
13. Create main method
14. Create an object,obj and call the functions
15. Stop

Program Listing:
import java.util.*;
class Convert{
static int n;
Convert(){
n = 0;

48
}
void inpnum(){
Scanner sc = new Scanner (System.in);
System.out.println("Enter: ");
n = sc.nextInt();
}
void extdigit(int a){
int x = a%10;
a /= 10;
if(a!=0)
extdigit(a);
Convert.num_to_words(x);
}
static void num_to_words(int a){
switch( a ){
case 0: System.out.print("zero "); break;
case 1: System.out.print("one "); break;
case 2: System.out.print("two "); break;
case 3: System.out.print("three "); break;
case 4: System.out.print("four "); break;
case 5: System.out.print("five "); break;
case 6: System.out.print("six "); break;
case 7: System.out.print("seven "); break;
case 8: System.out.print("eight "); break;
case 9: System.out.print("nine "); break;
}}
public static void main(String args[]){
Convert obj = new Convert();
obj.inpnum();
obj.extdigit(n);
}}

49
Input:
Enter:
1234
Output:
one two three four

Variable Name Variable Type Variable Description


Integer whose digits are to
n int
be expressed in words
r, x int Used in recursion
a[] int Used to store number names

50
Date: 18/08/20
15
Bank Account
Question: Class BankAcc contains details about the account holder. New account no is obtained via a
static member nextAccNo, which is incremented with every new account creation. It has methods
deposit() and withdraw() along with getBalance() and display().
Class SavingAcc inherits from BankAcc and additionally stores rate of interest (monthly). It has a
method addInterest() that computes interest and adds it to the balance. It overrides display() method to
BankAcc.

Algorithm:
1. Start
2. Create class BankAcc
3. Initialise nextAccNo and declare data members String firstName, String surName, String
address, int accNo, long balance
4. Open constructor, initialise all the data members and increment nextAccNo
5. Open function getBalance() and return balance
6. Open function deposit(long amount) and calculate the balance
7. Open function withdraw(long amount), check if the balance is greater than 1000 and allow
withdrawal
8. Open function display() and display the name of the customer, account number and account
balance
9. Close class BankAcc
10. Create subclass SavingAcc and declare data member double rate
11. Open function addInterest, calculate interest and add it to the balance
12. Open constructor, call all the initialised data members from the super class and initialise data
member rate
13. Open main method and run driver program
14. Stop

Program Listing:
public class BankAcc{
protected static int nextAccNo=1;
protected String firstName;
protected String surName;
protected String address;
protected int accNo;
protected long balance;
public BankAcc(String fn, String sn, String ad){
firstName=fn;
surName=sn;
address=ad;

51
balance=1000;
accNo=nextAccNo;
++nextAccNo;
}
public long getBalance(){
return balance;
}
public void deposit(long amount){
balance=balance+amount;
}
public void withdraw(long amount){
if((balance-amount)>1000)
balance=balance-amount;
else
System.out.println("Can't withdraw as the min balance would be <1000 after this
withdrawal.");
}
public void display(){
System.out.println("\nCustomer "+firstName+" "+surName);
System.out.println(" Account Number = "+accNo);
System.out.println(" Account balance = "+(balance/100.0));
}}

public class SavingAcc extends BankAcc{


private double rate;
public void addInterest(int months){
long interest;
interest=(long)(balance*rate/100.0*months/12.0);
balance=balance+interest;
}
public SavingAcc(String fn, String sn, String ad, double r){
super(fn,sn,ad);
rate=r;
}

52
public static void main(String arg[]){
BankAcc b1,b2;
b1=new BankAcc("Rubina", "Khan", "D.Park");
b2=new BankAcc("Tupur", "Sen", "S.lake");
b1.deposit(15500);
b2.deposit(10000);
b1.display();
b2.display();
b1.withdraw(5500);
b2.withdraw(11000);
b1.display();
b2.display();
SavingAcc depacc;
depacc=new SavingAcc("Bula", "Paul", "P.Lane", 9.0);
depacc.deposit(10000);
depacc.addInterest(10);
depacc.display();
}}

Output:
Customer Rubina Khan
Account Number = 1
Account balance = 165.0

Customer Tupur Sen


Account Number = 2
Account balance = 110.0
Can't withdraw as the min balance would be <1000 after this withdrawal.

Customer Rubina Khan


Account Number = 1
Account balance = 110.0

53
Customer Tupur Sen
Account Number = 2
Account balance = 110.0

Customer Bula Paul


Account Number = 3
Account balance = 118.25

Variable Name Variable Type Variable Description


firstName, surName String Name of Customer
accNo int Account number
balance long Account balance
amount long Amount withdrawn
rate double To calculate Interest
interest long Calculated interest

54
Date: 21/08/20
16
Calendar
Question:
Write a program to implement Manager class that inherits from class Employee. The specification of
these classes are:
Employee (Data members): name, salary, hireDay
Methods:
Constructor
print(): prints name and salary along with hire year
raiseSalary(): raises salary by the given percentage
hireYear(): returns the hire year
Manager (Data members): secretaryName
Methods:
Constructor
raiseSalary()
setSecretaryName(): sets the secretary name
getSecretaryName(): returns the secretary name

Algorithm:
1. Start
2. Create class Day and declare data members int year, month and day
3. Open constructors, assign values from the Calendar and initialise the data members
4. Open function getYear() and return year
5. Create subclass Employee and declare data members String name, double salary, Day
hireDay
6. Open constructor and initialise data members
7. Open function print() and print the name of the employee, their salary and the day when
they were hired
8. Open function raiseSalary(double byPercent) and calculate the raised salary
9. Open function hireYear() and return hireDay.getYear()
10. Create subclass of Employee, Manager, and declare data member String secretaryName
11. Open constructor, call the variables of the super class and initialise secretaryName
12. Open function raiseSalary(double byPercent) and calculate the salary per year, including
the bonus
13. Open function setSecretaryName(String n) and declare secretaryName=n
14. Open function getSecretaryName() and return secretaryName
15. Create class ManagerTest
16. Open main method and run driver program to display the name of the department
secretary
17. Stop

55
Program Listing:
import java.util.Calendar;
public class Day{
int year, month, day;
Day(){
Calendar cal=Calendar.getInstance();
day=cal.get(Calendar.DATE);
month=cal.get(Calendar.MONTH)+1;
year=cal.get(Calendar.YEAR);
}
Day(int y, int m, int d){
year=y; month=m; day=d;
}
int getYear(){
return year;
}}

public class Employee{


public Employee(String n, double s, Day d){
name=n;
salary=s;
hireDay=d;
}
public void print(){
System.out.println(name+" "+salary+" "+hireYear());
}
public void raiseSalary(double byPercent){
salary*=1+byPercent/100;
}
public int hireYear(){
return hireDay.getYear();
}
private String name;
private double salary;

56
private Day hireDay;
}

public class Manager extends Employee{


public Manager(String n, double s, Day d){
super(n,s,d);
secretaryName="";
}
public void raiseSalary(double byPercent){
Day today=new Day();
double bonus=0.5*(today.getYear()-hireYear());
super.raiseSalary(byPercent+bonus);
}
public void setSecretaryName(String n){
secretaryName=n;
}
public String getSecretaryName(){
return secretaryName;
}
private String secretaryName;
}

public class ManagerTest{


public static void main(String[] args){
Manager boss=new Manager("Nikita Sharma", 75000, new Day(1997,12,15));
boss.setSecretaryName("JaneRobin");
Employee[] staff=new Employee[3];
staff[0]=boss;
staff[1]=new Employee("Jane Robin",35000,new Day(2009,10,1));
staff[2]=new Employee("Tony Singh",38000,new Day(2010,3,15));
int i;
for(i=0;i<3;i++) staff[i].raiseSalary(5);
for(i=0;i<3;i++) staff[i].print();
System.out.println("The department secretary is "+boss.getSecretaryName());

57
}}

Output:
Nikita Sharma 87375.0 1997
Jane Robin 36750.0 2009
Tony Singh 39900.0 2010
The department secretary is Jane Robin

Variable Name Variable Type Variable Description


year, month, date int Calendar date values
name String Name of Employee
salary double Salary paid

58
Date: 25/08/20
17
Duplicate characters
Question:
Write a class Sentence to store a sentence and another class Duplicate to replace the duplicate
characters. The details of the classes are given below:
Class name : Sentence
Data members/instance variables:
str : To store a sentence in the string variable of protected type.
Member functions/methods:
Sentence( ) : Constructor to assign string variable.
void Accept( ) : To accept a sentence in the variable str.
void Display( ) : To display the sentence after performing the task.
Class name : Duplicate
Data members/instance variables:
P: To store the length of sentence str.
Member functions/methods:
void Remove( ) : To remove the duplicate characters in sequence by Its single occurrence in the
string.
The new string should contain only one space between two words, if it contains more spaces in the
original string. For example, Ammmmiiit Kuulkkkkarnni iiiiss aa sssttudddeentt of ccclllassss
tttwweellllvvvve Output: Amit Kulkarni is a student of class twelve
(i) Specify the class Sentence giving the details of the function void Accept( ) and void Display( ). (ii)
Using the concept of inheritance, specify the class Duplicate giving the details of the functions void
Remove( )

Algorithm:
1. Initialise all the instance variable.
2. Create a method and accept the string.
3. Create a method to display the result.
4. Create a function remove to scan for duplicate words and remove the duplicate characters :
String nstr="";
p=str.length();
for(int i=0;i<p-1;i++){
if(str.charAt(i)!=str.charAt(i+1)){
nstr += str.charAt(i);
}}

59
5. Stop.

Program Listing:
import java.util.*;
public class Sentence{
String str;
public Sentence(){
str="";
}
void Accept(){
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
str=sc.nextLine();
}
void Display(){
System.out.println(str);
}}

class Duplicate extends Sentence{


int p;
Duplicate(){
super();
Accept();
}
void Remove(){
String nstr="";
p=str.length();
for(int i=0;i<p-1;i++){
if(str.charAt(i)!=str.charAt(i+1)){
nstr += str.charAt(i);
}}
str = nstr;
Display();
}}

60
Input:
enter a sentence
Ammmmiiit Kuulkkkkarnni iiiiss aa sssttudddeentt of ccclllassss tttwweellllvvvve
Output:
Amit Kulkarni is a student of class twelve

Variable Name Variable Type Variable Description


To store a sentence in the
str String
string variable
p int Length of string
i int Used in for loop

61
Date: 28/08/20
18
Bookmarks in a Stack
Question:
A bookshelf is designed to store the bookmarks in a stack with LIFO operation. Design a class Book
with the necessary specifications.
Class name :Book
Data members/instance variables:
name[ ]: stores the names of the books
point : stores the index of the topmost book
max :stores the maximum capacity of the bookshelf
Methods/member functions:
Book(int cap): constructor to initialise the data members max, n, cap and point = -1
void tell( ) :displays the name of the book which was last entered in the shelf. If there is no book left
in the shelf, displays the message "SHELF EMPTY"
void add(String v) :adds the name of the book to the shelf if possible, otherwise displays the message
"SHELF FULL"
void display( ): displays all the names of the books available in the shelf.
Specify the class Book giving the details of ONLY the functions void tell( ) and void add(String).
Assume that the other functions have been defined. The main functions need not be written.

Algorithm:
1. Start
2. Declare name, point and max
3. Create constructor
4. Initialise this.max=cap, this.point=-1and this.name=new String[max]
5. Create function void tell( )
6. if (point == -1), print “SHELF EMPTY!”
7. else, print “The topmost book is" + name[point]”
8. Create function void add(String v)
9. this.point+=1
10. if(this.point==max), print “SHELF FULL!”
11. else, this.name[this.point]=v
12. Close function add
13. Create function void display( ) (already defined as per the question)
14. Stop

Program Listing:
public class Book{
String[] name;

62
int point;
int max;
public Book(int cap){
this.max=cap;
this.point=-1;
this.name=new String[max];
}
void tell(){
if(point==-1)
System.out.println("SHELF EMPTY!");
else
System.out.println("The topmost bok is" + name[point]);
}
void add(String v){
this.point+=1;
if(this.point==max){
System.out.println("SHELF FULL!");
}
else{
this.name[this.point]=v;
}}}

Output:
Enter maximum capacity of shelf
5
Enter 1 to display the name of the book last entered, 2 to add the name of a book, 3 to display the
names of all the books
2
Enter the name of the book
The Alchemist
Enter 1 to display the name of the book last entered, 2 to add the name of a book, 3 to display the
names of all the books
2
Enter the name of the book

63
To Kill a Mockingbird
Enter 1 to display the name of the book last entered, 2 to add the name of a book, 3 to display the
names of all the books
2
Enter the name of the book
Diary of a Wimpy Kid
Enter 1 to display the name of the book last entered, 2 to add the name of a book, 3 to display the
names of all the books
1
Diary of a Wimpy Kid
Enter 1 to display the name of the book last entered, 2 to add the name of a book, 3 to display the
names of all the books
2
Enter the name of the book
The Great Gatsby
Enter 1 to display the name of the book last entered, 2 to add the name of a book, 3 to display the
names of all the books
3
The Alchemist
To Kill a Mockingbird
Diary of a Wimpy Kid
The Great Gatsby
Enter 1 to display the name of the book last entered, 2 to add the name of a book, 3 to display the
names of all the books
2
Enter the name of the book
War and Peace
SHELF FULL!

Variable Name Variable Type Variable Description


Stores the names of the
name[] String
books
Stores the index of the
point int
topmost book
Stores the maximum
max int
capacity of the bookshelf

64
65
Date: 01/09/20
19
Word Pile
Question:
WordPile is an entity which can hold a maximum of 20 characters. The restriction is that a character
can be added or removed from one end only. Some of the members of classes are given below:
Class name: WordPile
Data members/instance variables:
ch[ ] : character array to hold the character elements
capacity: integer variable to store the maximum capacity
top: to point to the index of the topmost element
Methods/Member functions:
WordPile( int cap) : constructor to initialise the data member capacity = cap, top = -1 and create the
WordPile
void pushChar( char v) : adds the character to the top of WordPile if possible, otherwise output a
message “WordPile is full”
char popChar() : returns the deleted character from the top of the WordPile if possible, otherwise it
returns ‘\\’
Specify the class WordPile giving the details of the constructor, voidpushChar(char) and char
opChar().The main function and algorithm need not be written.

Algorithm:
1. Start
2. Declare ch, capacity and top
3. Create a constructor
4. Assign capacity=cap, top=-1, ch=new char[cap]
5. Create a function pushChar( char v)
6. if(top==capacity-1) then print “WordPile is full”
7. else, increment top
8. Assign ch[top]=v
9. Close function
10. Create function char popchar()
11. if(top==-1), return ‘\\’
12. else char c=ch[top] and decrement top
13. return c
14. Stop

Program Listing:
public class WordPile{
char[] ch;
int capacity;

66
int top;
public WordPile(int cap){
capacity=cap;
top=-1;
ch=new char[cap];
}

void pushChar(char v){


if(top==capacity-1)
System.out.println("WordPile is full");
else{
top++;
ch[top]=v;
}}
char popChar(){
if(top==-1)
return'\\';
else{
char c=ch[top];
top--;
return c;
}}}

Output:
Enter no. of characters
5
1. Push Character
2. Pop Character
Enter your choice:1
Enter thecharacter:8
1. Push Character
2. Pop Character
Enter your choice:1
Enter thecharacter:9

67
1. Push Character
2. Pop Character
Enter your choice:2
9 popped.
1. Push Character
2. Pop Character
Enter your choice:1
Enter thecharacter:5
1. Push Character
2. Pop Character
Enter your choice:1
Enter thecharacter:6
1. Push Character
2. Pop Character
Enter your choice:2
6 popped.
1. Push Character
2. Pop Character
Enter your choice:7
1. Push Character
2. Pop Character
Enter your choice:2
1. Push Character
2. Pop Character
Enter your choice:6
WordPile is full

Variable Name Variable Type Variable Description


Character array to hold the
ch[] char
character elements
Integer variable to store the
capacity int
maximum capacity
To point to the index of the
top int
topmost element

68
Date: 04/09/20
20
Queue
Question:
Queue is an entity which can hold a maximum of 100 integers. The queue enables the user to add
integers from the rear and remove integers from the front. Define class Queue with the following
details:
Class Name: Queue
Data members/instance variables:
Que[ ]: array to hold the integer elements
size: stores the size of the array
front: to point the index of the front
rear: to point the index of the rear
Member functions:
Queue (int mm): constructor to initialize the data size - mm, front -1, rear -1
void addele(int v) : to add integer from the rear if possible else display the message "Overflow"
int delele( ): returns elements from front if present, otherwise displays the message "Underflow" and
return -9999
void display( ) : displays the array elements
Specify the class Queue giving details of ONLY the functions void addele(int) and int deltic().
Assume that the other functions have been defined. The main function and algorithm need NOT be
written.

Algorithm:
1. Start
2. Declare Que[], front, rear and size
3. Create a constructor
4. Initialize size=mm, front =-1, rear= -1 and Que= new int [size]
5. Create a function boolean isEmpty( ) and return front = = -1
6. Create a function void addele
7. if (rear == -1), initialise front = 0 , rear = 0 and Que[rear]=v
8. else if (rear+1<Que.length)
9. else , print “OVERFLOW!!”
10. Create function int delete( )
11. Declare elemnt
12. if(isEmpty()), return -9999;

69
13. else elemnt=Que[front]
14. if ( front = = rear), them front= rear= -1
15. else, increment front and return elemnt
16. Close function delete
17. Create function display and print Que[i]
18. Stop

Program Listing:
public class Queue{
protected int Que[];
protected int front,rear;
protected int size;
public Queue(int mm){
size=mm;
front=-1;
rear=-1;
Que=new int[size];
}
boolean isEmpty(){
return front==-1;
}
public void addele(int v){
if(rear==-1){
front=0;
rear=0;
Que[rear]=v;
}
else if(rear+1<Que.length)
Que[++rear]=v;
else
System.out.println("OVERFLOW!!");
}

public int delete(){

70
int elemnt;
if(isEmpty())
return -9999;
else{
elemnt=Que[front];
if(front==rear)
front=rear=-1;
else
front++;
return elemnt;
}}
public void display(){
for(int i=front;i<=rear;i++)
System.out.println(Que[i]);
}}

Input:
Enter size of the queue
5
Enter 1 to add, 2 to delete
1
Add number to queue
8
Enter 1 to add, 2 to delete
1
Add number to queue
7
Enter 1 to add, 2 to delete
2
Enter 1 to add, 2 to delete
1
Add number to queue
5
Enter 1 to add, 2 to delete

71
1
Add number to queue
3
Output:
7
5
3

Variable Name Variable Type Variable Description


Array to hold the integer
Que[] int
elements
size int Stores the size of the array
To point the index of the
front int
front
To point the index of the
rear int
rear
elemnt int Used in delete()

72

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy