Baibhav Kumar 12 B Final Submission
Baibhav Kumar 12 B Final Submission
NAME : BAIBHAV
KUMAR CLASS/ SECTION :
XII-B UNIQUE ID : --
INDEX NUMBER : --
CERTIFICATE OF AUTHENTICITY
Madhurima Acharya
(HOD Computer Science)
Sonali Sen
(Principal)
INDEX
TOPICS
S.NO PG NO.
ARRAYS
Checking if the Matrix is symmetric or not. Also calculates the
6. sum of left and right diagonals of the matrix 29
DATA STRUCTURE
Program to implement Stack
16. 68
Program to implement LinearQ
17. 71
Program to implementing Dequeue
18. 74
Program to implementing CircularQ
19. 78
Program to implement Linked List
20. 82
Stack using Linked List
21. 88
Queue using Linked List
22. 93
INHERITANCE
Calculating salary of an employee by taking data from two
23. classes Employee and Salary 98
Program to calculate the salary of a daily wager based on
24. number of hours worked by inheriting classes Worker and 102
Wages
Program to find ranks of 50 students using inheritance of
25. classes Records and Rank 106
RECURSION
Finding out sum of the series recursively
28. 118
x2/1! + x4/3!+x6/5!+….x^n/(n-1)!
MISCELLANEOUS PROGRAMS
Program to perform Insertion Sort in a single dimension array
33. 135
Program to perform Merge Sort in a single dimension array
34. 138
Program to perform Quick Sort in a single dimension array
35. 142
1)
QUESTION-
A class Collection contains an array of 100 integers. Using the following class
description, create an array with common elements from two integer arrays. Some
of the members of the class are given below:
Class name : Collection
Data members :
ar[] : integer array of 100 elements
len : length of the array
Member methods :
Collection() : default constructor
Collection(int ) : parameterized constructor to assign the length
of the array
void input() : reads array elements
Collection common(Collection): return the Collection containing the
common Elements of current Collection and the collection object passed
as parameter.
void display() : displays the array Collection elements
ALGORITHM-
Step 1: Start
Step 2: Declare an array arr of size 100, arr2 of size len, set J=0
Step 3: Read integers into array of len numbers
Step 4: run loop from I=0 to len
Step 5: compare the elements of two arrays at Ith position
Step 6: if they are equal, store the element in arr2[Jth]
location Step 7: increment I by 1
Step 8: end loop
Step 9: Print the array with common elements and loop
Step 10: Stop
SOURCE CODE-
import java.util.*;
class Collection {
int[] ar;
int len;
public Collection(int len) { // constructor to initialize data
members this.len = len;
ar = new int[len];
}
void input(int[] arr) {
for (int i = 0; i < len; i++)
{ ar[i] = arr[i];
}
}
Collection common(Collection col) {
Collection commonCol = new Collection(len);
for (int i = 0; i < len; i++) {
for (int j = 0; j < col.len; j++) {
if (ar[i] == col.ar[j]) { // taking common elements
commonCol.ar[i] = ar[i];
break;
}
}
}
return commonCol; // returning from the method
}
int[] toArray() {
int[] arr = new int[len];
for (int i = 0; i < len; i++)
{ arr[i] = ar[i];
}
return arr;
}
public void display() { // displaying the array
for (int i = 0; i < len; i++) {
if (ar[i] != 0)
{ System.out.print(ar[i] + "
");
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the length of the first array:
"); int len1 = in.nextInt(); // taking user input
int[] arr1 = new int[len1];
}
Collection col1 = new Collection(len1); // creating object
Collection col2 = new Collection(len2);
col1.input(arr1);
col2.input(arr2);
Collection commonCol = col1.common(col2);
int[] commonArr = commonCol.toArray();
commonCol.display(); // Display the common elements
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
ar int[] To store the first array
len int To store the length of
the first array
i int Loop control variable
j int Loop control variable
arr int[] To store the second
array
len1 int To take user input
arr1 int[] To take user input
len2 int To take user input
arr2 int[] To take user input
OUTPUT-
2)
QUESTION-
A Transpose of an array is obtained by interchanging the elements of the 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
Data :
members/instance
variables
arr[][] : stores the matrix elements
Member functions :
Specify the class Transarray giving the details of the constructors, void fillarray(),
void transpose(Transarray) and void disparray(). You need not write the main
function.
ALGORITHM-
Step 1: Declare a double dimension array of size M x N
Step 2: Read elements into the array
Step 3: run outer loop from I=0 to M
Step 4: run inner loop from J=0 to N
Step 5: Temp=array [I][J]
Step 6: array[I][J] = array [J]
{I] Step 7: array [J][I] = Temp
Step 8: increment J by 1
Step 9: increment I by 1
Step 10: End inner loop
Step 11: End outer loop
Step 12: Print transposed array
Step 13: Stop
SOURCE CODE-
import java.util.*;
class Transarray{
int arr[][];
int m,n;
Transarray(){ // default constructor
m=0;n=0;
}
m=mm;n=nn;
arr = new int[m][n];
}
void fillarray(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the elements of the matrix"); // accepting user
input
for(int i=0;i<m;i++)
{ for(int j=0;j<n;j+
+){
arr[i][j]=in.nextInt();
}
}
}
void transpose(Transarray a){
int a1[][] = new int[a.arr[0].length][a.arr.length];
for(int i=0;i<a1.length;i++){
for(int j=0;j<a1[0].length;j++){
a1[i][j] = a.arr[j][i];
}
}
System.out.println("The transpose of the given matrix is: "); // displaying the
transpose
for(int i=0;i<a1.length;i++)
{ for(int j=0;j<a1[0].length;j+
+){
System.out.print(a1[i][j]+" ");
}
System.out.println();
}
}
void disparray(){
System.out.println("The original matrix is: "); // displaying the array
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
{ System.out.print(arr[i][j]+"
");
}
System.out.println();
}
}
public static void main(String args[])
{ Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns");
VDT-
VARIABLE NAME TYPE PURPOSE
arr int[][] To store the integers
m int To store the dimensions
n int To store the dimensions
mm int To store the dimensions
nn int To store the dimensions
i int Loop control variable
j int Loop control variable
a int[][] To transpose the array
OUTPUT-
3)
QUESTION-
A class Array is declared as follows:
Class name : Array
Data members :
ar[] : integer array of size 100
n : size of the array
num : integer variable
Member methods :
Array() : a constructor to store 0 at each location of ar[] and to
n. void getArray() : to input n integers in array
int process(Array B, int k): to assign k to num and return the frequency of num
from the array ar[] from the array object B.
Array merge(Array a) : merge the current array with the
parameterised array.
void display() : to print the array elements in such a way that
only 4 elements of array should be printed in one line with two spaces in between
the numbers.
Write main() method and call the above methods to generate the output.
ALGORITHM-
Step 1: Declare two integer arrays of size N
Step 2: Read elements into the arrays
Step 3: Enter the number whose frequency to be checked in K
Step 4: Run loop from I=0 to N
Step 5: Check if array1[I]=K then increment CTR by 1
Step 6: End loop
Step 7: Declare a third array of size array1.N + array2.N, set X=0
Step 8: Run loop from I=0 to array1.N
Step 9: Shift the elements of array1 to array 3 by array3[X++]=array1[I]
Step 10: Increment I by 1
Step 11: End loop
Step 12: Run a loop from I=0 to array2.N
Step 13: Shift the elements of array2 to array 3 by array3[X++]=array2[I]
Step 14: Increment I by 1
Step 15: End loop
Step 16: Print the merged array
Step 17: Stop
SOURCE CODE-
import java.util.*;
class Array{
int ar[];
int n, num;
Array(){ // constructor to initialize data members
ar=new int[n];
for(int i=0;i<n;i++)
{ ar[i] = 0;
}
n =0;
}
void getArray(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements");
n= in.nextInt(); // accepting user input
ar = new int[n];
for(int i=0;i<n;i++){
if(ar[i]==num){ // finding the frequency
c++;
}
}
return c;
}
Array merge(Array a)
{ Array ob = new
Array();
ob.ar = new int[this.ar.length + a.ar.length];
}
else{
ob.ar[i] = a.ar[i-this.ar.length];
}
}
return ob;
}
void display(){
System.out.println("The array is "); // displaying the array
for(int i=0;i<ar.length;i++){
if(i!=0 && i%4==0)
{ System.out.println();
}
System.out.print(ar[i]+" ");
}
System.out.println();
}
public static void main(String args[])
{ Scanner in = new Scanner(System.in);
Array ob1 = new Array(); // creeating object
ob1.getArray(); // calling methods
ob1.display();
System.out.println("Enter element to be searched");
int a = in.nextInt();
System.out.println("The frequency is " + ob1.process(ob1, a));
VDT-
VARIABLE NAME TYPE PURPOSE
ar int[] To store the array
n int To store the length of
the array
num int To store the number
to be searched
i int Loop control variable
k int To store the number
to be searched
c int To store the frequency
a int To accept user input
OUTPUT-
4)
QUESTION-
A class Time is declared as
follows: Class name : Time
Data members :
hrs, min : integers to store hour and minute
Methods :
Time() : default constructor to assign 0 to data members
void getTime(int h, int m): assigns hours and minutes
void printTime() : prints time in hh:mm format
Time sumTime(Time t1, Time t2): adds two time t1 with t2 and return them.
Implement the above class and write main() method and call the above methods to
generate the output.
ALGORITHM-
Start 1: Start
Step 2: Read hours and mins of Time1
Step 3: Read hours and mins of Time2
Step 4: Create a temporary object Time3
Step 5: Perform Time3->hours= Time1->hours+Time->hours
Step 6: Perform Time3->min= Time1>min+Time2>min
Step 7: If Time3.mins >=60 then
Step 8: Time3->hours+=Time3->min/60
Step 9: Time3->mins=Time3->min
%60 Step 10: Display Time3
Step 11: Stop
SOURCE CODE-
import java.util.*;
class Time{
int hrs,min;
void printTime()
{ System.out.println(hrs + ":" +
min);
}
}
}
else{
ob.min = t1.min + t2.min;
ob.hrs = t1.hrs + t2.hrs;
if(ob.hrs>=24){
ob.hrs-=24;
}
}
return ob;
}
public static void main(String args[]){
Time ob1 = new Time(); // creating object
Time ob2 = new Time(); // creating object
Scanner in = new Scanner(System.in);
System.out.println("Enter first time in hours and minutes");
ob1.getTime(in.nextInt(),in.nextInt()); // accepting user input
ob1.printTime(); // calling methods
System.out.println("Enter second time in hours and minutes");
ob2.getTime(in.nextInt(),in.nextInt());
ob2.printTime(); // calling methods
System.out.println("On adding the time:");
ob1.sumTime(ob1,ob2).printTime(); // calling methods
}
VDT-
VARIABLE NAME TYPE PURPOSE
hrs int To store hours
min int To store minutes
h int Parameter variable
m int Parameter variable
OUTPUT-
5)
QUESTION-
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
ALGORITHM-
Step 1: Start
Step 2: Read the value of row and column and declare matrix A[r][c], B[r][c], C[r]
[c]
Step 3: Read the values in A[][] and B[][]
Step 4: Declare variable i=0, j=0
Step 5: Repeat until i < r
Step 6: Repeat until j < c
Step7: Perform C[i][j]=A[i][j] - B[i][j]
Step 8: Set j=j+1
Step 9: End inner loop
Step 10: Set i=i+1
Step 11: End outer loop
Step 12: display matrix C[][]
Step 13: Stop
SOURCE CODE-
import java.util.*;
class Matrix{
int arr[][];
int m,n;
Matrix(int mm, int nn){ // constructor to initialize data members
if(mm>25||nn>25){
System.out.println("Invalid input");
System.exit(0);
}
m=mm;n=nn;
arr = new int[m][n];
}
void fillarray(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the elements of the matrix"); // accepting user input
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
{ arr[i][j] =
in.nextInt();
}
}
}
Matrix SubMat(Matrix A){
Matrix ob = new Matrix(A.arr.length,A.arr[0].length);
for(int i=0;i<this.m;i++){
for(int j=0;j<this.n;j++){
ob.arr[i][j] = A.arr[i][j] - this.arr[i][j]; // finding the difference
}
}
return ob; // returning object
}
void display(){
System.out.println("The array is "); // displaying the array
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
{ System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String args[])
{ Scanner in = new Scanner(System.in);
System.out.println("Enter the
dimensions");
Matrix obj1 = new Matrix(in.nextInt(),in.nextInt());
obj1.fillarray(); // creating object
obj1.display(); // calling methods
VDT-
VARIABLE NAME TYPE PURPOSE
arr int[][] To store the array
m int To store the dimensions
n int To store the dimensions
mm int Parameter variable
nn int Parameter variable
i int Loop control variable
j int Loop control variable
OUTPUT-
6)
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:
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
Example 2
INPUT : M=4
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
OUTP :
UT
ORIGINAL MATRIX
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
ALGORITHM-
Step 1: Start
Step 2: Declare a matrix A[m][m]
Step 3: Read values in matrix A
Step 4: Run loop from I=0 to m
Step 5: Run loop from J=0 to m
Step 6: check if A[I][J] ≠ A[J][I]
then Step 7: Print array is not
symmetric Step 8: Terminate
loop
Step 9: End loop
Step 10: End loop
Step 11: Print Array is
symmetric Step 12: Run loop
from I=0 to m Step 13: Set
SUM1+= A[I][I]
Step 14: Set SUM2+=A[J][I]
Step 15: End loop
Step 16: Print SUM1 and SUM2
Step 17: Stop
SOURCE CODE-
import java.util.*;
class matrixab{
int arr[][];
int M;
void input(){
System.out.println();
}
}
void symmetric()
{ int i,j;
outer:
for(i=0;i<M;i++){
for(j=0;j<i;j++){ if(arr[i]
[j]!=arr[j][i]){
break outer;
}
}
}
if(i==M){ // checking if it is a symmetric matrix
System.out.println("It is a symmetric matrix");
}
else{
System.out.println("It is not a symmetric matrix");
}
}
void sum(){
int sum_l=0,sum_r=0;
for(int i=0;i<M;i++){
sum_l+=arr[i][i]; // calculating sum of left diagonal
sum_r+=arr[i][M-i-1]; // calculating sum of right diagonal
}
VDT-
VARIABLE NAME TYPE PURPOSE
arr int[][] To store the matrix
M int To store the size
i int Loop control variable
j int Loop control variable
sum_l int To store the sum of
the left diagonal
sum_r int To store the sum of
the right diagonal
OUTPUT-
7)
QUESTION-
Write a Program in Java to input a 2-D array of size ‘m*n’ and print its boundary
(border) elements.
For example:
ALGORITHM-
Step 1: Start
Step 2: Read rows and column in m and n
Step 3: Read values in array
Step 4: Run loop from I=0 to m
Step 5: Run loop from J=0 to m
Step 6: check if (I=0) or (I=(m-1)) or (J=0) or (J=(n-1))
Step 7: Print A[I][J]
Step 8: End loop
Step 9: End loop
Step 10: Stop
SOURCE CODE-
import java.util.*;
class boundary{
int a[][];
int m,n;
void input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the matrix");
m = in.nextInt();
n = in.nextInt();
a = new int[m][n];
System.out.println("Enter the elements of the matrix");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
else{
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String args[]){
boundary obj = new boundary(); // creating object
obj.input(); // calling methods
obj.display();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
a int[] To store the elements
m int To store the number
of rows
n int To store the number
of columns
i int Loop control variable
j int Loop control variable
OUTPUT-
8)
QUESTION-
Write a program to check if the given matrix is a Magic Square Matrix or not.
A square matrix is said to be a Magic Square, if the sum of each row, each column
and each diagonal is same. Write a program to enter an integer number ‘n’. Create
a magic square of size ‘n*n’. Finally, print the elements of the matrix as Magic
Square.
Note: n <= 5
Sample Input: Enter the size of the matrix : 4
Sample Output: The Magic Matrix of size 4×4 is:
Sample Input: Enter the size of the matrix : 5
Sample Output: The Magic Matrix of size 5×5 is:
ALGORITHM-
Step 1: Start
Step 2: Read a matrix A[][] of mxm size
Step 3: Set RSUM=0, CSUM=0, D=0
Step 4: Run loop from I =0 to M
Step 5: D=D+A[I][I]
Step 6; End loop
Step 7: Run loop from I =0 to M
Step 8: Set RSUM=0, CSUM=0
Step 9: Run loop from J=0 to M
Step 10: RSUM=RSUM+A[I][J]
Step 11: CSUM=CSUM+A[J][I]
Step 12: end loop
Step 13: If CSUM ≠D or RSUM ≠ D then Set FLAG=
FALSE Step 14: Print Not Magic Square
Step 15: terminate loop
Step 16: End loop
Step 17: If FLAG=TRUE then
Step 18: Print Magic Square
Step 19: Stop
SOURCE CODE-
import java.util.*; class MagicMatrix
{
int[][] arr; int size;
MagicMatrix(int s)//Parameterised constructor
{
size = s;
arr = new int[size][size];
}
public void fillMatrix()//Accepting values of array
{
Scanner scanner = new Scanner(System.in); System.out.println("Enter the
elements of the matrix:"); for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
arr[i][j] = scanner.nextInt();
}
}
}
public void displayMatrix()//Displaying the array
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
boolean magicMatrix()//Checks whether the given array is magic Matrix
{
int S1[] = new int[size]; boolean b = true;
for (int i = 0; i < size ; i++)
{
VDT-
VARIABLE NAME TYPE PURPOSE
arr[] int Stores the integer value
size int Stores the size of array
s int Stores the size of array
S1 int Stores the sum of rows
S2 int Stores the sum of
column
S3 int Stores the sum of
primary diagonal
S4 int Stores the sum of
secondary diagonal
b boolean Stores true/false
i int Stores the integer
value used in
loop
j int Stores the integer
value used in
loop
OUTPUT-
9)
QUESTION-
Write a program to declare a square matrix A[ ][ ] of order ‘n’. Allow the user to
input positive integers into this matrix. Perform the following tasks on the matrix:
(i) Output the original matrix.
(ii) Find the SADDLE POINT for the matrix. If the matrix has no saddle point,
output the message “NO SADDLE POINT”.
[Note: A saddle point is an element of the matrix such that it is the minimum
element for the row to which it belongs and the maximum element for the
column to which it belongs. Saddle point for a given matrix is always unique.]
Example: In the Matrix
4 5 6
7 8 9
5 1 3
ALGORITHM-
Step 1: Start
Step 2: Read elements in matrix MAT[][] of mxm size
Step 3: Run loop from I=0 to M
Step 4: Set MINROW=MAT[I][0] and COLIND = 0
Step 5: Run loop J=1 to M
Step 6: If MINROW> MAT[I][J] then
Step 7: MINROW=MAT[I][J] and COLIND=J
Step 8: End loop
Step 9: Run loop K=0 to M
Step 10: If MINROW< MAT[K][COLIND] then end loop
Step 11: If K=M then
Step 12: Print Saddle point is MINROW
Step 13: end loop
Step 13: Stop
SOURCE CODE-
import java.util.*;
class SaddlePoint
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in); System.out.print("Enter the size of the
matrix: "); int n = in.nextInt();
int a[][] = new int[n][n];
System.out.println("Enter elements of the matrix: "); for (int i = 0; i < n; i++)
//Taking Input
{
System.out.println("Enter Row "+ (i+1) + " :"); for (int j = 0; j < n; j++)
{
a[i][j] = in.nextInt();
if (a[i][j] < 0)
{
System.out.print("Invalid Input"); return;
}
}
}
System.out.println("Matrix A[ ][ ]"); printMatrix(a, n);
//Find the Saddle Point
boolean found = false;
for (int i = 0; i < n; i++) //loop changes to every row
{
int Min = a[i][0]; int check = 0;
for (int j = 1; j < n; j++) //loop changes columns and checks Min value
{
if (Min > a[i][j])
{
Min = a[i][j]; check = j;
}
}
int k = 0;
for (k = 0; k < n; k++) //If the Min value is lower than its corresponding column
then it is not Saddle point
{
if (Min < a[k][check])
{
break;
}
}
if (k == n) //Only a saddle point would have greatest value in column while having
min value in its row
{
found = true;
System.out.println("Saddle Point = " + Min); break;
}
}
if (!found)
{
System.out.println("No Saddle Point");
}
}
public static void printMatrix(int arr[][], int n)//Printing
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
a[][] int Stores the integer value
arr[][] int Stores the integer value
n int Stores the length of
array
Min int Stores the minimum
value of the element in
column
check int Stores the column where
minimum value was
found
i int Stores the integer
value used in
loop
j int Stores the integer
value used in
loop
OUTPUT-
10)
QUESTION-
Write a Program in Java to input a 2-D square matrix and check whether it is an
Upper Triangular Matrix or not.
Upper Triangular Matrix : An Upper Triangular matrix is a square matrix in which
all the entries below the main diagonal ( ) are zero. The entries above or on the
main diagonal themselves may or may not be zero.
Example:
ALGORITHM-
STEP 1: START
STEP 2: DEFINE rows, cols
SOURCE CODE-
import java.util.*;
class triangular{
int ar[][];
int m;
void input(){
}
}
}
void triangularc(){
int i,j;
outer:
for(i=0;i<m;i++){
for(j=0;j<i;j++){
if(ar[i][j]!=0){
break outer;
}
}
}
if(i==m){ // checking if it is upper triangular matrix
System.out.println("It is upper triangular matrix");
}
else{
System.out.println("It is not upper triangular matrix");
}
}
public static void main(String args[]){
triangular obj = new triangular(); // creating object
obj.input();
obj.triangularc(); // calling methods
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
ar int[][] To store the matrix
m int To store the size
i int Loop control variable
j int Loop control variable
OUTPUT-
11)
QUESTION-
A sequence of Fibonacci Strings is generated as follows:
S0 = “a”, S1 = “b”, Sn = S(n-1) + S(n-2) where ‘+’ denotes concatenation. Thus the
sequence is:
a, b, ba, bab, babba, babbabab, n terms.
Design a class FiboString to generate Fibonacci strings. Some of the members of
the class are given below:
Class name : FiboString
Data members/instance variables:
x : to store the first string
y : to store the second string
z : to store the concatenation of the previous two strings
n : to store the number of terms
Member functions/methods:
FiboString() : constructor to assign x=”a”, y=”b”,
z=”ba” void accept() : to accept the number of terms ‘n’
void generate() : to generate and print the fibonacci strings. The sum of
(‘+’ i.e. concatenation) first two strings is the third string. Eg. “a” is first string,
“b” is second string then the third string will be “ba” and fourth will be “bab” and
so on.
Specify the class FiboString, giving details of the constructor(), void
accept() and void generate(). Define the main() function to create an object and call
the functions accordingly to enable the task.
ALGORITHM-
Step 1: Start
Step 2: Let x = “a”, y = “b”, z = “ba”
Step 3: Read value of the number of terms and store it in n
Step 4: If n == 1, display “a”
Step 5: If n == 2, display “a,b”
Step 6: If n > 2, display “a,b,ab”
Step 7: Run a loop from I = 0 to I <= n-3 (where i is the Loop Control Variable)
Step 8: x = z
Step 9: z = z + y
Step 10: Display z + “,”
Step 11: y = x
End Loop
Step 12: End
SOURCE CODE-
import java.util.*;
class
FiboString{ String
x,y,z;
int n;
z = "ba";
}
void accept(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of terms");
n = in.nextInt(); // accepting user input
}
void generate()
{ if(n>=1){
System.out.print(x +" ");
}
if(n>=2)
{ System.out.print(y+" ");
}
if(n>=3)
{ System.out.print(z+"
");
for(int i=4;i<=n;i++){ // printing the fibonacci series
x =y;
y = z;
z = y+x;
System.out.print(z+ " ");
}
System.out.println();
}
}
public static void main(String args[]){
FiboString obj = new FiboString(); // creating object
obj.accept(); // calling methods
obj.generate();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
x String To store the terms
y String To store the terms
z String To store the terms
OUTPUT-
12)
QUESTION-
Write a program to accept a sentence which may be terminated by either ‘.’ ‘?’ or
‘!’ only. Any other character may be ignored. The words may be separated by
more than one blank space and are in UPPER CASE.
Perform the following tasks:
(a) Accept the sentence and reduce all the extra blank space between
two words to a single blank space.
(b) Accept a word from the user which is part of the sentence along with
its position number and delete the word and display the sentence.
Test your program with the sample data and some random data:
Example 1
INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE
DAY.
WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6
OUTPUT: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.
Example 2
INPUT: AS YOU SOW, SO SO YOU
REAP. WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE: 4
OUTPUT: AS YOU SOW, SO YOU
REAP.
Example 3
ALGORITHM-
Step 1: Start
Step 2: Read the sentence and store it in ‘str’. Read the word to be deleted and
store it in ‘del.
Read the position of the word stored in ‘del’ and store it in ‘pos’.
Step 3: If str does not end with ‘.’, ‘?’ or ‘!’, display “Invalid Input”. Go to Step 16
Step 4: Let str2 = “”
Step 5: str2 += str.charAt(0);
Step 6: Run a loop from i = 0 to i < len (Where len is array length)
Step 7: Let ch = character at ith position
Step 8: If ch == ‘ ‘ and character at i+1th position == ‘ ‘, then ignore Step 9
Step 9: str2 += ch
End Loop
Step 10: convert str2 into a string array arr[]
Step 11: Let len = array length
Step 12: Run a loop from i = pos-1 to i < len-1 (Where i is the Loop Control
Variable)
Step 13: arr[i] = arr[i+1]
Step 14: len=len-1
Step 15: Print array
Step 16: End
SOURCE CODE-
class
sentence{ Str
ing s, s1; int
x;
void accept(){
if(s.charAt(s.length()-1)!='.'&&s.charAt(s.length()-1)!='!'&&s.charAt(s.length()-1)
!='?'){
System.out.println("Invalid input");
System.exit(0);
}
}
void modify(){
String a="";
for(int i=0;i<s.length()-1;i++)
{ if(s.charAt(i)==' ' && s.charAt(i+1)==' '){
continue;
}
a+=s.charAt(i);
}
a+=s.charAt(s.length()-
1); int count=0;
for(int i=0;i<a.length();i++)
{ if(a.charAt(i)==' '){count+
+;} if(count!=x-1){
System.out.print(a.charAt(i)); // modifying and printing the sentence
}
}
System.out.println();
}
public static void main(String args[]){
sentence obj = new sentence(); // creating object
obj.accept(); // calling methods
obj.modify();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
s String To store the sentence
s1 String To store the word to
be deleted
x int To store the position
of the word
OUTPUT-
13)
QUESTION-
A simple encryption system uses a shifting process to hide a message. The value of
the shift can be in the range 1 to 26. For example a shift of 7 means that A = U, B
=V,C = W, etc.i e.
Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N
O P Q R ST
Fist an extra space is added to the end of the string. To make things little more
difficult, spaces within the original text are replaced with QQ before the text is
encrypted. Double Q (QQ) was selected because no English word ends in Q or
contains QQ.
Additionally the coded message is printed in blocks of six characters separated by
spaces. The last block might not contain six characters. Write a program that takes
the coded text (less than 100 characters), the shift value and prints the decoded
original text. Your program must reject any non-valid value for shift and display
an error message “INVALID SHIFT VALUE)”. Assume all characters are upper
case. Test your program for the following data and some data that you have coded,
using the rules given above:
SAMPLE DATA:
1. INPUT:
CODED TEXT : “UHINBY LKKQCH HYLKK”
SHIFT : 7
OUTPUT:
DECODED TEXT : ANOTHER VALUE
2. INPUT:
CODED TEXT : “RUIJGG EVGGBK SAGG”
SHIFT : 11
OUTPUT:
DECODED TEST : BEST OF LUCK
3. INPUT:
CODED TEXT : “DKSMMW NAMMUK QMM”
SHIFT : 29
OUTPUT:
INVALID SHIFT VAULE
ALGORITHM-
Step 1: Start
Step 2: Read the code and store it in ‘str’. Read the shift value and store it in
‘shift’.
Step 3: If string’s length > 100, display “Invalid input”. Go to Step
Step 4: If shift < 1 or shift > 26, display “Invalid input”. Go to Step
Step 5: Let str2 = “”
Step 6: shift = shift -1
Step 7: Run a loop from I = 0 to I < LEN – 1 (Where LEN is string length)
Step 8: Let ch = character at ith position
Step 9: If ch == ‘ ‘, go to Step 7
Step 10: If ch == ‘Q’ and character at i+1th position == ‘Q’, str2 += “ “
Step 11: If Step 10 is not true, then let ascii = (int)ch
Step 12: Let new_ascii = ascii + shift
Step 13: If new_ascii > 90, new_ascii -= 26 and str2+= (char)new_ascii
Step 14: If Step 13 is not true, then str2 += (char)new_ascii
End Loop
Step 15: Display str2
Step 16: End
SOURCE CODE-
import java.util.*;
class encryption{
String s,s2="";
int shift;
void accept(){
}
else{
c = (char)(s.charAt(i) + (shift - 1)); // decryption
}
s2+=c;
}
s2 = s2.replaceAll("QQ"," ");
System.out.println("Decoded text: " + s2); // Displaying the decoded text
}
public static void main(String args[]){
encryption obj = new encryption(); // creating object
obj.accept(); // calling methods
obj.decode();
}
}
VDT-
VARIABLE TYPE PURPOSE
NAME
OUTPUT-
14)
QUESTION-
Write a program to input a word from the user and remove the consecutive
repeated characters by replacing the sequence of repeated characters by its single
occurrence.
Example:
INPUT – Jaaavvvvvvvvaaaaaaaaaaa
OUTPUT – Java
INPUT – Heeeiiiissggoiinggg
OUTPUT – Heisgoing
ALGORITHM-
Step 1: Start
Step 2: Read a word and store it in ‘word’. Convert it to lowercase
Step 3: Let word2 = “”
Step 4: Let flag = false
Step 5: word2 += character at 0th position
Step 5: Run a loop from I = 0 to I < LEN (Where Len is the length of string)
Step 6: Let ch = character at ith position
Step 7: If ch == character at i-1th position then ignore Step 8
Step 8: word2 += ch
End Loop
Step 9: Display word2
Step 10: End
SOURCE CODE-
import java.util.*;
class repetition{
public static void main(String args[])
{ Scanner in = new Scanner(System.in);
System.out.println("Enter the word");
String s = in.next(); // accepting user input
for(int i=0;i<s.length()-1;){
if(s.charAt(i)==s.charAt(i+1) && i<s.length()-2){ // checking for
repetition
s = s.substring(0,i+1) + s.substring(i+2);
}
else if(s.charAt(i)==s.charAt(i+1)){ // checking for repetition
s = s.substring(0,i+1);
}
else{
i++;
}
}
System.out.println(s); //printing the modified string
} // end of main()
} // end of class
VDT-
VARIABLE NAME TYPE PURPOSE
s String To store the string
i int Loop control variable
OUTPUT-
15)
QUESTION-
Write a program to input a string (word). Convert it into lowercase letters. Count
and print the frequency of each alphabet present in the string. The output should be
given as:
Sample Input: Alphabets
Sample Output:
==========================
Alphabet Frequency
==========================
a 2
b 1
e 1
h 1
l 1
p 1
s 1
t 1
ALGORITHM-
Step 1: Start
Step 2: Read a word and store it in ‘word’. Convert to Lowercase
Step 3: Let alpha[] = new int[26]
Step 4: Run a loop from i = 0 to I < LEN (Where Len is the length of string)
Step 5: Let ch = character at ith position
Step 6: Let ctr = ch – 97
Step 7: alpha[ctr]=alpha[ctr]+1
End Loop
Step 8: Display “Alphabet Frequency”
Step 9: Run a loop from I = 0 to I < 26 (Where i is the Loop Control
Variable) Step 10: If alpha[i] == 0, ignore Step 11
Step 11: Display (char)(i+97) + “ “ alpha[i]
End Loop
Step 12: End
SOURCE CODE-
import java.util.*;
class freq{
String s;
void input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the word");
s = in.next(); // accepting user input
s = s.toLowerCase();
}
void frequency()
{ System.out.println("Alphabet
Frequency"); System.out.println(" ");
String x = s;
for(int i=0;i<x.length();i++){
for(int j=0;j<x.length()-i-1;j++){ //arranging in alphabetical order
if(x.charAt(j)>x.charAt(j+1)&&j<x.length()-2){
x = x.substring(0,j) + x.charAt(j+1) + x.charAt(j) + x.substring(j+2);
}
else if(x.charAt(j)>x.charAt(j+1)){
x = x.substring(0,j) + x.charAt(j+1) + x.charAt(j) ;
}
}
}
int count=1;
for(int i=0;i<x.length()-1;i++)
{ if(x.charAt(i)==x.charAt(i+1)){
count++;
continue;
}
else if(i==x.length()-2){
System.out.println(x.charAt(i)+" " + count); // printing frequency
System.out.println(x.charAt(i+1)+" 1");
break;
}
System.out.println(x.charAt(i)+" " + count);
count =1;
}
}
public static void main(String args[])
{ freq obj = new freq(); // creating
object obj.input(); // calling methods
obj.frequency();
}
VDT-
VARIABLE NAME TYPE PURPOSE
s String To store the string
x String To store the string
i int Loop control variable
j int Loop control variable
count int To store the frequency
OUTPUT-
16)
QUESTION-
Write a program to implement Stack with pop(), push() and print() methods.
ALGORITHM-
ALGORITHM FOR PUSH IN STACK:
STEP 1: START
STEP 2: IF TOP = CAPACITY then STACK OVERFLOW, exit
Else
STEP 3: TOP = TOP +1
STEP 4: STACK[TOP] =
VALUE STEP 5: END
ALGORITHM FOR POP IN STACK:
STEP 1: START
STEP 2: IF TOP < 0 then STACK UNDERFLOW, exit
Else
STEP 3: VALUE =
STACK[TOP] STEP 4:
TOP=TOP - 1
STEP 4: END
SOURCE CODE-
class
Stack{ int
st[];
int size, top;
st[++top] = x;
}
void print(){ // printing elements
System.out.println("Stack: ");
for(int i=0;i<=top;i++){
System.out.print(st[i] + " ");
}
System.out.println();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
st int[] To store the stack
size int To store the size of
the stack
top int The top pointer of the
stack
n int To initialize the size
of the stack
x int To push an element
into the stack
i int Loop control variable
OUTPUT-
17)
QUESTION-
Write a program to implement LinearQ with insert(), delete() and print() methods.
ALGORITHM-
Algorithm for push in linear queue:
Step 1: start
Step 2: if rear = capacity then queue overflow, exit
else
Step 3: rear = rear +1
Step 4: queue[rear] = value
Step 5: end
Algorithm for pop in linear queue:
Step 1: start
Step 2: if front=rear then queue underflow, exit
else
Step 3: front=front + 1
Step 4: value = queue[front]
Step 4: end
SOURCE CODE-
class
LinearQ{ int
Q[];
int size, f, r;
}
System.out.println();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
Q int[] To store the queue
size int To store the size of
the queue
f int The front pointer
r int The rear pointer
n int To initialize the size
of the queue
x int To insert an element
i int Loop control variable
OUTPUT-
18)
QUESTION-
Write a program to implement Dequeue with insertfront(), insertRear(),
deleteFront(), deleteRear() and print() methods.
ALGORITHM-
Algorithm for push from front in dequeue:
Step 1: start
Step 2: if front = 0 then queue overflow from front, exit
else
Step 3: queue[front] = value
Step 4: front=front-1
Step 5: end
Algorithm for pop from front in dequeue:
Step 1: start
Step 2: if front=rear then queue underflow from front, exit
else
Step 3: front=front+1
Step 4: value = queue[front]
Step 5: end
Algorithm for push from rear in dequeue:
Step 1: start
Step 2: if rear = capacity then queue overflow from rear, exit
else
Step 3: rear = rear +1
Step 4: queue[rear] = value
Step 5: end
Algorithm for pop from rear in dequeue:
Step 1: start
Step 2: if front=rear then queue underflow from rear, exit
else
Step 3: value = queue[front]
Step 4: rear=rear-1
Step 4: end
SOURCE CODE-
class
Deque{ int
DQ[]; int
size, f, r;
Deque(int n){ // constructor to initialize data members
size = n;
DQ = new int[size];
f=r=0;
}
DQ[f--] = x;
}
void insertRear(int x){ // inserting elements from rear
System.out.println("Element inserted from rear : " + x);
if(r == size-1){
System.out.println("Overflow from rear");
return;
}
DQ[++r] = x;
}
void deleteFront(){ // deleting elements from front
if(f==r){
System.out.println("Underflow from front");
return;
}
System.out.println("Deleted element from front: " + DQ[++f]);
}
void deleteRear(){ // deleting elements from rear
if(f==r){
System.out.println("Underflow from rear");
return;
}
}
System.out.println();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
DQ int[] To store the deque
size int To store the size of the
deque
f int The front pointer
r int The rear pointer
n int To initialize the size
of the deque
x int To insert an element
OUTPUT-
19)
QUESTION-
Write a program to implement CircularQ with insert(), delete() and print()
methods.
ALGORITHM-
Algorithm for push in circular queue:
Step 1: start
Step 2: if front = (rear+1) mod capacity then queue overflow, exit
else
Step 3: rear = (rear +1) mod capacity
Step 4: queue[rear] = value
Step 5: end
r = (r+1)%size;
cQ[r] = x;
}
f = (f+1)%size;
System.out.println("Deleted element: " + cQ[f]);
}
void print(){ // printing elements
System.out.println("Circular queue: ");
if(r>=f){
for(int i=f+1;i<=r;i++)
{ System.out.print(cQ[i] + " ");
}
}
else{
for(int i=f+1;i<size;i++)
{ System.out.print(cQ[i] + " ");
}
for(int i=0;i<=r;i++)
{ System.out.print(cQ[i] + " ");
}
}
System.out.println();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
cQ int[] To store the circular
queue
size int To store the size of the
circular queue
f int The front pointer
r int The rear pointer
n int To initialize the size
of the circular
queue
x int To insert an element
i int Loop control variable
OUTPUT-
20)
QUESTION-
Write a program to implement LinkedList using insertBeg(),insertMid(int),
insertLast(), deleteBeg(), deleteMid(int), deleteLast() and print() methods.
ALGORITHM-
Insertion at the beginning
Traverse the list until you reach the node just before the desired position.
Adjust the pointers:
● Point the new node’s next to the next node of the current node.
● Point the current node’s next to the new node.
● Point the current node’s next to the next node’s next (i.e., skip the node to
be deleted).
SOURCE CODE-
public class Linklist
{
Node start;
Linklist()
{
start=null;
}
void insertFront(int e)
{
Node temp=new Node(e);
if (start==null) start=temp;
else
{
temp.next=start;
start=temp;
}
}
void display()
{
for(Node n=start; n!=null; n=n.next)
System.out.print(n.data+"--->");
}
void insertEnd(int e)
{
Node temp=new Node(e);
Node n;
if(start==null) start=temp;
else{
for(n=start; n.next!=null; n=n.next);
n.next=temp;
}
}
void insertMid(int e, int pos)
{
int x=1;
Node temp=new Node(e);
Node ptr=start;
if(start ==null)
{System.out.println("Insertion at nth position not possible"); return;}
while(x<pos)
{
System.out.println(ptr.data);
ptr=ptr.next;
x=x+1;
}
// System.out.println("Insertion at nth position not possible");
temp.next=ptr.next;
ptr.next=temp;
}
void deleteFront()
{
if(start==null) System.out.println("Underflow");
else
start=start.next;
}
void deleteEnd()
{
if(start==null) {System.out.println("Underflow"); return;}
else
{
Node ptr;
for( ptr=start; ptr.next.next!=null; ptr=ptr.next);
ptr.next=null;
}
}
void deleteAtPos(int pos)
{
if(start==null){ System.out.println("Underflow"); return;}
else
{
int i=1;
Node ptr1,ptr2;
ptr1=ptr2=start;
while (i<pos)
{
ptr1=ptr2;
ptr2=ptr2.next;
i++;
}
ptr1.next=ptr2.next;
ptr1=ptr2=null;
}
}
}
public class Node
{
int data;
Node next;
Node (){}
Node(int n)
{ data=n;
next=null;}
}
// Test underflow
list.deleteFront();
list.deleteFront(); // Expected output: Underflow
list.display(); // Expected output: (empty)
}
VDT-
VARIABLE NAME TYPE PURPOSE
start Node Used to keep track of the
beginning of the linked list.
temp Node Created during node
insertions (at the front,
end, or middle).
n Node Used to iterate through the
list.
e int
OUTPUT-
21)
QUESTION-
Write a program to Implement Stack using Linked List.
ALGORITHM-
Algorithm for Push Operation:
Step 1: Create a new node.
Step 2: Set the data of the new node to the value to be pushed.
Step 3: Set the next pointer of the new node to the current top node.
Step 4: Update the top pointer to point to the new node.
Algorithm for Pop Operation:
Step 1: Check if the stack is empty (i.e., top == null). If it is empty, return an error
or message indicating underflow.
Step 2: Store the data of the top node in a temporary variable.
Step 3: Update the top pointer to point to the next node in the stack.
Step 4: Return the stored data.
SOURCE CODE-
class Node {
int data; // Data stored in the node
Node next; // Pointer to the next node
// Constructor to initialize node data
public Node(int data) {
this.data = data;
this.next = null;
}
}
import java.util.*;
class Stack_Link {
private Node top; // Pointer to the top element of the stack
}
// Method to print the elements of the stack
public void print() {
if (isEmpty()) {
System.out.println("The stack is empty.");
return;
}
System.out.println();
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
Stack_Link stack = new Stack_Link(); // Create a new stack
boolean exit = false;
while (!exit) {
System.out.println("\nChoose an operation:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Print");
System.out.println("4. Exit");
System.out.print("Your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter a value to push onto the stack: ");
int value = scanner.nextInt();
stack.push(value);
break;
case 2:
stack.pop();
break;
case 3:
stack.print();
break;
case 4:
exit = true;
System.out.println("Exiting program.");
break;
default:
}
scanner.close();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
Top Node To point the topmost
node
OUTPUT-
22)
QUESTION-
Write a program to Implement Queue using Linked List.
ALGORITHM-
Algorithm to Insert element:
Step 1: Create a new node.
Step 2: Set the data of the new node to the value to be enqueued.
Step 3: If the queue is empty (i.e., rear == null), set both front and rear to the new
node.
Step 4: If the queue is not empty, set the next pointer of the current rear node to the
new node, then update the rear pointer to the new node.
Algorithm to Delete element:
Step 1: If the queue is empty (i.e., front == null), return an error or message
indicating underflow.
Step 2: Store the data of the front node in a temporary variable.
Step 3: Update the front pointer to point to the next node in the queue.
Step 4: If the front becomes null after this operation (i.e., the queue is now empty),
set rear to null as well.
Step 5: Return the stored data.
SOURCE CODE-
class Node {
int data; // Data stored in the node
Node next; // Pointer to the next node
// Constructor to initialize node data
public Node(int data) {
this.data = data;
this.next = null;
}
}
// Queue class using a linked list
import java.util.*;
class Queue_Link {
private Node front; // Pointer to the front of the queue
private Node rear; // Pointer to the rear of the queue
// Constructor to initialize the queue
public Queue_Link() {
this.front = null; // Queue is initially empty
this.rear = null; // Queue is initially empty
}
}
// Method to print the elements of the queue
public void print() {
if (isEmpty()) {
System.out.println();
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
Queue_Link queue = new Queue_Link(); // Create a new queue
boolean exit = false;
while (!exit) {
System.out.println("\nChoose an operation:");
System.out.println("1. Enqueue");
System.out.println("2. Dequeue");
System.out.println("3. Print");
System.out.println("4. Exit");
System.out.print("Your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
queue.dequeue();
break;
case 3:
queue.print();
break;
case 4:
exit = true;
System.out.println("Exiting program.");
break;
default:
}
scanner.close();
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
Front Node To point the first node
Rear Node To point the last node
Newnode Node To store the node
temporary
Exit Boolean Checks the status
OUTPUT-
23)
QUESTION-
A class Employee contains employee details and another class Salary calculates the
employee’s net salary. The details of the two classes are given below:
Class name : Employee
Data members :
empNo : stores the employee number.
empName : stores the employee name
empDesig : stores the employee’s
designation. Member functions:
Employee() : default constructor.
Employee(…) : parameterized constructor to assign values to
data members.
void display() : display the employee details.
Class name : Salary
Data members :
ALGORITHM-
Class: Employee
Step 1: Start
Step 2: Let empName = “”, empDesig = “” and empNo = 0;
Step 3: Accept the employee name, designation, code and basic salary from the
user and store it in the data members of super and sub class
Step 4: Display the employee name, code and designation
Step 5: End
Class: Salary
Step 1: Start
Step 2: Let basic = 0
Step 3: Call super() and initialise super and sub class data members
Step 4: Let da = 0.1 * basic
Step 5: Let hra = 0.15 * basic
Step 6: Let salary = basic + da + hra
Step 7: Let pf = 0.08 * salary
Step 8: Let net_sal = salary – pf
Step 9: super.display()
Step 10: Display net_sal
Step 11: End
SOURCE CODE-
class Employee{ // super class
int empNo;
String empName, empDesig;
}
Employee(int n, String s1, String s2){ // constructor to initialize data members
empNo = n;
empName = s1;
empDesig = s2;
}
void display(){
System.out.println("Employee no : " + empNo);
System.out.println("Employee name : " + empName);
System.out.println("Employee designation : " + empDesig);
}
}
class Salary extends Employee{ // sub class
float basic;
Salary(int x, String y, String z, float f1){ // constructor to initialize data
members
super(x,y,z); // calling super class constructor
basic = f1;
}
void calculate(){
float da = 0.10f * basic;
float hra = 0.15f * basic;
float salary = basic + da + hra;
float pf = 0.08f *salary;
salary = salary - pf;
display(); // calling method
System.out.println("Employee salary: " + salary);
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
empNo int To store
employee
number
empName String To store employee name
empDesig String To store
employee
designation
n int Parameter variable
s1 String Parameter variable
s2 String Parameter variable
basic float To store basic pay
x int Parameter variable
y String Parameter variable
z String Parameter variable
f1 float Parameter variable
da float To store DA
hra float To store HRA
salary float To store salary
pf float To store PF
OUTPUT-
24)
QUESTION-
A super class Worker has been defined to store the details of a worker. Define a
sub class Wages to compute the monthly wages for the worker. The details of both
the classes are given below:
Class name : Worker
Data members :
name : to store the name of the worker
basic : to store the basic pay in decimal
Member functions :
Worker(….) : parameterized constructor to assign values to
the instance variables
void display() : display worker details
Class name : Wages
Data members :
Specify the class Worker giving details of the constructor() and void display().
Using the concept of inheritance, specify the class Wages giving details of the
constructor(), double overtime() and void display(). The main function need not be
written.
ALGORITHM-
Class
Worker Step
1: Start
Step 2: Let name and basic
Step 3: Accept values for data members for super and sub class
Step 4: Display name and basic
Step 5: End
Class:
Wages Step
1: Start
Step 2: Let hrs, wage and rate
Step 3: Initialise data members of super and sub class
Step 4: Let overtime = hrs*rate
Step 5: Let wage = overtime + basic
Step 6: super.display()
Step 7: Display wage
Step 8: End
SOURCE CODE-
class Worker{ // super class
String name;
double basic;
void display()
{ System.out.println("Name: " +
name);
System.out.println("Basic pay: " + basic);
}
}
class Wages extends Worker{ // sub class
int hrs;
double rate,wage;
double overtime(){
return hrs*rate;
}
void display(){
wage = basic + overtime();
super.display(); // calling methods
System.out.println("Hours worked: "+ hrs);
System.out.println("Rate per hour: "+
rate); System.out.println("Wage: "+ wage);
}
VDT-
VARIABLE NAME TYPE PURPOSE
name String To store the name
basic double To store the basic pay
s String Parameter variable
a double Parameter variable
OUTPUT-
25)
QUESTION-
A super class Record has been defined to store the names and ranks of 50
students. Define a sub class Rank to find the highest rank along with the name.
The details of both classes are given below:
Class name : Record
Data members
name[] : to store the names of students
rnk[] : to store the ranks of students
Member functions :
Record() : constructor to initialize data members
void readvalues() : to store names and ranks
void display() : displays the names and the corresponding
ranks Class name : Rank
Data members
ALGORITHM-
Class: Record
Step 1: Start
Step 2: Let name[], rnk[]
Step 3: name = new String[50]
Step 4: rnk = new int[50]
Step 5: Accept values for name and rnk
Step 6: Display name[] with rnk[]
Step 7: End
Class: Rank
Step 1: Start
Step 2: Let index
Step 3: Initialise the data members of super and sub class
Step 4: Let max = rnk[0]
Step 5: Let ind = 0
Step 6: Run a loop for i =0 till i < LEN (where LEN is length of string)
Step 7: If rnk[i] < max, do Steps 8 and 9
Step 8: max = rnk[i]
Step 9: ind = i
Step 10: Go to Step 7
Step 11: index = ind
Step 12: super.display()
Step 13: Display name[index] and rnk[index]
Step 14: End
SOURCE CODE-
import java.util.*;
class Record{ // super class
String name[];
int rank[];
}
void readvalues(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of students");
name = new String[in.nextInt()];
rank = new int[name.length];
}
void display(){
for(int i=0;i<name.length;i++)
{ System.out.println(name[i] + " - " + rank[i]);
}
}
}
class Rank extends Record{ // sub class
int index;
Rank(){ // constructor to initialize data members
super(); // calling super class constructor
index =0;
}
void highest(){
int min=rank[0];
for(int i=1;i<rank.length;i++){
if(rank[i]<min){
index = i;
min = rank[i];
}
}
}
void display(){
super.display(); // calling methods
System.out.println("Topmost rank: ");
System.out.println(name[index] + " - " + rank[index]);
}
VDT-
VARIABLE NAME TYPE PURPOSE
name String[] To store the names
rank int[] To store the ranks
i int Loop control variable
index int To store the index
min int To store the highest
rank
OUTPUT-
26)
QUESTION-
A super class Detail has been defined to store the details of a customer. Define a
sub class Bill to compute the monthly telephone charge of the customer as per the
chart given below:
NUMBER OF CALLS RATE
1- 100 Only rental charge
101-200 60 paisa per call + rental charge
201-300 80 paisa per call + rental charge
Above 300 1 rupee per call + rental
charge The details of both the classes are given below:
Class Name : Detail
Data members
name : to store the name of the customer.
ALGORITHM-
Class: Detail
Step 1: Start
Step 2: Let name, address, telno, rent
Step 3: Accept the values for name, address, telno and rent. Also accept the value
for number of calls made
Step 4: Display name, telno, address and rent
Step 5: End
Class: Bill
Step 1: Start
Step 2: Let n and amt
Step 3: Initialise data members of super and sub class
Step 4: If n <= 1 and n <= 100, amt = rent
Step 5: Else if n >= 101 && n <= 200, amt = (0.60 * n) + rent
Step 6: Else if n >= 201 && n <= 300, amt = (0.80 * n) + rent
Step 7: Else, amt = n + rent
Step 8:
super.show() Step
9: Display amt Step
10: End
SOURCE CODE-
class Detail //Super Class
{
String name, address; int telno;
double rent;
Detail(int t, double r, String n, String a)//Parameterised Constructor
{
telno = t; rent = r; name = n; address = a;
}
void show()//Display Method
{
System.out.println("Name: "+name); System.out.println("Address:
"+address); System.out.println("Telephone No: "+telno);
System.out.println("Rent: "+rent);
}
}
class Bill extends Detail //Sub class
{
int n; double amt;
Bill(int N, int t, double r, String na, String a)//Parameterised constructor
{
super(t,r,na,a); n = N; // calling super class constructor
amt = 0.0;
}
VDT-
VARIABLE NAME TYPE PURPOSE
name String To store the name
address String To store the address
amt double To store the amount
rent double To store the rent
n int Stores integral Value
tellno int To store the telephone
number
N int Parameter variable
t int Parameter variable
r double Parameter variable
na String Parameter variable
a String Parameter variable
OUTPUT-
27)
QUESTION-
A super class Perimeter has been defined to calculate the perimeter of a
parallelogram. Define a sub class Area to compute the area of the parallelogram by
using the required data members of the super class. The details are given below:
Class name : Perimeter
Data Members
a : to store the length in decimal
ALGORITHM-
Class: Perimeter
Step 1: Start
Step 2: Let a and b
Step 3: Accept values for the length, breadth and height of the parallelogram
Step 4: Display the length, breadth and perimeter of the parallelogram =( 2*(a+b))
Step 5: End
Class: Area
Step 1: End
Step 2: Let h and b
Step 3: Initialise the data members of super and sub class
Step 4: Let b = h * super.b
Step 5: super.show();
Step 6: Display b
SOURCE CODE-
class Perimeter{ // super class
double a,b;
Perimeter(double x, double y){ // constructor to initialize data members
a = x; b= y;
}
double Calculate(){
return 2*(a+b);
}
void show()
{ System.out.println("a = " +
a); System.out.println("b = " +
b);
System.out.println("Perimeter = " + Calculate());
}
}
class Area extends Perimeter{ // sub class
double h, area;
Area(double m, double n, double o){ // constructor to initialize data members
super(m,n); // calling super class constructor
h = o;
}
void doArea(){
area= b *h;
}
void show()
{ super.show
();
System.out.println("h = " + h);
doArea(); // calling methods
System.out.println("Area = " + area);
}
VDT-
VARIABLE NAME TYPE PURPOSE
a double To store the dimensions
b double To store the dimensions
x double Parameter variable
y double Parameter variable
h double To store the height
area double To store the area
m double Parameter variable
n double Parameter variable
o double Parameter variable
OUTPUT-
28)
QUESTION-
A class SeriesSum is designed to calculate the sum of the following series:-
Sum= x2/1! + x4/3!+x6/5!+….xn/(n-1)!
Some of the members of the class are given below:
Class name : SeriesSum
Data members
x : to store an integer number
ALGORITHM-
Step 1: Start
Step 2: Initialise x to ‘xx’ and n to ‘nn’
Step 3: Read an integer and store it in ‘x’.
Step 4: Read the number of terms and store it in ‘n’.
Step 5: Let sum = 0.
Step 6: If n == 0, display sum, else, do Steps 7,8,9,10,11,12
Step 7: If 2*n == 0, return 1 to call statement
Step 8: Else, return (x*x), (2*n)-- to call statement, go to Step 7
Step 9: If (2*n-1) == 1, return 1 to call statement
Step 10: Else, return {(2*n-1) * (2*n-2 --)} to call statement, go to Step 9
Step 11: sum += (Result of Step 8) / (Result of Step 10)
Step 12: n = n-1, go to Step 6
Step 13: End
SOURCE CODE-
import java.util.*;
class SeriesSum{
int x, n;
double sum=0.0;
SeriesSum(int xx, int nn){ // constructor to initialize data members
x =xx;n=nn;
}
double findfact(int m)
{ if(m==1){
return 1;
}
return m* findfact(m-1); // calculating factorial recursively
}
double findpower(int a, int b)
{ if(b==1){
return a;
}
return a*findpower(a,b-1); // finding the power recursively
}
void calculate(){
for(int i=1;i<=n;i++){
sum += findpower(x,2*i)/findfact(2*i-1); // calculating the sum
}
}
void display(){
System.out.println("The sum of the series is " + sum); // displaying the sum
}
public static void main(String args[])
{ Scanner in = new Scanner(System.in);
System.out.println("Enter the value of x and the number of terms");
VDT-
VARIABLE NAME TYPE PURPOSE
x int To store the value
n int To store the number
of terms
sum double To store the sum
xx int Parameter variable
nn int Parameter variable
m int Parameter variable
a int Parameter variable
b int Parameter variable
i int Loop control variable
OUTPUT-
29)
QUESTION-
A class RecFact defines a recursive function to find the factorial of a number. The
details of the class are given below:
Class Name : RecFact
Data Members :
n : stores the number whose factorial is required.
r : stores an integer
Member functions :
ALGORITHM-
Step 1: Start
Step 2: Let n = 0, r = 0 and series = 0
Step 3: Read the number and store it in ‘n’
Step 4: Read an integer and store it in ‘r’.
Step 5: If n == 1, return n to call statement
Step 6: Else if n == 0, return 1 to call statement
Step 7: Else n * (n-1), n--, go to Step 5
Step 8: series = (Result of Step 7) / (Result of Step 7 with n replaced by r) *
(Result of Step 7
with n replaced by (n-r))
Step 9: Display series
Step 10: End
SOURCE CODE-
import java.util.*;
class RecFact{
int n, r;
void readnum(){
Scanner in = new Scanner(System.in);
System.out.println("Enter values of n and r");
n = in.nextInt(); // accepting user input
r = in.nextInt(); // accepting user input
if(r>n){
System.out.println("Invalid input");
System.exit(0);
}
}
int factorial(int x){
if(x==0){ // calculating factorial recursively
return 1;
}
return x*factorial(x-1);
}
void factseries(){
int s = factorial(n)/(factorial(r)*factorial(n-r)); //calculating required value
System.out.println("The value is " + s);
}
VDT-
VARIABLE TYPE PURPOSE
NAME
OUTPUT-
30)
QUESTION-
An Emirp number is a number which is prime backwards and forwards. Example:
13 and 31 are both prime numbers. Thus 13 is an emirp number.
Design a class Emirp to check if a given number is Emirp number or not. Some of
the members of the class are given below:
Class Name : Emirp
Data Members
n : stores the number
rev : stores the reverse of the number
f : stores the divisor
Member functions
Emirp(int nn) : to assign n=nn, rev=0, and f=2
int isprime(int x) : check if the number is prime using the
recursive technique and return 1 if prime otherwise return 0.
void isEmirp() : reverse the given number and check if both the
original number ad the reverse number are prime, by invoking the function
isprime(int) and display the result with an appropriate message.
Specify the class Emirp giving details of the constructor(int), int isprime(int) and
void isEmirp(). Define the main function to create an object and call the
methods to check for Emirp number.
ALGORITHM-
Step 1: Start
Step 2: Let n = nn, rev = 0 and f = 2
Step 3: Read a number and store it in ‘n’.
Step 4: If f == n, f = 2 and return 1
Step 5: Else if n%f == 0, return 0
Step 6: f += 1, go to Step 4
Step 5: Let backup = n
Step 6: Do Steps 7,8,9 till n >0
Step 7: Let dig == n%10
Step 8: rev = (rev*10) + dig
Step 9: n = n/10, go to Step 6
Step 10: If (Result of Step 4-6 with backup in place of n) == 1 && Result of Step 4
– 6 with
rev in place of n == 1, display “Emirp Number”
Step 11: Else display “Not an Emirp Number”
Step 12: End
SOURCE CODE-
import java.util.*;
class Emirp {
int n; // stores the number
f = 2;
}
public static void main(String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Enter a number"); // accepting number from the user
int a = in.nextInt();
Emirp obj = new Emirp(a); // creating object
obj.reverseNumber(); // calling methods
obj.isEmirp();
}
}
void isEmirp() { // Method to check if the number is Emirp
if (isprime(n) == 1 && isprime(rev) == 1) { // checking whether the number
is Emirp or not
System.out.println(n + " is an Emirp number."); // displaying the result
} else {
System.out.println(n + " is not an Emirp number.");
}
}
}
VDT-
VARIABLE NAME TYPE PURPOSE
n int To store the number
OUTPUT-
31)
QUESTION-
Design a class VowelWord to accept a sentence and calculate the frequency of
words that begin with a vowel. The words in the input string are separated by a
single blank space and terminated by a full stop.
The description of the class is given below:
Class Name :
VowelWord Data members
str : to store a sentence
ALGORITHM-
Step 1: Start
Step 2: Let str = “” and freq = 0
Step 3: Read a sentence and store it in str
Step 4: str = “ “+str
Step 5: Let i = 0
Step 6: Run Steps 7,8,9, till I < LEN (Length of string)
Step 7: Let ch = character at ith position
Step 8: If ch == ‘ ’, then do Step 9
Step 9: If character at ith position is matched with ‘AEIOU’ then freq ++, go to
Step 6
Step 10: Display str and freq
Step 11: End
SOURCE CODE-
import java.util.*;
class
VowelWord{
String str;
int freq;
VowelWord(){ // constructor to initialize data members
str= "";
freq = 0;
}
void readstr(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the string");
str = in.nextLine(); // accepting user input
}
void freq_vowel(){
String a[] = str.split(" ");
for(int i=0;i<a.length;i++){
char c = a[i].charAt(0);
c = Character.toLowerCase(c); if(c=='a'||c=='e'||c=='i'||c=='o'||
c=='u'){
freq++;
} // calculating frequency
}
}
void display(){
System.out.println("Original string \n"+str); // displaying the string
System.out.println("frequency of words beginning with a vowel= " + freq); //
displaying the frequency
}
public static void main(String args[]){
VowelWord obj = new VowelWord(); // creating object
obj.readstr(); // calling methods
obj.freq_vowel();
obj.display();
}
VDT-
VARIABLE NAME TYPE PURPOSE
str String To store the string
freq int To store the frequency
a String[] To store the words
i int Loop control variable
c char To store the characters
OUTPUT-
32)
QUESTION-
Input a sentence from the user and count the number of times, the words “an” and
“and” are present in the sentence. Design a class Frequency using the description
given below:
Class name : Frequency
Data Members
text : stores the sentence
technique. void display() : to display the frequency of “an” and “and” with
suitable messages.
ALGORITHM-
Step 1: Start
Step 2: Let text = “”, countand = 0, countan = 0 and len = 0
Step 3: Let text = n
Step 4: text = “ ” + text + “ ”
Step 5: Let backup = text
Step 6: Let len1 = text_length and len2 = backup_length
Step 7: If len2 == 0 then return
Step 8: Else if backup=”and” then countand +=1
Step 9: update backup
Step 10: len2 = backup_length; go to Step 7
Step 11: If len1 == 0 return
Step 12: Else if backup=”an” the countan+=1
Step 13: update backup
Step 14: len1 = backup_length, go to Step 11
Step 15: Display countand and countan
Step 16: End
SOURCE CODE-
import java.util.*;
class Frequency{
String text;
String a[];
int countand, countan, len;
}
void accept(String n)
{ text = n;
len = text.length();
a = text.split(" ");
}
void checkandfreq(int i){ // calculating frequency of and
if(a[i].equals("and")&&i!=a.length-1)
{ countand += 1 ;
}
else if(a[i].equals("and")&&i==a.length-1){
countand += 1;
}
else if(i==a.length-1){
return;
}
checkandfreq(++i);
}
void checkanfreq(int i){ // calculating frequency of and
if(a[i].equals("an")&&i!=a.length-1){
countan += 1 ;
}
else if(a[i].equals("an")&&i==a.length-1){
countan += 1;
}
else if(i==a.length-1){
return;
}
checkanfreq(++i);
}
void display(){
System.out.println("Original string: " + text); // displaying results
System.out.println("Frequency of and: " + countand);
System.out.println("Frequency of an: " + countan);
}
}
}
VDT-
VARIABLE TYPE PURPOSE
NAME
text String To store the sentence
a String[] To store the words
countand int To store the frequency of the
word and
countan int To store the frequency of the
word an
len int To store the length of the
string
n String Parameter variable
i int Parameter variable
OUTPUT-
33)
QUESTION-
Read an array of integers and sort them in ascending order using Insertion Sort
method.
ALGORITHM-
Step 1: Start
Step 2: Read array size ‘n’ and array elements into arr[] in the
method accept() Step 3 − If it is the first element, it is already
sorted. return 1;
Step 4 − Pick next element
Step 5 − Compare with all elements in the sorted sub-list
Step 6 − Shift all the elements in the sorted sub-list that is
greater than the value to be sorted
Step 7 − Insert the value
Step 8 − Repeat until list
is sorted Step 9- Print the
sorted array Step 10: Stop
SOURCE CODE-
import java.util.Scanner;
public class InsertionSort
{
int arr[];
int n;
void accept() //to enter the size of the array
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the size of the array.");
n = sc.nextInt();
arr = new int[n];
System.out.println("Please enter the elements of the array.");
for (int i = 0;i<n;i++) {
arr[i] = sc.nextInt();
}
}
OUTPUT-
35)
QUESTION-
Read an array of integers and sort them in ascending order using
Quick Sort method
ALGORITHM-
Step 1: Start
Step 2: Read array elements into array[] and the
size of the array. Step 3 − Choose the highest index
value has pivot
Step 4 − Take two variables to point left and right of the list
excluding pivot
Step 5 − left points to the low
index Step 6 − right points to
the high
Step 7 − while value at left is less than pivot
move right Step 8 − while value at right is
greater than pivot move left
Step 9 − if both step 5 and step 6 does not match swap
left and right Step 10 − if left ≥ right, the point where
they met is new pivot
Step 11- Print the sorted array
Step 12: Stop
SOURCE CODE-
import java.util.Scanner;
public class QuickSort {
int arr[];
void accept() //reads array size
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter size of the array.");
int n = sc.nextInt();
arr = new int[n];
System.out.println("Please enter the elements of the array.");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
}
int partition(int start, final int end) //partitions array elements into subarrays
{
for (int i = start; i < end; i++) {
if (arr[i] < arr[end])
{ swap(start, i);
start++;
}
}
swap(start, end);
return start;
}
void swap(int left, int right) //swaps array elements
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
void sort(int left, int right) //sorting using quick sort logic
{
if (left < right) {
int pivot = partition(left, right);
sort(left, pivot - 1);
sort(pivot + 1, right);
}
}
void display() //display sorted array
{
System.out.println("The sorted array is:");
for (int value : arr) {
System.out.println(value);
}
}
public static void main(String[] args) //main method to call member methods
{
QuickSort ob = new QuickSort();
ob.accept();
ob.sort(), ob.arr.length - 1);
ob.display();
}
}
VDT-
VARIABLE TYPE PURPOSE
NAME
arr[] int Single-dimension integer array
sc Scanner Scanner object to take input
n int Stores the array size
i int Loop control variable
start int Stores starting position of the
array
end int Stores end position in the
array
left int Stores an integer value
right int Stores an integer value
temp int Stores an integer value
ob QuickSort Object of the class to call
member methods.
OUTPUT-