0% found this document useful (0 votes)
56 views108 pages

Java Programs for Number Classification

Uploaded by

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

Java Programs for Number Classification

Uploaded by

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

ISC 2024-2025

NAME : PRITI GHOSAL


CLASS : XII COMMERCE 2
ROLL : 30
REGD : 12849
SUBJECT : COMPUTER SCIENCE
UNIQUE ID : 7783620

[1]
INDEX
SL.NO CONTENTS PG.NO
01. Write a program to input a number. Check whether the number 6-9
is a spy number or not.

02. Write a program to input a number. Check whether the 10-13


number is a magic number or not.

03. Write a program to input a number. Check whether the number 14-17
is a Happy number or not.

04. Write a program to input a number. Check whether the number 18-22
is a special two digit number or not.

05. Write a program to input a number. Check whether the number 23-26
is a special number or not.

06. Write a program to input a number. Check whether the 27-31


number is a Goldbach number or not.

07. Write a program to declare a matrix A [][] of order (M x N) 32-36


where M is the number of rows and N is the number of
columns such that both M and N must be greater than 2 and
less than 10. Allow the user to input integers into this matrix.
Display appropriate error message for an invalid input

08. Write a program to declare a square matrix A [][] of order (M 37-41


x M) where M is the number of rows and is the number of
columns, such that M must be greater than 2 and less than
10.
09. Write a program to declare a matrix A [][] of order (M x N) 42-46
where M is the number of rows and N is the number of
columns such that both M and N must be greater than 2 and
less than
10.

[2]
10. Write a program to declare a square matrix A [][] of order (M 47-51
x M) where M is the number of rows and is the number of
columns, such that M must be greater than 2 and less than
10.
11. Write a program to accept a sentence which may be 53-57
terminated by either ‘.’, ‘?’ or ‘!’ only. The words may be
separated by a single blank space and should be case-
insensitive.
12. Develop a program code to find the number of keystrokes 58-62
needed to type the text.

Accept a word without any punctuation marks, numbers or


white spaces and the text message would consist of just 1
word.

13. Write a program to check is a string is an Anagram of another 63-67


string. Two strings are anagrams if they can be rearranged to
form the same string.

14. A sports academy wants to conduct a friendly match between 69-74


two teams with maximum fifteen players. A class Sports
contains three data members, to store the name of the team
with ‘n’ number of players and a one- dimensional array to
store height of each player. Design a class Sports to compare
average height of both the teams.

15. A super class Demand has been defined to store the details of 75-78
the demands for a product. Define a subclass Supply which
contains the production and supply details of the products.

16. Implement Stack in Java using array . 80-85

17. Implement Queue in Java using array. 87-92

18. Implement Double Ended Queue in Java using array . 94-102

19. Implement singly linked list in Java. 104-113

20. Binary tree. 115-116

[3]
RECURSION
BASED
PROGRAMS
QUESTION 1:
Write a program to input a number and Check whether the
number is a spy number or not.
Example: input sample =1124 , Sum of digits= 1+1+2+4 =
8, product of digits=1*1*2*4 = 8
If sum of digits and product of digits both are same then 1124 is a

spy number..
Class name : Spy

Instance variable

[4]
n Integer type variable to store a number

Member Functions:

Spy(int n): Parameterized constructor to assign the


value of x to n.

int sum(int x): Recursive function to compute the sum of


digits and return the value to the check()
function.

int product (int x): Recursive function to compute the product


of digits and return the value to the check()
function.

void check( ); Invoke sum(…) and product(..) function to


check whether the number is a spy number
or not.

Write main() function to call all the function defined above.

➢ ALGORITHMS:
• Step 1 : START
• Step 2 : Create a Class “ Spy ”
• Step 3 : Define Recursive Function : int sum( int x );
• Step 4 : Declare Base Case : return 0
• Step 5 : Declare Recursive Case : return (x%10)+sum(x/10);
• Step 6 : Define Recursive Function : int product( int x );
• Step 7 : Declare Base Case : return 1
• Step 8 : Declare Recursive Case : return (x%10)*sum(x/10);
• Step 9 : Creating object of “ Spy ” Class
• Step 10 : STOP

SOURCE CODE

[5]
import java.util.*; // Creating package for Scanner class class
Spy // Creating a Class
{
int n; // Declaring the instance variable
Spy(int x)// Declaring the parameterized constructor
{
n=x;// assign the value of x to n
}
public int sum(int x) //Recursive function to calculate sum of digit
{
if(x == 0) // Base case
{
return 0;
}
else // Recursive case
{
return (x%10)+sum(x/10);
}
}
public int product(int x)//Recursive function to calculate product of digits
{
if(x == 0)// Base case
{
return 1;
}
else // Recursive case
{
return (x%10)*product(x/10);
}
}// checking the condition for the Spy Number
public void check( )
{

[6]
int s=sum(n); // invoking the sum(int x) function int
p=product(n);// invoking the product (int x) function
if(s==p) // checking the condition for spy number
{
System.out.println("It is Spy number");
}
else
{
System.out.println("It is not Spy Number");
}
}
public static void main(String[] args) // Declaring the main
function
{
Scanner sc=new Scanner(System.in); // Creating Scanner Class

System.out.println("ENTER THE NUMBER");

int num=sc.nextInt();// Taking input from the User

Spy sp=new Spy(num);// Object of class

sp.check();// Check function is call


}
}

INPUT /OUTPUT
[7]
QUESTION 2:
Write a program to input a number and Check whether the number is a
magic number or not. Example: Sample input : 64
Then sum of digit :
6+4=10
1+0=1
A number is said to be a magic number if the eventual sum of digits of the
Number is one.

Class Name: Magic

Instance variable/Member variable

int n Integer type variable to store a number.

Member function

magic(int x): Parameterized constructor to assign the value


of x to n.

int sum(int x): Recursive function to compute the sum of


digits and return the value to the check()
function.

void check(): Invoke sum(…) function to check whether the


number is a magic number or not.

Write main() function to call all the functions defined above.

➢ ALGORITHMS:
• Step 1 : START
• Step 2 : Create a Class “Magic”
• Step 3 : Define Recursive Function : int sum( int x );
• Step 4 : Declare Base Case : return 0
• Step 5 : Declare Recursive Case : return (x%10)+sum(x/10);
• Step 6 : Define check() Function

[8]
• Step 7 : Creating an object for Magic class
• Step 8 : STOP

SOURCE CODE
import java.util.Scanner; // Creating package for Scanner Class
class Magic // Creating a Class
{
int n; // Declaring the instance variable
public Magic(int x) // Declaring the Parameterized
Constructor
{
n=x;// assign the value of x to n
}
public int sum(int x)//Recursive function to calculate the sum of
digits {
if(x== 0) // Base Case
{
return 0;
}
else // Recursive Case
{
return (x%10)+sum(x/10);
}
}
public void check ( ) // To check the condition for Magic
Number
{

[9]
while(n>9) // Running the function till it return the sum in single
digit
{
n=sum(n);// invoking the sum (int x) function
}
if(n==1)// condition for the Magic Number
{
System.out.println("it is a magic number");
}
else
{
System.out.println("It is not a magic number");
}
}
public static void main(String []args) // Declaring the Main
Function
{
Scanner sc=new Scanner(System.in); // Creating Scanner
Class

System.out.println("ENTER THE NUMBER");


int num=sc.nextInt();// Taking the Input from User

Magic ma= new Magic(64);//Object of a Class


ma.check(); // check() function is call
}
}

