Java Programs for Number Classification
Java Programs for Number Classification
[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.
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.
[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.
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.
[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:
➢ 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
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.
Member function
➢ 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
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.
Member function
➢ 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
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
[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
Member function
➢ 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
Member function
➢ 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
Member function
➢ 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.
[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
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
}
[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
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”.
➢ 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.
SOURCE CODE
import java.util.*;
class Pangram {
System.out.println("Enter a sentence:");
int c = 0;
String st = str;
str = str.toLowerCase();
[48]
if (str.charAt(str.length() - 1) == '?' || str.charAt(str.length() - 1)
== '.' || str.charAt(str.length() - 1) == '!') {
{ if (str.charAt(j) == i) {
c++; break;
if (c == 26) {
} else {
shortestWord = array[i];
[49]
if (array[i].length() > longestWord.length())
{ longestWord = array[i];
} else {
[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
[SPACE]
0
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.
[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.
SOURCE CODE
import java.util.Scanner; public class
main(String[] args) {
[53]
// Prompt the user to enter a word
char c = alpha[j].charAt(k);
if (ch == c) {
sum += (a + 1);
[54]
}
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.
[56]
SOURCE CODE
import java.util.*; class
anagram{
String s1=sc.nextLine();
String s2=sc.next();
s1=s1.trim();
s2=s2.trim();
char ch='\u0000';
count2=0;
for(int i=0;i<s1.length();i++){
[57]
ch=s1.charAt(i); if(!
Character.isLetter(s1.charAt(i))){
count1++;
if(count1==0&&count2==0){ char
s2.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2); s1=new
String(c1); s2=new
String(c2);
if(s1.compareTo(s2)==0){
[58]
}
else{
else{
System.out.println("Error 404");
[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:
Instance variable/Member
variable
[61]
N To store total number of players
Member function
➢ 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.*;
Height[]; String
Name;
int N;
Name=name;
N=n;
[63]
void fillHeight(){
for(int i=0;i<N;i++){
Height[i]=sc.nextInt();
Double averageHeight(){
double ah=0.0;
i=0;i<N;i++)
{ th=th+Height[i];
ah=th/N;
return ah;
{ double ah1=s1.averageHeight();
double ah2=s2.averageHeight();
[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
System.out.println(msg);
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{
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 id "+Pid);
System.out.println("Product demand "+pdemand);
[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
[74]
DISPLAY THE PUSHED ELEMENTS
[75]
CALLING pop() FUNCTION TO DELETE
ELEMENTS
[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.
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];
if(rear==size-1){
System.out.println("Queue overflow");
else{
int d=0;
if(front==rear){
System.out.println("Queue Underflow");
[80]
}
else{
return -9999;
if(front==rear){
System.out.println("Queue is Empty");
else{
for(int i=front+1;i<=rear;i++){
System.out.println(q[i]);
[81]
INPUT/OUTPUT
CREATING A QUEUE OF SIZE 4
[82]
CALLING THE delete Front() FUNCTION TO DELETE ELEMENTS
[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
SOURCE CODE
class DEQueue{//creating class int
front,rear;
DEQueue(int s){
[86]
size=s;
front=-1; rear=-
1; dq=new
int[size];
if(rear==size-1){
System.out.println("Queue overflow");
else{
if(front>-1&&front<rear)
else{
[87]
System.out.println("Queue overflow");
int d=0;
if(front==rear){
System.out.println("Queue underflow");
else{
d=dq[++front];
System.out.println(d+" deleted");
if(rear==front){
System.out.println("Queue underflow");
else{
System.out.println(dq[rear--]+" deleted");
[88]
}
if(front==rear){
System.out.println("Queue is empty");
else{
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
[90]
ENEDED QUEUE
OVERFLOW CONDITION
[91]
DISPLAYING THE ELEMENTS OF THE
DOUBLE ENDED QUEUE
[92]
CALLING insertFront() FUNCTION
[93]
SINGLY LINKED
LIST
PROGRAM
QUESTION 19 :
Implement singly linked list in Java using the given functions:
[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.
[95]
• STEP 15 : Declare void DeletefromEnd() function to delete
elements from the starting element and display the deleted
element .
• 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
[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 7) The internal nodes of the left sub tree are F,G.
[106]
ANS 8) The degree of the node ‘F’ is 2.
[107]