INPUT/OUTPUT
[10]
QUESTION 3 :
Write a program to input a number. Check whether the number is a Happy
number or not.
Example: Sample Input : 32
Then sum of square digit :
32+22=13
12+32=10 12+0=1.
A number is said to be a Happy number if the eventual sum of square of
digits of the Number is one.

Class Name: Happy

Instance variable/Member variable

N Integer type variable to store a number.

Member function

Happy(int x): Parameterized constructor to assign the value


of x to n.

int sumSquare(int x): Recursive function to compute the sum of


square of digits and return value to the
check() function.

void check(): Invoke sumSquare(…) function to check


whether the number is a Happy number or
not.

Write main() function to call all the functions defined above.

➢ ALGORITHMS:
• Step 1 : START
• Step 2 : Create a Class “ Happy ”
• Step 3 : Define Recursive Function : int sumSquare(int x);

[11]
• Step 4 : Declare Base Case : return 0

• Step 5 : Declare Recursive Case : return


Maths.pow(x%10,2)+sum(x/10);
• Step 6 : Define check() Function
• Step 7 : Creating object of Happy class
• Step 8 : STOP

SOURCE CODE
import java.util.Scanner; // Creating Package for Scanner Class
public class Happy // Creating a Class
{
int n;// Declaring the instance Variable public
Happy(int x) // Declaring the Parameterized Constructor
{
n=x;// assign the value of x to n
}
public int sumSquare(int x)// calculate the sum of Square of
digits {
if(x== 0)// Base Case
{
return 0;
}
else // Recursive Case
{
return (int)Math.pow((x%10),2)+sum(x/10);
}
}

[12]
public void check() // To check the Condition for the Happy Number
{
while(n>9)// Running the function till it return the sum in single
digit
{
n=sumSquare(n); // Invoking the sumSquare()
}
if(n==1)// condition for the Happy Number
{
System.out.println("it is a Happy number");
}
else
{
System.out.println("It is not a Happy number");
}
}
public static void main(String[] args) // Declaring the main function
{
Scanner sc=new Scanner(System.in); //Creating Scanner
Class
System.out.println("ENTER THE NUMBER");
int num=sc.nextInt();// Taking input from the User

Happy hp= new Happy(num);// Object of class


hp.check();// check () function is call
}
}

[13]
QUESTION 4:
Write a program to input a number. Check whether the number is a
special two digit number or not.
Example: Sample Input : 59 :: sum of digit : 5+9=14 product
of digit : 5*9 =45 :: sum of digit +product of digit =59
A number is said to be Special two Digit Number only if the sum
of product of digit and sum of digit is equal to that original Number
Class Name: Special2digit

Instance variable/Member variable

int n Integer type variable to store a number.

Member function

Special2digit (int x): Parameterized constructor to assign the value of


x to n.

int sum(int x): Recursive function to compute the sum of digits


and return the value to the check() function.

int product(int x): Recursive function to compute the product of


digits and return the value to the check()
function.

void check(): Invoke sum(…) and product(…) function to check


whether number is specialtwodigit number or
not.

Write main() function to call all the functions defined above.

➢ ALGORITHMS:
• Step 1 : START

[14]
• Step 2 : Create a Class “Special2Digit ”
• Step 3 : Define Recursive Function : int sum( int x );
• Step 4 : Declare Base Case : return 0
• Step 5 : Declare Recursive Case : return (x%10)+sum(x/10);
• Step 6 : Define Recursive Function : int product( int x );
• Step 7 : Declare Base Case : return 1
• Step 8 : Declare Recursive Case : return (x%10)*sum(x/10);
• Step 9 : Creating object of “Special2Digit” Class
• Step 10 : STOP

SOURCE CODE
import java.util.Scanner;// Creating Package for Scanner
Class public class Special2Digit// Creating a Class
{
int n;// Declaring the instance Variable
public Special2Digit(int x) // Declaring the Parameterized
Constructor
{
n=x;// assign the value of x to n
}
public int sum(int x)// Recursive function to calculate the sum of
digits {
if(x== 0)// Base Case
{
return 0;
}
else // Recursive Case
{

[15]
return (x%10)+sum(x/10);
}
}
public int product(int x)// Recursive function to calculate the product of
digits

{
if(x == 0)// Base case
{
return 1;
} else // Recursive case
{
return (x%10)*product(x/10);
}
}
public void check() { int s=sum(n);// invoking the
sum(int x) function int p=product(n);//invoking the
product (int x) function
if((s+p) == n){// checking the condition for Special two digit number
System.out.println("It is Special two digit number");
}else{
System.out.println("It is not Special two digit
Number");
}
}
public static void main(String[] args)// Declaring the main function
{
Scanner sc=new Scanner(System.in); // Creating Scanner

[16]
Class
System.out.println("ENTER THE NUMBER");
int num=sc.nextInt();// Taking input from the User
Special2Digit sd= new Special2Digit(num);// Object of
class sd.check();// check () function is call
}
}

[17]
INPUT/OUTPUT

QUESTION 5 :
Write a program to input a number. Check whether the number
is a special number or not. Example: Sample input =145,
Sum of digits = 1 ! + 4 ! + 5 ! = 1 + 24 + 125 = 145
A number is said to be special number only when the sum of
digit factorial is equal to the original number.

[18]
Class Name: Special

Instance variable/Member variable

Int n Integer type variable to store a number.

Member function

Special(int x); Parameterized constructor to assign the


value of x to n.

int factorial(int x); Recursive function to compute factorial of


the number and return the value to the
sum(…) function.

int sum(int x); Recursive function to compute the sum of


digit’s factorial and return the value to the
check() function.

void check(); Invoke sum(…) function to check whether


the number is a special number or not.

Write main() function to call all the functions defined above.

➢ ALGORITHMS:
• Step 1 : START
• Step 2 : Create a Class “Special ”
• Step 3 : Define Recursive Function : int factorial( int x );
• Step 4 : Declare Base Case : return 1 ;
• Step 5 : Declare Recursive Case : return x*factorial(x-1);
• Step 6 : Define Recursive Function : int sum( int x );
• Step 7 : Declare Base Case : return 1
• Step 8 : Declare Recursive Case :return factorial(x
%10)+sum(x/10);
• Step 9 : Create object of “Special ” class

[19]
• Step 10 : STOP

SOURCE CODE
import java.util.*;// creating package for Scanner class class
Special // Creating a Class

{
int n;// to store a number
Special(int x)// Declaring the parameterized constructor
{
n=x;// assign the value of x to n
}
int factorial(int x)// Recursive function to calculate factorial of digits
{
if(x==0 || x==1)// Base case
{
return 1;
}else// Recursive Case
{
return x*factorial(x-1);
}
}
int sum( int x) { // Recursive function to calculate the sum of
digits
if(x == 0){ // Base case
return 0 ;
} else { // Recursive case
return factorial(x%10)+sum(x/10);
[20]
}
}// check whether the number is special number or
not void check ( ) { int s=sum(n);
if(s==n){// checking the condition for special number
System.out.println("It is Special number");
}else{
System.out.println("It is not Special Number");
}
}
public static void main(String[] args) // Declaring the main
function {
Scanner sc=new Scanner(System.in); // Creating Scanner
Class
System.out.println("ENTER THE NUMBER"); int
num=sc.nextInt();// Taking input from the User
Special sp=new Special(num);// Constructor
sp.check();// Check function is call
}
}

INPUT/OUTPUT

[21]
QUESTION 6 :
A number is said to be a Goldbach number if the number can be
expressed as the addition of two odd prime numbers pairs. If we
follow the above condition then we can find that every even
number larger than four is a Goldbach number because it must
have any pair of odd prime numbers . Ex -6= 3,3 , 10= 3,7 and 5,5.
Write a program to enter any positive even natural number N where
(1<=N<=50) and generate odd prime pairs of N
Class Name: Goldbach

Instance variable/Member variable

Int n Integer type variable to store a number.

Member function

Goldbach(int x); Parameterized constructor to assign the value


of x to n.

int prime(inty,inti); Recursive function to compute how many


times the number y is divisible by i and return
the value to the print() function.

void print(); Invoke prime(…) function to print the prime


pairs of the given number and check whether
the number is a Goldbach number or not.

Write main() function to call all the functions defined above.

➢ ALGORITHMS :
• Step 1 : START

[22]
• Step 2 : Create a Class “Goldbach ”
• Step 3 : Define Recursive Function : int prime( int y ,int i );
• Step 4 : Declare Base Case : return 1 ;
• Step 5 : Declare Recursive Case : return prime ( y , i- 1 ) ;
• Step 6 : Define print( ) Function
• Step 7 : Create a object of “ Goldbatch ”class
• Step 8 : STOP

SOURCE CODE
import java.util.*;// creating package for Scanner class class
Goldbatch // Creating a Class
{
int n; // to store the number
Goldbatch(int x) { // Declaring the parameterized
constructor
n=x; // assign the value of x to n
} // Recursive function to check whether it is prime number or
not
int prime ( int y , int I ) { if ( y <
2) { // 0 and 1 are not prime
return 0 ;
} if ( i == 1 ){ // Base case
return 1;
} if (y % i == 0){ // /Not prime if it is divisible by i
return 0;
}

[23]
return prime ( y , i- 1 ) ; // recursive call
} // printing the pair of prime number void
print(){
boolean isGoldbatch=false;
System.out.println("Prime pair for "+n+" :" );
for(int i=1;i<(n/2);i++){ int j=n-i; if (( prime ( i, (
i / 2 )) == 1) && ( prime ( j , ( j / 2)) ==
1)){
// printing the prime pair of number
System.out.println(i+" + "+j +" = "+n);
isGoldbatch=true;
}
}// checking the condition for goldbatch number
if(isGoldbatch){
System.out.println(" IT IS A GOLDBATCH NUMBER ");
}else{
System.out.println(" IT IS NOT A GOLDBATCH NUMBER
");
}
}
public static void main(String[]args){
Scanner sc=new Scanner(System.in);// Creating Scanner
Class
System.out.println("ENTER THE NUMBER ");
int n=sc.nextInt();// accept the number from User
if((n>=1)&&(n<=50) &&(n%2==0)){
Goldbatch gb=new Goldbatch(n);// constructor
gb.print();// print function is call

[24]
}else{
System.out.println("please enter the number greater than 1
and less the 50 number that is positve even number");
}
}
}

[25]
INPUT/OUTPUT

[26]
MATRIX
PROGRAM
S
QUESTION 7 :
Write a program to declare a matrix A [][] of order (M x N) where M
is the number of rows and N is the number of columns such that
both M and N must be greater than 2 and less than 10. Allow the
user to input integers into this matrix. Display appropriate error
message for an invalid input.

Perform the following tasks on the matrix:


1. Display the original matrix.
2. Shift each row one step upward so the first row will become
the last row 2nd row will be the 1st row and so on.
3. Display the rotated matrix along with the highest element and
its location in the matrix.
Example:
Input: M=3, N=4

[27]
Enter element in the matrix :
1 2 3 4

5 6 7 8

2 1 3 4
OUTPUT:
Original Matrix: New Matrix:
1 2 3 4 5 6 7 8

5 6 7 8 2 1 3 4

2 1 3 4 1 2 3 4

➢ ALGORITHMS:
• STEP 1: Start the program.
• STEP 2: Create a Scanner object for input.
• STEP 3: Prompt the user to enter the number of rows (m).
• STEP 4: Read the value of m using the Scanner.
• STEP 5: Prompt the user to enter the number of columns (n).
• STEP 6: Read the value of n using the Scanner.
• STEP 7: Declare two 2D arrays arr and kb of size m x n. •
STEP 8: Prompt the user to enter m * n elements for the
matrix.
• STEP 9: Use nested loops to read elements into the array arr.

[28]
• STEP 10: Print the original matrix arr row by row using nested
loops.
• STEP 11: Initialize nested loops for transforming rows in the
matrix.
• STEP 12: Check if i == 0, copy the first row of arr to the
last row of kb.
• STEP 13: Otherwise, shift rows of arr downward to kb.
• STEP 14: Print the new matrix kb row by row using nested loops.
• STEP 15: End the program

SOURCE CODE
import java.util.Scanner; public
class Matrix2{
public static void main(String[]args)
{ Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF ROW ");
int m=sc.nextInt();
System.out.println("ENTER THE NUMBER OF COLUMN");
int n=sc.nextInt();
if (m <= 2 || m >= 10 || n <= 2 || n >= 10) {
System.out.println("Error: Number of rows and columns must
be greater than 2 and less than 10."); return;
}
int arr[][]= new int [m][n];
int kb[][]=new int [m][n];
System.out.println("ENTER THE "+(m*n)+" NUMBER OF ELEMENTS
"); for(int i=0;i<m;i++){
for(int j=0;j<n;j++)

[29]
{ arr[i]
[j]=sc.nextInt();
}
}
System.out.println(" ORIGINAL MATRIX ");
for(int i=0;i<m;i++){ for(int j=0;j<n;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println();int na=2;
for(int i=0;i<m;i++){ for(int
j=0;j<n;j++){ if(i==0){
kb[m-1][j]=arr[i][j];

}else{
kb[i-1][j]=arr[i][j];
}
} }
System.out.println(" NEW MATRIX ");
for(int i=0;i<m;i++){ for(int
j=0;j<n;j++){
System.out.print(kb[i][j]+" ");
}
System.out.println();
}
}
}

[30]
INPUT/OUTPUT

QUESTION 8:
Write a program to declare a square matrix A [][] of order (M x M)
where M is the number of rows and is the number of columns, such
that M must be greater than 2 and less than 10. Allow the user to
input integers into this matrix. Display appropriate error message
for an invalid input.

[31]
Perform the following tasks on the matrix: I.
Display the original matrix.
II. Check if the given matrix is Symmetric or not. A square matrix
is said to be a Symmetric, if the element of ithrow and jth
column is equal to the element of the jthrow and ithcolumn..
III. Find the sum of the elements of left diagonal and the sum of
the elements of right diagonal of the matrix and display them.
Example:
Input: M=3
Enter element in the matrix:

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.
Sum of left diagonal = 11
Sum of right diagonal = 10

➢ ALGORITHMS:
[32]
• STEP 1: Start the program.
• STEP 2: Create a Scanner object for user input.
• STEP 3: Prompt the user to enter the number of rows (m).
• STEP 4: Read the value of m using the Scanner.
• STEP 5: Prompt the user to enter the number of columns (n).
• STEP 6: Read the value of n using the Scanner.
• STEP 7: Declare a 2D array arr of size m x n.
• STEP 8: Prompt the user to input m * n elements for the matrix.
• STEP 9:Use nested loops to read elements into arr.
• STEP 10: Print the original matrix row by row using nested loops.
• STEP 11: Initialize a boolean variable isSymmetric to true.
• STEP 12: Use nested loops to check if arr[i][j] equals arr[j]
[i]; if not, set isSymmetric to false.
• STEP 13: Print whether the matrix is symmetric based on the value of
isSymmetric.
• STEP 14: Calculate the sum of the left diagonal (arr[i][i]) and
right diagonal (arr[i][n - i - 1]) using a loop.
• STEP 15: Print the sums of the left and right diagonals.

• STOP

SOURCE CODE
import java.util.Scanner; public
class Symmetric{
public static void main(String[]args)
{ Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF ROW ");
int m=sc.nextInt();

[33]
System.out.println("ENTER THE NUMBER OF COLUMN");
int n=sc.nextInt(); int arr[][]= new int [m][n];
if (m <= 2 || m >= 10 || n <= 2 || n >= 10) {
System.out.println("Error: Number of rows and columns must
be greater than 2 and less than 10."); return;
}
System.out.println("ENTER THE "+(m*n)+" NUMBER OF ELEMENTS
"); for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
{ arr[i]
[j]=sc.nextInt();
}
}
System.out.println(" ORIGINAL MATRIX ");
for(int i=0;i<m;i++){ for(int j=0;j<n;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println();
boolean isSymetric=true;
for(int i=0;i<m;i++)
{ for(int j=0;j<n;j++){
if(arr[i][j] != arr[j][i]){
isSymetric=false;
}
}}
if(isSymetric){
System.out.println("it is Sysmetric Matrix");
}else{
System.out.println("it is not a Sysmetric MATRIX ");

[34]
}
// FINDING THE SUM OF THE LEFT DIAGONAL
// AND LEFT DIAGONAL int
leftDiagonalSum = 0, rightDiagonalSum = 0;
// Calculate the sums of diagonals for
(int i = 0; i < n; i++) { leftDiagonalSum +=
arr[i][i]; // Left diagonal
rightDiagonalSum += arr[i][n - i - 1]; // Right diagonal
}
System.out.println("Sum of Left Diagonal: " + leftDiagonalSum);
System.out.println("Sum of Right Diagonal: " + rightDiagonalSum);
}
}

[35]
INPUT/OUTPUT

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

[36]
II. Find the maximum and minimum value in the matrix and display
them along with their position.
III. Sort the element of the matrix in ascending order using any standard
sorting technique and rearrange them in the matrix. Display the new
matrix.Example: Input: M=3, N=4
Enter element in the matrix:
8 7 9 3

-2 0 4 5

1 3 6 -4
OUTPUT:
Original Matrix:
8 7 9 3

-2 0 4 5

1 3 6 -4

Largest number= 9, Row=2, Column=3


Smallest number= -4, Row=0, Column=0

Rearranged matrix:

-4 -2 0 1

3 3 4 5

6 7 8 9

➢ ALGORITHMS:
• STEP 1 : Start
• STEP 2 : Initialize a Scanner object for user input.
• STEP 3 : Input the number of rows m and columns n.

[37]
• STEP 4 : Validate that m and n are greater than 2; otherwise,
terminate with an error message.
• STEP 5 :Declare a 2D array arr[m][n] to store the matrix
elements and a 1D array kb[m*n] to store sorted elements.
• STEP 6 : Prompt the user to input m*n elements into the
matrix.
• STEP 7 : Fill the matrix arr with user input and copy the
elements into kb sequentially.
• STEP 8 : Display the original matrix by iterating through arr
and printing its elements.
• STEP 9 : Sort the kb array using Bubble Sort to arrange
elements in ascending order.
• STEP 10 :Find the maximum and minimum values in the matrix
using nested loops:
Update the maximum value and its position (max, r, c).
Update the minimum value and its position (min, mr, mc).
• STEP 11 :Repopulate the matrix arr using the sorted values
from kb and a counter variable.
• STEP 12 :Display the sorted matrix by iterating through arr.
• STEP 13 :Print the largest value, its row and column position.
• STEP 14 :Print the smallest value, its row and column position.
• STEP 15 : STOP.

SOURCE CODE
import java.util.Scanner; // Import Scanner class for user input
public class Matrix1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

[38]
System.out.println("ENTER THE NUMBER OF ROW "); int
m = sc.nextInt(); // Read the number of rows
System.out.println("ENTER THE NUMBER OF COLUMN"); int n
= sc.nextInt(); // Read the number of columns int arr[][] = new
int[m][n]; // Initialize a 2D array for the matrix int kb[] = new
int[m * n]; // Initialize a 1D array to store all elements of the matrix
System.out.println("ENTER THE " + (m * n) + " NUMBER OF ELEMENTS
");
for (int i = 0; i < m; i++) { // Loop to traverse rows for
(int j = 0; j < n; j++) { // Loop to traverse columns arr[i][j]
= sc.nextInt(); // Read each element of the matrix
}
}
System.out.println(" ORIGINAL MATRIX "); int ad
= 0; // Initialize counter for the 1D array for (int i = 0; i
< m; i++) { // Loop to traverse rows for (int j = 0; j <
n; j++) { // Loop to traverse columns
System.out.print(arr[i][j] + " "); kb[ad] = arr[i]
[j]; // Copy element to the 1D array ad++; //
Increment counter
}

System.out.println(); // New line after each row


}
for (int i = 0; i < kb.length - 1; i++) { // Outer loop for Bubble
Sort
for (int j = 0; j < kb.length - i - 1; j++) { if (kb[j] >
kb[j + 1]) { // Compare adjacent elements int temp
= kb[j]; // Swap if first greater than second kb[j] =
kb[j + 1]; // Place smaller element first kb[j + 1] =
temp; // Place larger element next

[39]
}
}
}
System.out.println("Rearrange Matrix"); int cd =
0; // Initialize counter for rearranging the matrix for (int
i = 0; i < m; i++) { // Loop to traverse rows for (int j = 0;
j < n; j++) { // Loop to traverse columns
arr[i][j] = kb[cd]; // Assign sorted value back to the matrix
System.out.print(arr[i][j] + " "); cd++; // Increment
counter
}
System.out.println(); // New line after each row
}
System.out.println(); // Line break for separation
System.out.println("Largest Element :: " + arr[(m - 1)][n - 1]);
System.out.println(" ROW :: " + (m - 1) + " COLUMN :: " + (n - 1));
System.out.println("Smallest Element :: " + arr[0][0]);
System.out.println(" ROW :: " + 0 + " COLUMN :: " + 0);
}
}

[40]
INPUT/OUTPUT

Question 10 :
Write a program to declare a square matrix A [][] of order (M x
M) where M is the number of rows and is the number of
columns, such that M must be greater than 2 and less than 10.
Allow the user to input integers into this matrix. Display

[41]
appropriate error message for an invalid input. Perform the
folLowing tasks on the matrix: I. Display the original matrix.
II. Convert the sum of digits of each element to a
single digit.
III. Display the new matrix. Example:
Input: M=3
Enter element in the matrix :

123 569 47
23 49 56
355 145 467

OUTPUT:
Original Matrix:
123 579 47

23 49 56

355 345 467


New Matrix:
6 3 2

5 4 2

4 3 8

➢ ALGORITHMS:
• STEP 1: Start the program.
• STEP 2: Create a scanner object for user input.

[42]
• STEP 3: Prompt the user to enter the number of rows (m).
• STEP 4: Read the value of m using the scanner.
• STEP 5: Prompt the user to enter the number of columns (n).
• STEP 6: Read the value of n using the scanner.
• STEP 7: Declare a 2d array arr of size m x n.
• STEP 8: Prompt the user to input m * n elements for the
matrix.
• STEP 9: Use nested loops to read elements into arr.
• STEP 10: Print the original matrix row by row using
nested loops.
• STEP 11: Initialize nested loops to traverse all elements
of the matrix.
• STEP 12: For each element, reduce it to a single-digit
sum of its digits.
• STEP 13: Use a while loop to repeatedly sum the
digits until the value becomes a single digit.
• STEP 14: Update each element in the matrix with its
reduced single-digit value.
• STEP 15: Print the transformed matrix row by row using
nested loops.
• STEP 16: Stop.

SOURCE CODE
import java.util.Scanner; public
class Matrix{

[43]
public static void main(String[]args)
{ Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF ROW ");
int m=sc.nextInt();
System.out.println("ENTER THE NUMBER OF COLUMN");
int n=sc.nextInt();int arr[][]= new int [m][n]; if (m <= 2 ||
m >= 10 || n <= 2 || n >= 10) {
System.out.println("Error: Number of rows and columns must
be greater than 2 and less than 10."); return;
}
System.out.println("ENTER THE "+(m*n)+" NUMBER OF ELEMENTS
"); for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
{ arr[i]
[j]=sc.nextInt();
} }
System.out.println(" ORIGINAL MATRIX ");
for(int i=0;i<m;i++){ for(int j=0;j<n;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println(" NEW MATRIX ");
for(int i=0;i<m;i++){ for(int
j=0;j<n;j++){ int d=arr[i][j];
while(d>9){ sum=0;

[44]
while(d != 0){ sum=sum+(d%10);
d=d/10;
}
d=sum;
}
arr[i][j]=d;
}}
for(int i=0;i<m;i++)
{ for(int j=0;j<n;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

[45]
INPUT/OUTPUT

[46]
STRING BASED
PROGRAMS
QUESTION 11 :
Write a program to accept a sentence which may be terminated by
either ‘.’, ‘?’ or ‘!’ only. The words may be separated by a single
blank space and should be case- insensitive.
Perform the following tasks:
i) Determine if the accepted sentence is a Pangram or not.
[A Pangram is a sentence that contain every letter of the
alphabet at least once.]
Example: “The quick brown fox jumps over the lazy dog”.

ii) Display the first occurring longest and shortest word in


the accepted sentence.

➢ ALGORITHMS :
• STEP 1 : CREATE CLASS .
• STEP 2 : CHECK IF THE SENTENCE ENDS WITH ‘ ! ’ OR ‘ ? ’ OR ‘ .
’.

[47]
• STEP 3 : REMOVE WHITESPACE AND CONVERT ALL
CHARACTERS IN TO LOWER CASE.

• STEP 4 : CHECK FOR PANGRAM .


• STEP 5 : SPLIT SENTENCE INTO WORDS.
• STEP 6 : FIND LONGEST AND SHORTEST WORDS.
• STEP 7 : DISPLAY THE OUTPUT.
• STEP 8 : END.

SOURCE CODE
import java.util.*;

class Pangram {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter a sentence:");

String str = sc.nextLine();

int c = 0;

String st = str;

String[] array = st.split(" ");

str = str.replaceAll("\\s", "");

str = str.toLowerCase();

[48]
if (str.charAt(str.length() - 1) == '?' || str.charAt(str.length() - 1)
== '.' || str.charAt(str.length() - 1) == '!') {

for (char i = 'a'; i <= 'z'; i++) { for

(int j = 0; j < str.length(); j++)

{ if (str.charAt(j) == i) {

c++; break;

if (c == 26) {

System.out.println("The string is a pangram.");

} else {

System.out.println("The string is not a pangram.");

String shortestWord = array[0];

String longestWord = array[0];

for (int i = 1; i < array.length; i++) { if

(array[i].length() < shortestWord.length()) {

shortestWord = array[i];

[49]
if (array[i].length() > longestWord.length())

{ longestWord = array[i];

System.out.println("The longest word is: " + longestWord);

System.out.println("The shortest word is: " + shortestWord);

} else {

System.out.println("Wrong input: the string does not end


with ?, . or !");

[50]
INPUT/OUTPUT

QUESTION 12:
Most (Not all) cell phone keypads look like the following
arrangement (the letters are above the respective number).

[51]
1 ABC DEF
2 3

GHI JKL MNO


4 5 6

PQRS TUV WXYZ


7 8 9

[SPACE]
0

For sending text/ SMS the common problem is the number of


keystrokes to type a particular text.

For example, the word STOP, there are a total 9 keystrokes needed
to type the word. You need to press the key 7 four times, the key 8
once, the key 6 three times and the key 7 once to get it.

Develop a program code to find the number of keystrokes needed


to type the text.

Accept a word without any punctuation marks, numbers or white


spaces and the text message would consist of just 1 word.

Example: Input: DEAR

Output: Number of key strokes= 7

[52]
➢ ALGORITHMS:
• STEP 1: Start the program an initialize a Scanner for user input.
• STEP 2: Prompt the user to input a word and store it in the
string n.
• STEP 3: Define an array alpha containing groups of characters
mapped to keypad buttons.
• STEP 4: Convert the input string n to uppercase for uniformity.
• STEP 5: Initialize a variable sum to store the total number of
keystrokes.
• STEP 6: Iterate through each character ch of the input string n.
• STEP 7: For each character ch, search in each group of the
alpha array.
• STEP 8: Find the position of ch in the group and add (position
+ 1) to sum.
• STEP 9: Display the original word and the calculated number
of keystrokes.

• STEP 10: End the program

SOURCE CODE
import java.util.Scanner; public class

Keypads { public static void

main(String[] args) {

// Create a Scanner object to take input from the user

Scanner sc = new Scanner(System.in);

[53]
// Prompt the user to enter a word

System.out.println("Enter the word");

String n = sc.next(); // Read the input word

// Array representing the characters on each keypad button


String alpha[] = {"ABC", "DEF", "GHI", "JKL", "MNO", "PQRS",
"TUV", "WXYZ ” }

int sum = 0; // Initialize the total number of keystrokes

// Loop through each character in the input word

for (int i = 0; i < n.length(); i++) { char ch =

n.charAt(i); // Get the current character

// Loop through each group of characters in the alpha array

for (int j = 0; j < alpha.length; j++) {

// Loop through each character in the current

group for (int k = 0; k < alpha[j].length(); k++) {

char c = alpha[j].charAt(k);

// Check if the input character matches the current character


from the group

if (ch == c) {

int a = k; // Position of the character in the group

sum += (a + 1);

continue; // Exit the inner loop once a match is found

[54]
}

// Display the original word

System.out.println("Original Word :: " + n);

// Display the total number of keystrokes

System.out.println("Number of KeyStrokes :: " + sum);

INPUT/OUTPUT

[55]
QUESTION 13 :.
Write a program to check is a string is an Anagram of another string.
Two strings are anagrams if they can be rearranged to form the
same string. For example: “listen” and “silent” are anagrams.

Accept two strings from the user and check if they are anagrams of
each other. Ensure that the comparison is case-insensitive and
ignores spaces. Display an appropriate message based on whether
they are anagrams or not. If any of the strings contain invalid
character(e.g., numbers or special characters), generate an error
message.

➢ ALGORITHMS:
• STEP 1 : Create class.
• STEP 2 : Accept two strings as input from the user.
• STEP 3 : Remove all whitespaces and convert into lowercase.
• STEP 4 : Check wether any of the strings contain special
characters or not.

• STEP 5 : Convert each string into a character array.


• STEP 6 : Sort the character arrays alphabetically.
• Step 7 : Compare the sorted arrays.
• STEP 8 : Display the result.

[56]
SOURCE CODE
import java.util.*; class

anagram{

public static void main(String[]args){

Scanner sc=new Scanner(System.in);

System.out.println("enter first string");

String s1=sc.nextLine();

System.out.println("enter second string");

String s2=sc.next();

//removing white spaces from the strings

s1=s1.trim();

s2=s2.trim();

char ch='\u0000';

int count1=0; int

count2=0;

//converting the strings in same case so that they are case


insensative s1=s1.toUpperCase();
s2=s2.toUpperCase();

//checking for any special numbers in first string

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

[57]
ch=s1.charAt(i); if(!

Character.isLetter(s1.charAt(i))){

count1++;

//checking for any special numbers of numbers in second


string for(int i=0;i<s2.length();i++){ ch=s2.charAt(i);
if(!Character.isLetter(s2.charAt(i))){ count2++;

//checking if the strings are anagram

if(count1==0&&count2==0){ char

c1[]= s1.toCharArray(); char c2[] =

s2.toCharArray();

Arrays.sort(c1);

Arrays.sort(c2); s1=new

String(c1); s2=new

String(c2);

if(s1.compareTo(s2)==0){

System.out.println("strings are anagram");

[58]
}

else{

System.out.println("Strings are not anagram");

//Error message if there are any special characters or


numbers in any of the strings

else{

System.out.println("Error 404");

System.out.println("only aphabets are allowed");

[59]
INPUT/OUTPUT

[60]
OBJECT
PASSING
PROGRAMS
QUESTION 14:.
A sports academy wants to conduct a friendly match between
two teams with maximum fifteen players. A class Sports
contains three data members, to store the name of the team
with ‘n’ number of players and a one- dimensional array to
store height of each player. Design a class Sports to compare
average height of both the teams. The details of the members
of the class are given below:

Class Name: Sports

Instance variable/Member
variable

Height[] To store the height of each player

Name To store the name of the team

[61]
N To store total number of players

Member function

Sports(): Default constructor

Sports(int n, String name): To initialize the number of


players and name of the team.

void fillHeight(): To enter the heights of all


players.

Double averageHeight(): To calculate average height of


both the team

String compare(Sports To compare the average height of


s1,Sports s2) : both the teams and return the
name of the team with the
higher average height to the
main() function.

Void display(String msg): To display the name of the team


with the higher average height
stored in msg . if both the teams
have the same average height,
then it msg should be “Both
teams have the same average
height”

Write main() function to call all the functions given above.

➢ ALGORITHMS:

[62]
• STEP 1 : Define class .
• STEP 2 : Declare instance variables.
• STEP 3 : Create parameterised constructor.
• STEP 4 : Take input from the user.
• STEP 5 : Calculate average height.
• STEP 6 : Compare the average height of both the teams.
• STEP 7 : Create main method.
• STEP 8 : Call the functions.
• STEP 9 : STOP.

SOURCE CODE
import java.util.*;

class Sports{ int

Height[]; String

Name;

int N;

Sports(int n,String name){

Name=name;

N=n;

Height= new int[N];

[63]
void fillHeight(){

Scanner sc=new Scanner(System.in);

System.out.println("enter heights of all players");

for(int i=0;i<N;i++){

Height[i]=sc.nextInt();

Double averageHeight(){

double ah=0.0;

double th=0.0; for(int

i=0;i<N;i++)

{ th=th+Height[i];

ah=th/N;

return ah;

String compare(Sports s1,Sports s2)

{ double ah1=s1.averageHeight();

double ah2=s2.averageHeight();

System.out.println("Name of the team 1 :"+s1.Name+" average


height of team 1 :"+ah1);

[64]
System.out.println("Name of the team 1 :"+s2.Name+" average
height of team 2 :"+ah2); if(ah1>ah2) return s1.Name;
else if(ah2>ah1) return s2.Name;

else

return "Both teams have the same average height";

void display(String msg){

System.out.println(msg);

public static void main(){

Sports s1=new Sports(5,"ABC");

Sports s2=new Sports(5,"CBA");

s1.fillHeight();

s2.fillHeight();

String a=s1.compare(s1,s2);

s1.display(a);

[65]
INPUT/OUTPUT

QUESTION 15 :

[66]
A super class Demand has been defined to store the details of
the demands for a product. Define a subclass Supply which
contains the production and supply details of the products.

The details of the members of both the classes are given below:
Class Name: Demand
Instance variable/Member
variable
Pid String to store the product ID
pname String to store the name of the
product
pdemand Integer to store the quantity
demanded for the product.
Member function
Demand (…): Parameterized constructor to
assign the values to data
members.
Void display(): To display the details of the
product.
Class Name Supply
Pproduced Integer to store the quantity of the
product produced.
Prate To store the cost per unit of the
product in decimal.
Supply (….): Parameterized constructor to
assign the values to data members
of both the classes.
Double calc() Returns the difference between

[67]
the amount (rate x demand) and
the amount produced (rate x
produced)
Void display() To display the details from the
super class and the difference
between the amount (rate x
demand) and the amount
produced (rate x produced)
Assume that the super class Demand has been defined using the
concept of inheritance, specify the class Supply giving the details of
the constructor (….), double calc () and void display (). The super
class, main () function and algorithm need not be written.

➢ ALGORITHMS:
• STEP 1 : Define subclass Supply.
• STEP 2 : Inherit the attributes of the superclass Demand using
extends keyword.
• STEP 3 : Declare the additional attributed for Supply.
• STEP 4 : Create a constructor for Supply.
• STEP 5 : Define method calc() to find the difference between
Prate * pdemand and Prate * Pproduced.
• STEP 6 : Define method display() to print the details and the
difference.
• STEP 7 : STOP.

SOURCE CODE

[68]
class Supply extends Demand{

int Pproduced; double Prate;

Supply(String id,String name,int pdmnd,int pp,double prate)

super(id,name,pdmnd);

Pproduced=pp;

Prate=prate;

double calc(){

double amt1=Prate*pdemand;

double amt2=Prate*Pproduced;

double diff=amt2-amt1;

return diff;

void display(){

System.out.println("Product name "+pname);

System.out.println("Product id "+Pid);
System.out.println("Product demand "+pdemand);

System.out.println("Product produced "+Pproduced);

System.out.println("Product rate "+Prate);

System.out.println("The difference is "+calc());

[69]
}

INPUT/OUTPUT

[70]
STACK
PROGRAMS
QUESTION 16 :.
Implement Stack in Java using array using the given details:
Class Name: Stack
Instance variable/Member
variable
int st[] To store the integers
int size To store the size of the stack
int top To store the index of stack.
Member function
Stack(int s): To initialize size with s, top with -1
and define the array with the size
‘size’
void push(int n): To enter the element if stack is
empty. Otherwise display
overflow message.

[71]
int pop(): Return the deleted element. In
case of underflow return -9999.
void display(): To display the stack elements in
LIFO order.

➢ ALGORITHMS:
• STEP 1 : Define class.
• STEP 2 : Define instance variables.
• STEP 3 : Create constructor to initialize the variables.
• STEP 4 : Create a push method.
• STEP 5 : Create a pop method.
• STEP 6 : Create display method.
• STEP 7 : Create main method.
• STEP 8 : Create an infinite loop to accept input from the
user.

SOURCE CODE
import java.util.*;
class Stack {
int st[];

[72]
int size;
int top;
//constructor to initialize
variables Stack(int s){ top=-1;
size=s;
st=new int[size];
}
// push method
void push(int n)
{ if(top==size-1){
System.out.println("Stack overflow");
}
else{ t
op++;
st[top]=n;
System.out.println("pushed element "+n);
}
}
//pop function
int pop()
{ if(top==-1){
System.out.println("Stack underflow");
return -9999;
}
else{
System.out.println("Popped element "+st[top]);
top--;
return st[top+1];
}
}

[73]
//display method
void display()
{ if(top==-1){
System.out.println("Stack empty");
}
else{
for(int i=0;i<=top;i++){
System.out.println(st[i]);
}
}
}

INPUT/OUTPUT
CREATING A STACK OF SIZE 3

CALLING push(int ) FUNCTION 3 TIMES WITH 3


DIFFERENT VALUES

[74]
DISPLAY THE PUSHED ELEMENTS

[75]
CALLING pop() FUNCTION TO DELETE
ELEMENTS

STACK OVERFLOW CONDITION

STACK UNDERFLOW CONDITION

[76]
STACK EMPTY CONDITION

[77]
QUEUE
PROGRAM
QUESTION 17 :.
Implement Queue in Java using array using the given details:
Class Name: Queue
Instance variable/Member
variable
int q[] To store the integers.
int size To store the size of the queue.
int front and int rear To store the indices of queue.
Member function
Queue(int s): To initialize size with s, front with
-1, rear with -1 and define the
array with the size ‘size’.
void insertRear(int n): To enter the element if queue is
empty. Otherwise display
overflow message.
int deleteFront(): Return the deleted element. In
case of underflow return -9999.

[78]
void display(): To display the stack elements in
FIFO order.

➢ ALGORITHMS:
• STEP 1 : Create class.

• STEP 2 : Define member variables.

• STEP 3 : Implement constructor to initialize the size and the


array.

• STEP 4 : Create insert rear() funtion to insert an element.

• STEP 5 : Check if the queue is full.

• STEP 6 : If not insert an element and increase rear by 1.

• STEP 7 : Create deletefront() function to delete an element.

• STEP 8 : Create display() method to display the queue.

SOURCE CODE
import java.util.*;//Creating a package for Scanner class class

Queue{//Creating a class

[79]
int q[]; int

size; int

front,rear;

Queue(int s){

size=s;

front=-1; rear=-

1; q=new

int[size];

void insertRear(int a){//To insert an element to the queue

if(rear==size-1){

System.out.println("Queue overflow");

else{

q[++rear]=a;//Adding element to the queue

int deleteFront(){//To delete an element from the queue

int d=0;

if(front==rear){

System.out.println("Queue Underflow");

[80]
}

else{

d=q[++front];//To store the deleted element

System.out.println(d+"Deleted from the queue");

return -9999;

void display(){//To display the elements of the queue in FIFO


order

if(front==rear){

System.out.println("Queue is Empty");

else{

System.out.println("Elements of the Queue in FIFO order :");

for(int i=front+1;i<=rear;i++){

System.out.println(q[i]);

[81]
INPUT/OUTPUT
CREATING A QUEUE OF SIZE 4

CALLING insertRear() FUNCTION 4 TIMES WITH DIFFERENT VALUES

CALLING THE display() FUNCTION

[82]
CALLING THE delete Front() FUNCTION TO DELETE ELEMENTS

QUEUE OVERFLOW CONDITION

QUEUE UNDERFLOW CONDITION

[83]
DOUBLE
ENDED
QUEUE
PROGRAM
QUESTION 18 :.
Implement Double Ended Queue in Java using array using the
given details:
Class Name: DEQueue
Instance variable/Member
variable
int dq[] To store the integers

[84]
int size To store the size of the double
ended queue
int front and int rear To store the indices of double
ended queue.
Member function
DEQueue(int s): To initialize size with s, front with
1, rear with -1 and define the array
with the size ‘size’.
void insertRear(int n): To enter the element at the rear
end if queue is empty. Otherwise
display overflow message.
int deleteFront(): Return the deleted element. In
case of underflow return -9999.
void insertFront(int n): To enter the element at the front
end if queue is empty. Otherwise
display overflow message.
int deleteRear(): Return the deleted element from
the rear end. In case of underflow
return -9999.
void display(): To display the stack elements in
FIFO order.

➢ ALGORITHMS:
• STEP 1 : Create class
• STEP 2 : Define member variables
• STEP 3 : Create a constructor to initialize the member
variables and allocate memory for the array

[85]
• STEP 4 : Create insertrear() function to insert elements at
the rear positon

• STEP 5 : Check if the double ended queue is full


• STEP 6 : If not increase rear and insert the element at
dq[rear]

• STEP 7 : Create insertfront() function to insert elements


at the front position

• STEP 8: Check if there is space to insert at the front ,if no


space ,print overflow and exit.

• STEP 9: Otherwise, insert the value n at dp[front] and


decrease front by 1.

• STEP 10: Create deletefront() function to delete an


element from the front position and return the deleted
element.e

• STEP 11 : Check if the queue is empty by comaring front


and rear, if empty print “underflow ” and exit.

• STEP 12: Create deleteRear() function to delete an


element from the queue from the rear position and
perform the same task as in previous .

SOURCE CODE
class DEQueue{//creating class int

dq[];//creating single dimentional array

int size; int

front,rear;

DEQueue(int s){

[86]
size=s;

front=-1; rear=-

1; dq=new

int[size];

void insertRear(int n){//To insert an element from the


rear end of the dequeue

if(rear==size-1){

System.out.println("Queue overflow");

else{

dq[++rear]=n;//Adding the element

void insertfront(int n)//To insert an element from the


front end of the dequeue

if(front>-1&&front<rear)

dq[front--]=n;//Adding the element

else{

[87]
System.out.println("Queue overflow");

void deleteFront(){//To delete an element from the front


end of the dequeue

int d=0;

if(front==rear){

System.out.println("Queue underflow");

else{

d=dq[++front];

System.out.println(d+" deleted");

void deleteRear(){//To delete an element from the rear


end of the dequeue

if(rear==front){

System.out.println("Queue underflow");

else{

System.out.println(dq[rear--]+" deleted");

[88]
}

void display(){//To display the elements of the Double


ended queue

if(front==rear){

System.out.println("Queue is empty");

else{

System.out.println("The elements of the Double


ended queue are :");

for(int i=front+1;i<=rear;i++){

System.out.println(dq[i]);

INPUT/OUTPUT
CREATING OBJECT WITH OBJECT SIZE 4

[89]
CALLING insertRear() FUNCTION 4 TIMES WITH
DIFFERENT VALUES

DISPLAYING ALL THE ELEMENTS OF THE DOUBLE

[90]
ENEDED QUEUE

OVERFLOW CONDITION

CALLING deleteRear() FUNCTION

CALLING deleteFront() FUNCTION

[91]
DISPLAYING THE ELEMENTS OF THE
DOUBLE ENDED QUEUE

[92]
CALLING insertFront() FUNCTION

DISPLAYING THE ELEMENTS OF THE


DOUBLE ENDED QUEUE

[93]
SINGLY LINKED
LIST
PROGRAM
QUESTION 19 :
Implement singly linked list in Java using the given functions:

Void addNode (int data) - to insert a node.

Void display () - to display the nodes.

Void countNode () - to count the number of nodes.

Void AddAtStart (int data) - to add a node at the beginning.

Void AddAtLast (int data) - to add a node at the last.

Void search (int data) - To search a node.

Void min_max () - to display the smallest and largest node.

Void DeleteFromStart()-to delete the first element.

Void DeleteFromEnd () - to delete the last element.

[94]
➢ ALGORITHMS:
• STEP 1 : Start.
• STEP 2 : Create class named ‘linked list ’.
• STEP 3 : Create a class named ‘node’.
• STEP 4 : Declare the instance variables.
• STEP 5 : Declare the parameterized constructor.
• STEP 6 : Add values to the nodes , head and tail.
• STEP 7 : Declare void addNode(int data) function to add
elements.

• STEP 8 : Declare void display() function.


• STEP 9 : If head = tail, display “List is empty”.
• STEP 10 : Else display all the elements of the single linked
list.

• STEP 11 : declare void countNode() function to count and


display the number of the elements present in the single
linked list.

• STEP 12 : Declare void AddAtStart() function to add


elements at first.

• STEP 13 : Declare void AddAtLast() function to add elements


at last.

• STEP 14 : Declare void DeletefromEnd() function to delete


elements from the starting element and display the deleted
element.

[95]
• STEP 15 : Declare void DeletefromEnd() function to delete
elements from the starting element and display the deleted
element .

• STEP 16 : Declare SearchNode(int data) function to search


the entered element. if the element is not present in the
single linked list , display the message “List is empty ” else
display the searched node along with its position in the
single linked list.

• STEP 17 : Delcare void min_max() to calculate and display


the minimum and maximum value of the node in the single
linked list.

• STEP 18 : Write the main function .


• STEP 19 : Create a object of the ‘Linkedlist’ class and call all
the above functions.

• STEP 20 : STOP.

SOURCE CODE
class linkedlist{
class Node //creating another class
{
int data;//declaring instance variables
Node next;
Node (int data)//declaring the parameterized constructor
{
this.data=data;
this.next=null;
}
}

[96]
public Node head=null; public
Node tail=null; public void
addNode(int data){ Node
newNode=new Node(data);
if(head==null)
{ head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
tail=newNode;
}
}
public void display()//to display the elements of linked list
{
Node current=head;
if(head==null){
System.out.println("list is empty");
}

while(current!=null){
System.out.print(current.data+" ");
current=current.next;
}
System.out.println();
}
public void countNode(){
int count=0; Node
current=head;
while(current!=null){
count++;
current=current.next;

[97]
}
System.out.println("Number of Nodes :"+count);
}
public void AddAtStart(int data)//to add an element at first of the
linked list
{
Node newNode=new Node(data);
if(head==null)
{ head=newNode;
tail=newNode;
}
else{
Node t=head;
head=newNode;
head.next=t;
}
System.out.println("After adding an element in the beginning
the nodes of the singly linkedlist are :");
}
public void AddAtLast(int data)//to add an element at the last of
the linked list
{
Node newNode=new Node(data);
if(head==null)
{ head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
tail=newNode;
}

[98]
System.out.println("After adding an element in the last, the
node of the singly linked list are:");
}
public void DeletefromStart()//to delete the starting element from
the linked list
{
if(head==null){
System.out.println("list is empty");
}
else{
if(head!=tail){
head=head.next;
}
else
{ head=nu
ll;
tail=null;
}
}
System.out.println("After deleting an element from the
beginning the nodes of the singly linked list are:");
}
public void DeletefromEnd()//to delete the last element of the
linked list
{
if(head==null){
System.out.println("List is empty");
}
else{
if(head!=tail){

[99]
Node current=head;
while(current.next!=tail){
current=current.next;
}
tail=current;
tail.next=null;
}
else{ head
=null;
tail=null;
}
}
System.out.println("After deleting an element form the
last, the nodes of singly linked list are :");
}
public void SearchNode(int data)//To search a node present in the
linked list
{
Node current=head;
int i=1;
Boolean f=false;
if(head==null){
System.out.println("List is Empty");
}
else
{
while(current!=null)
{
if(current.data==data)
{ f=true;
break;

[100]
}
i++;
current=current.next;
}
}
if(f==true){
System.out.println("Element "+data+"is present in the singly
linked list at the position "+i);
}
else{
System.out.println("Element is not present in the list");
}
}
//min_max() will find out the minimum and maximum value of
the node in the list

public void min_max(){


Node current=head;
int min;
if(head==null)
{
System.out.println("List is empty");
}
else{
min=head.data;// Initializing min with head node data
while(current!=null)//if current node's data is smaller than min
{ //Then,replace value of min with the current
//node's data
if(min>current.data){
min=current.data;
}
current=current.next;

[101]
}
System.out.println("Minimum value node in the list :"+min);
}
current=head;
int max;
if(head==null){
System.out.println("List is empty");
}
else{
max=head.data;//Initializing max with head node data
while(current!=null){
//if current node's data is greater than max
//Then,replace value of max with current node's data
if(max<current.data){
max=current.data;
}
current=current.next;
}
System.out.println("Maximum value node in the list :"+max);
}
}
public static void main()//Declaring the main function
{
linkedlist ob=new linkedlist();//Creating an object of the
class ob.addNode(7);//Function calling
ob.addNode(5);//Function calling ob.addNode(2);//Function
calling
ob.addNode(10);//Function calling
ob.display();//Function calling
ob.countNode();//Function calling
ob.AddAtStart(6);//Function calling

[102]
ob.display();//Function calling
ob.AddAtLast(15);//Function calling
ob.display();//Function calling
ob.DeletefromStart();//Function calling
ob.display();//Function calling
ob.DeletefromEnd();//Function calling
ob.display();//Function calling
ob.SearchNode(5);//Function calling
ob.min_max();//Function calling
}
}

[103]
INPUT/OUTPUT

[104]
BINARY
TREE
QUESTION 20 :.
Answer the following question from the given binary tree:
A 1. Write the leaf nodes of the tree.
F B
2. Write the nodes of right sub tree.
D G H
3. Write the depth of the node ‘H’.
I E
4. Write the in order traversal of the
tree.
5. Write the preorder traversal of the
tree.
6. Write the post order traversal of
the tree.

[105]
7. Write the internal nodes of left sub
tree.
8. Write the degree of node ‘F’.

SOLUTION
ANS 1) The leaf nodes of the tree are the nodes which does not
have children nodes . D , I , E are the leaf nodes.

ANS 2) The nodes of the right subtree is B,H,E.

ANS 3) The depth of the node ‘H’ is 2.

ANS 4) The in-order traversal of the tree is D,F,G,I,A,B,E,H.

ANS 5) The pre-order traversal of the tree is A , F , D, G , I, B , H ,E.

AND 6) The post-order traversal of the tree is D,I,G,F,E,H,B,A.

ANS 7) The internal nodes of the left sub tree are F,G.

[106]
ANS 8) The degree of the node ‘F’ is 2.

[107]

You might also like