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

Computer Project (Srishti)

Uploaded by

aviralrirdbkt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views

Computer Project (Srishti)

Uploaded by

aviralrirdbkt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 163

LUCKNOW PUBLIC COLLEGE

Sahara States, Jankipuram

COMPUTER SCIENCE
Programming assignments Session:
2023-24

Submitted by - Submitted to -
Name - SANCHITA SRIVASTAVA Mr. Amit Kumar Trivedi

Class & Sec – 12th - A Teacher

Roll Number - 28 Computer Science

UID -

Index Number-
Page|2

CERTIFICATE

Name :- _____________________________________

Class & Sec :- _______ Roll Number:-__________

UID :- ____________ Index Number:- ___________

This is certified to be the bona fide work of the


student in the Computer Science Laboratory
during the academic year 2023-24.
No. of practical certified ______ out of ______
in the subject of Computer Science.

Sign. of Internal Examiner:


Sign. of External Examiner:

ACKNOWLEDGMENT

I would like to express my special thanks of gratitude


to my teacher Mr. Amit Kumar Trivedi as well as our
respected principal Ms. Meena Tangri who gave me
the golden opportunity to do this wonderful project,
which also helped me in doing a lot of Research and I
came to know about so many new things I am really
thankful to them.
Secondly I would also like to thank my parents and
friends who helped me a lot in finalizing this project
within the limited time frame.

Name:

Class & Sec. :


Page|4

PROGRAM 1
A Goldbach number is a positive even integer that can be expressed as the sum
of two odd primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example:
6=3+3
10 = 3 + 7
10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime
pairs, i.e. 3 and 7, 5 and 5.
Write a program to accept an even integer 'N' where N > 9 and N < 50. Find all
the odd prime pairs whose sum is equal to the number 'N'.
Test your program with the following data and some random data:
Example 1
INPU
T:
N=
14
OUTPUT:
PRIME PAIRS ARE:
3, 11
7, 7
Example 2
INPU
T: N =
30
OUTPUT:
PRIME PAIRS
ARE: 7, 23
11, 19
13, 17
Example 3
INPU
T: N =
17
OUTPUT:
INVALID INPUT. NUMBER IS ODD.
Example 4
INPUT:
N = 126
OUTPUT:
INVALID INPUT. NUMBER OUT OF RANGE.
Page|6

ALGORITHM:
• Initialize a number ‘N’.
• Store it in a variable.
• Check if the number is even or not.
• If the number is odd, print “Invalid Input’.
• If the number is even then,
o Define two arrays. One for storing prime numbers and other for
calculating the prime numbers.
o Find all prime numbers till the entered number
using a ‘for loop’ and store it in an array.
o In the second array, store only odd prime numbers using ‘if’ statement.

o Display the odd prime pairs.

SOURCE CODE:
import java.util.*;
public class Goldbach
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in); int
i,j,k,b=0,c=0,num=0,sum=0;
System.out.println("Enter the number: "); int
num=sc.nextInt(); k=num;
int arr1[]=new int[num];
int arr2[]=new int[num];
if(num%2!=0)
{
System.out.println("Invalid Input, Number is odd");
}
else
{
for(i=1;i<=num;i++)
{
for(j=1;j<=i;j++)
{ if(i
%j==0)
{ c
++;
}
}
if((c==2)&&(i%2!=0))
{ arr1[
b]=i; arr2[b]=i;
b++;
}
c=0;
}
System.out.println("Odd and prime pairs are: ");
for(i=0;i<b;i++)
{
for(j=i;j<b;j++)
{
sum=arr1[i]+arr2[j];
if(sum==k)
{
System.out.print(arr1[i]+" , "+arr2[j]);
System.out.println();
Page|8

}
}
}
System.out.println(k+" is a Goldbach Number");
}
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description

i int For loop

j int For loop

k int Copy of original number

b int For odd prime number

c int For even prime number

sum int For finding sum of number

num int For inputting number

OUTPUT:
PROGRAM 2
Write a program to declare a matrix a[][] of order (m × n) where 'm' is the
number of rows and 'n' is the number of columns such that the values of both 'm'
and 'n' must be greater than 2 and less than 10. Allow the user to input integers
into this matrix. Perform the following tasks on the matrix:

1. Display the original matrix.


2. Sort each row of the matrix in ascending order using any standard
sorting technique.
3. Display the changed matrix after sorting each row.

Test your program for the following data and some random data:
P a g e | 10

Example 1
INPUT:
M
=4
N=3
ENTER ELEMENTS OF MATRIX:
11 -2 3
5 16 7
9 0 4
3 1 8
nnOUTPUT:
ORIGINAL
MATRIX
11 -2 3
5 16 7
9 0 4
3 1 8
P a g e | 11

MATRIX AFTER SORTING ROWS


-2 3 11
5 7 16
04 9
13 8
Example 2
INPUT: M = 10
N= 10
ENTER ELEMENTS OF MATRIX 10
22 57 36 12 12

9 13 6
OUTPUT:
ORIGINAL MATRIX
22 5 19

2023-23| SANCHITA SRIVASTAVA


P a g e | 12

7 36
12 9
13 6
MATRIX AFTER SORTING ROWS
5 19 22 7 12 36
6 9 13
Example 3
INPUT:
M
N= 5
OUTPUT:
MATRIX SIZE OUT OF RANGE

ALGORITHM:
• Start.
• Declare variables.
• Check if the value of m and n is less than 2 and greater than 10, if so print
‘Invalid Input’ and terminate the program.

• Else.
• Create a matrix of order ‘M’*’N’.
• Enter the values in the matrix.
• Find the largest number.
P a g e | 13

• Find the smallest number.


• Rearrange the matrix with the smallest number first and largest number at
last.

• Display the final rearranged matrix.


• Close the program.

SOURCE CODE:
import java.util.Scanner;
public class ArraySort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF M: ");
int m = in.nextInt();
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
if (m <= 2|| m >= 10|| n <= 2 || n >= 10)
{
System.out.println("Invalid Input");
return;
}
int a[][] = new int[m][n];
System.out.println("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++)

2023-23| SANCHITA SRIVASTAVA


P a g e | 14

System.out.println("ENTER ELEMENTS OF ROW " + (i+1) + ":");


for (int j = 0; j < n; j++)
{
a[i][j] = in.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{

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


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

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description
m int To store rows
n int To store columns
i int For Loop
j int For Loop
k int For Loop
a int To store array

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 16

2023-23| SANCHITA SRIVASTAVA


P a g e | 17

PROGRAM 3
The names of the teams participating in a competition should be displayed on a
banner vertically, to accommodate as many teams as possible in a single banner.
Design a program to accept the names of N teams, where 2 < N < 9 and display
them in vertical order, side by side with a horizontal tab (i.e. eight spaces).
Test your program for the following data and some random data:
Example 1
INPUT:
N=3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote
OUTPUT:
E R
Cm o
ou a
ys d
o
t R
e o
l
s

2023-23| SANCHITA SRIVASTAVA


P a g e | 18

Example 2
INPUT:
N=4
Team 1: Royal
Team 2: Mars
Team 3: De Rose
Team 4: Kings
OUTPUT:
R M D
Ko a e
iy r
na s R
gl o
s s
e
Example 3
INPU
T: N =
10
OUTPUT:
INVALID INPUT

ALGORITHM:
• Initialize a number N to store number of names.

2023-23| SANCHITA SRIVASTAVA


P a g e | 19

• Initialize array.
• If the entered number is less than 2 and more than 9 then print ‘Invalid
Input’.

• Enter the names in array using ‘for’ loop.


• Declare another variable to find the length of the longest string.

• Now run the loop to extract the character.


• Print each character and the tabular space accordingly in vertical form.

• Close the program.

SOURCE CODE:

2023-23| SANCHITA SRIVASTAVA


P a g e | 20

import java.util.*;
public class Banner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
in.nextLine();
if (n <= 2 || n >= 9)
{
System.out.println("INVALID INPUT");
return;
}
String teams[] = new String[n];
int highLen = 0;
for (int i = 0; i < n; i++)
{
System.out.print("Team " + (i+1) + ": ");
teams[i] = in.nextLine();
if (teams[i].length() > highLen)
{
highLen = teams[i].length();
}
}
for (int i = 0; i < highLen; i++)
{
for (int j = 0; j < n; j++)
{
int len = teams[j].length();
if (i >= len)
{
P a g e | 21

System.out.print(" \t");
}
else
{
System.out.print(teams[j].charAt(i) + "\t");
}
}
System.out.println();
}
}
}

VARIABLE DESCRIPTION TABLE:

2023-23| SANCHITA SRIVASTAVA


P a g e | 22

Variable Data Type Description


teams[] string To input names
n int To input number of names
i int For loop
j int For loop
highLen int To find the length of longest
string
len int To find length of name of
each team
OUTPUT:

PROGRAM 4

2023-23| SANCHITA SRIVASTAVA


P a g e | 23

Design a class Perfect to check if a given number is a perfect number or not. [ A


number is said to be perfect if sum of the factors of the number excluding itself
is equal to the original number].

Example : 6 = 1 + 2 + 3 (where 1, 2 and 3 are factors of 6, excluding itself).

Some of the members of the class are given below:

Class name : Perfect

Data members/instance variables: num : to store the number

Methods/Member functions:
Perfect (int nn) : parameterized constructor to initialize the data member
num=nn.
int sum_of_factors(int i) : returns the sum of the factors of the number(num),
excluding itself, using recursive technique.
void check( ) : checks whether the given number is perfect by invoking the
function sum_of_factors( ) and displays the result with an appropriate message.
Specify the class Perfect giving details of the constructor( ), int
sum_of_factors(int) and void check( ). Define a main( ) function to create an
object and call the functions accordingly to enable the task.

ALGORITHM:
• Step 1 – Start, Initialize the instance variable.
• Step 2 – Make a default constructor.
• Step 3 – Make the function to return the sum of the factors of the number.

2023-23| SANCHITA SRIVASTAVA


P a g e | 24

• Step 4 – Make the function to check whether the given number is perfect by
invoking the previous function.
• Step 5 – Make the main function.
• Step 6 – Input a number and Check whether it is a Perfect number or Not.

• Step 7 - End.

SOURCE CODE:
import java.util.*;
class Perfect
{
int num;
Perfect(int nn)
{
num=nn;
}
int sum_of_factors(int i)
{
if (i == num)
return 0; else if (num%i==0)
return i + sum_of_factors(i+1); else
return sum_of_factors(i+1);
}
void check()
{
int s=sum_of_factors(1);
if (s==num)

2023-23| SANCHITA SRIVASTAVA


P a g e | 25

System.out.println(num+"is a perfect number"); else


System.out.println(num+"is not a perfect number");
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number"); int
no=sc.nextInt();
Perfect ob=new Perfect(no);
ob.check();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description
num int Instance variable
nn int Local variable for constructor

i int For loop


n int To store number
s int To store sum
OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 26

PROGRAM 5
Two matrices are said to be equal if they have the same dimension and their
corresponding elements are equal.
Design a class EqMat to check if two matrices are equal or
not. Assume that the two matrices have the same
dimension.

Class name : EqMat


Data members/instance variables:

2023-23| SANCHITA SRIVASTAVA


P a g e | 27

a[ ][ ] : to store integer
elements m : to store the
number of rows
n : to store the number of columns

Member functions/methods:

EqMat(int mm, int nn) : parameterised constructor to initialise the data


members m = mm and n = nn
void readarray( ) : to enter elements in the array
int check(EqMat P, EqMat Q) : checks if the parameterized objects P and Q are
equal and returns
1 if true, otherwise returns 0
void print( ) : displays the array elements

Define the class EqMat giving details of the constructor( ), void readarray( ), int
check(EqMat, EqMat) and void print( ). Define the main( ) function to create
objects and call the functions accordingly to enable the task.

ALGORITHM:
• Step 1 – Make the parameterized constructor.

• Step 2 – Make the function „readarray‟ to input the elements in the array.

• Step 3 – Make the function „check‟ to check if the parameterized elements


are equal.
• Step 4 – Make the function „print‟ to print the matrix.

2023-23| SANCHITA SRIVASTAVA


P a g e | 28

• Step 5 – Make the main function.


• Step 6 – Input the number of rows and columns.
• Step 7 – Check the numbers using functions.

SOURCE CODE:
import java.util.*;
class EqMat
{ int a[]
[]; int m;
int n;
static Scanner sc=new Scanner(System.in);
EqMat(int mm,int nn)
{
m=mm;
n=nn;
a=new int[m][n];
}
void readarray()
{
System.out.println("Enter " + (m*n) + " elements" );
for (int i=0;i<m;i++) for (int j=0;j<n;j++)
a[i][j]=sc.nextInt();
}
int check(EqMat P,EqMat Q)
{
for (int i=0;i<P.m;i++)

2023-23| SANCHITA SRIVASTAVA


P a g e | 29

for (int j=0;j<P.n;j++)


{
if (P.a[i][j]!=Q.a[i][j])
return 0;
}
return 1;
}
void print()
{
for (int i=0;i<m;i++)
{
System.out.println();
for (int j=0;j<n;j++)
System.out.print(a[i][j]+"\t");
}
}
public static void main(String args[])
{
EqMat ob1=new EqMat(3,3);
EqMat ob2=new EqMat(3,3);
System.out.println("Enter nos for the Ist Matrix");
ob1.readarray();
System.out.println("Enter nos for the 2nd Matrix");
ob2.readarray();
if (ob1.check(ob1,ob2)==1)
{
System.out.println("Equal Matrix");
ob1.print(); ob2.print();

2023-23| SANCHITA SRIVASTAVA


P a g e | 30

OUTPUT :

}
else

System.out.println("No
t Equal");
}
}

VARIABLE
DESCRIPTION TABLE:

PROGRAM 6
A class Capital has been defined to check whether a sentence has words
beginning with a capital letter or not.
Some of the members of the class are given below:
Class name : Capital
Data member/instance variable:
sent : to store a sentence freq : stores the frequency of
words beginning with a capital letter Member
functions/methods:

2023-23| SANCHITA SRIVASTAVA


P a g e | 31

Capital( ) : default
constructor void input() : to
accept the sentence
boolean isCap(String w) : checks and returns true if word begins with a capital
letter, otherwise returns false void display () : displays the sentence along with
the frequency of the words beginning with a capital letter.
Specify the class Capital, giving the details of the constructor( ), void input( ),
boolean isCap(String) and void display( ). Define the main( ) function to create
an object and call the functions accordingly to enable the task

ALGORITHM:
• Step 1 – Start; Make the default constructor.
• Step 2 – Make a function input to input the values from user.

• Step 3 – Make a function „isCap‟ to check and returns true if word begins
with a capital letter, otherwise returns false.

• Step 4 – Make a function display to display the output

• Step 5 – Apply all the functions in the main function. End

SOURCE CODE:
import java.util.*;
class Capital
{
String sent;
int freq;
Capital()

2023-23| SANCHITA SRIVASTAVA


P a g e | 32

{
sent="";
freq=0;
}
void input()
{
Scanner sc=new Scanner(System.in); System.out.println("Enter
the sentence");
sent=sc.nextLine();
}
boolean isCap(String w)
{
char c=w.charAt(0); if
(Character.isUpperCase(c) )
return true;
else
return false;
}
void display()
{
System.out.println("sentence="+sent);
StringTokenizer ob=new StringTokenizer(sent); int
count=ob.countTokens();
for (int i=0;i<count;i++)
{
String wd=ob.nextToken();
if (isCap(wd))
freq=freq+1;

2023-23| SANCHITA SRIVASTAVA


P a g e | 33

}
System.out.println("Frequency of title word="+freq);
}
public static void main(String args[])
{
Capital ob=new Capital();
ob.input();
ob.display();
}
}

VARIABLE DESCRIPTION TABLE:

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 34

PROGRAM 7
Design a program to accept a day number (between 1 and 366), year (in 4
digits) from the user to generate and display the corresponding date. Also,
accept 'N' (1 <= N <= 100) from the user to compute and display the future date
corresponding to 'N' days after the generated date. Display an error message if
the value of the day number, year and N are not within the limit or not
according to the condition specified.
Test your program with the following data and some random data:
Example 1
INPUT:
DAY NUMBER: 255

2023-23| SANCHITA SRIVASTAVA


P a g e | 35

YEAR: 2018
DATE AFTER (N DAYS): 22
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018
Example 2
INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45
OUTPUT:
DATE: 26TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019
Example 3
INPUT:
DAY NUMBER: 500
YEAR: 2018
DATE AFTER (N DAYS): 33
OUTPUT:
DAY NUMBER OUT OF RANGE
Example 4
INPUT:
DAY NUMBER: 150

2023-23| SANCHITA SRIVASTAVA


P a g e | 36

YEAR: 2018
DATE AFTER (N DAYS): 330
OUTPUT:
DATE AFTER (N DAYS) OUT OF RANGE

ALGORITHM:
• Step 1 –The Program enter the Day number and Year.
• Step 2 –The dateofmonth() function checks the month and checks for leap
year.

• Step 3– The main functions runs datetomonth() function and print the date
and month after n days.

SOURCE CODE:
import java.util.Scanner;

public class DateCalculator


{
public static boolean isLeapYear(int y)
{
boolean ret = false;

if (y % 400 == 0) {
ret = true;
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 37

else if (y % 100 == 0)
{

2023-23| SANCHITA SRIVASTAVA


P a g e | 39

P a g e | 31

ret = false;
}
else if (y % 4 == 0)
{
ret = true;
}
else
{
ret = false;
}

return ret;
}

public static String computeDate(int day, int year)


{
int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String monthNames[] = {"JANUARY", "FEBRUARY", "MARCH",
"APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER",

2023-23| SANCHITA SRIVASTAVA


if (leap)
{ monthDays[1] = 29;
}

int i = 0; int
daySum = 0;
for (i = 0; i < monthDays.length; i++)
{
daySum += monthDays[i];
if (daySum >= day)
{
break;
}
}
2023-23| SANCHITA SRIVASTAVA
P a g e | 41

P a g e | 32

int date = day + monthDays[i] - daySum;

StringBuffer sb = new StringBuffer();


sb.append(date); sb.append("TH ");
sb.append(monthNames[i]);
sb.append(", ");
sb.append(year);

return sb.toString();
}

public static void main(String args[])


{
Scanner in = new Scanner(System.in); System.out.print("DAY
NUMBER: ");
int dayNum = in.nextInt(); System.out.print("YEAR:
");
int year = in.nextInt();
System.out.print("DATE AFTER (N DAYS): ");

2023-23| SANCHITA SRIVASTAVA


}

if (n < 1 || n > 100) {


System.out.println("DATE AFTER (N DAYS) OUT OF RANGE");
return;
}

String dateStr = computeDate(dayNum, year);

int nDays = dayNum + n;


int nYear = year;
boolean leap = isLeapYear(year);
2023-23| SANCHITA SRIVASTAVA
P a g e | 43

if (leap && nDays > 366) {

nYear = nYear + 1;
nDays = nDays - 366;
}
else if (nDays > 365)
{
nYear = nYear + 1;
nDays = nDays - 365;
}

String nDateStr = computeDate(nDays, nYear);

System.out.println();
System.out.println("DATE: " + dateStr);
System.out.println("DATE AFTER " + n
+ " DAYS: " + nDateStr);
}
}
VARIABLE DESCRIPTION TABLE:

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 44

2023-23| SANCHITA SRIVASTAVA


P a g e | 45

Program 8:
Write a program to declare a single-dimensional array a[] and a square matrix
b[][] of size N, where N > 2 and N < 10. Allow the user to input positive
integers into the single dimensional array.
Perform the following tasks on the matrix:

1. Sort the elements of the single-dimensional array in ascending order


using any standard sorting technique and display the sorted elements.
2. Fill the square matrix b[][] in the following format:
If the array a[] = {5, 2, 8, 1} then, after sorting a[] =
{1, 2, 5, 8} Then, the matrix b[][] would fill as below:

1258
1251
1212
1125

3. Display the filled matrix in the above format.

Test your program for the following data and some random data:
Example 1
INPUT:
N=3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT:

2023-23| SANCHITA SRIVASTAVA


137

131

113

ALGORITHM:
• Step 1- Entering the matrix and array.
P a g e | 47

P a g e | 36

• Step 2- Sorting the array.


• Step 3- Running loop to change the matrix.

SOURCE CODE:
import java.util.Scanner;

public class Array


{
public static void sortArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++)
{ for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}

2023-23| SANCHITA SRIVASTAVA


System.out.print("ENTER VALUE OF N: "); int n
= in.nextInt();

if (n <= 2 || n >= 10) {


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

int a[] = new int[n];


int b[][] = new int[n][n];

2023-23| SANCHITA SRIVASTAVA


P a g e | 37

System.out.println("ENTER ELEMENTS OF SINGLE


DIMENSIONAL ARRAY:");
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}

sortArray(a);
System.out.println("SORTED ARRAY:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}

for (int i = n - 1, r = 0; i >= 0; i--, r++)


{ for (int j = 0; j <= i; j++) {
b[r][j] = a[j];
}

for (int k = n - 1; k > i; k--)


{ b[r][k] = a[k - i - 1];
}
}

System.out.println();
System.out.println("FILLED MATRIX:");
for (int i = 0; i < n; i++) { for (int j = 0; j <
n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
}
}

VARIABLE DESCRIPTION TABLE:


P a g e | 39

Program 9
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’
or ‘!’ only. The words are to be separated by a single blank space and are in
uppercase.
Perform the following tasks:
(a) Check for the validity of the accepted sentence.
(b) Convert the non-palindrome words of the sentence into palindrome
words by concatenating the word by its reverse (excluding the last
character).
Example:
The reverse of the word HELP would be LEH (omitting the last alphabet) and by
concatenating both, the new palindrome word is HELPLEH. Thus, the word
HELP becomes HELPLEH.
Note: The words which end with repeated alphabets, for example ABB would
become ABBA and not ABBBA and XAZZZ becomes XAZZZAX.
[Palindrome word: Spells same from either side. Example:
DAD, MADAM etc.] (c) Display the original sentence along
with the converted sentence. Test your program for the
following data and some random data: Example 1 INPUT:
THE BIRD IS
FLYING. OUTPUT:
THE BIRD IS FLYING.
THEHT BIRDRIB ISI FLYINGNIYLF

ALGORITHM:
• Step 1 – Entering the sentence and converting in UPPERCASE
• Step 2 – Checking whether the sentence terminates with ‘.’ , ‘?’ ,’!’
• Step 3 – Running loop to get palindrome of each word.
• Step 4 – Concatenating each word of the sentence

SOURCE CODE:
P a g e | 40

public class Palindrome


{

public static boolean isPalindrome(String word) { boolean


palin = true;

int len = word.length(); for (int i = 0; i <= len / 2;


i++) { if (word.charAt(i) != word.charAt(len - 1 - i))
{ palin = false; break;
}
}

return palin;
}

public static String makePalindrome(String word)


{ int len = word.length(); char lastChar =
word.charAt(len - 1); int i = len - 1; while
(word.charAt(i) == lastChar) { i--;
}

StringBuffer sb = new StringBuffer(word);


for (int j = i; j >= 0; j--)
{ sb.append(word.charAt(j));
}

return sb.toString();
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.println("ENTER THE SENTENCE:");
String ipStr = in.nextLine().trim().toUpperCase(); int len =
P a g e | 41

char lastChar = ipStr.charAt(len - 1);


if (lastChar != '.' && lastChar != '?'
&& lastChar != '!') {
System.out.println("INVALID INPUT");
return;
}

String str = ipStr.substring(0, len - 1);

StringTokenizer st = new StringTokenizer(str);


StringBuffer sb = new StringBuffer();

while (st.hasMoreTokens())
{ String word = st.nextToken();
boolean isPalinWord = isPalindrome(word);
if (isPalinWord) {
sb.append(word);
}
else {
String palinWord = makePalindrome(word);
sb.append(palinWord);
}
sb.append(" ");
}

String convertedStr = sb.toString().trim();

System.out.println();
System.out.println(ipStr);
System.out.println(convertedStr);
}
}
2023-23| SANCHITA SRIVASTAVA
P a g e | 59

VARIABLE DESCRIPTION
TABLE:

OUTPUT :

2023-23| SANCHITA SRIVASTAVA


P a g e | 60

PROGRAM 10
Design a class ArmNum to check if a given number is an Armstrong number or
not. [A number is
said to be Armstrong if sum of its digits raised to the power of length of the
number is equal to
the number]
Example : 371 = 33 + 73 + 13
1634 = 14 + 64 + 34 + 44
54748 = 55 + 45 + 75 + 45 + 85
Thus 371, 1634 and 54748 are all examples of Armstrong numbers.
Some of the members of the class are given below:
Class name : ArmNum
Data members/instance variables:
n : to store the
number
l: to store the length of the number
Methods/Member functions:
ArmNum (int nn) : parameterized constructor to initialize the data member
n=nn Int sum_pow(int i) : returns the sum of
each digit raised to the power of the length of the number
using recursive technique eg. 34 will return 32 + 42 (as the length of the
number is 2) void isArmstrong( ) : checks whether
the given number is an Armstrong number by invoking the
function sum_pow( ) and displays the result with an appropriate message
Specify the class ArmNum giving details of the constructor( ), int
sum_pow(int) and void isArmstrong( ). Define a main( ) function to create an
object and call the functions accordingly to enable the task.
P a g e | 61

ALGORITHM:
• Step 1 – Start Make the parameterized constructor.

• Step 2 – Make the function „sum_pow‟ to find the sum of each digit raised
to the power of the length of the number using recursive technique.

• Step 3 – Make the function „isArmstrong‟ to check whether the given


number is an Armstrong number by invoking the function sum_pow() and
displays the result with an appropriate message.

• Step 4 – Make the main function and the call all the functions to find the
Armstrong number. End.

SOURCE CODE:
import java.util.Scanner;
public class ArmNum
{
int n,l;
ArmNum(int nn)
{
n=nn;
l=Integer.toString(n).length();
}
int sum_pow(int i)

2023-23| SANCHITA SRIVASTAVA


P a g e | 62

{
if(i==0)
{
return 0;
}
else
{
return (int)Math.pow(i%10,l) + sum_pow(i/10);
}
}
void isArmstrong()
{
if(sum_pow(n)==n)
{
System.out.println(n + " is an Armstrong number");
}
else
{
System.out.println(n + "is not an Armstrong number");
}
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int num=sc.nextInt();
ArmNum ob1=new ArmNum(num);
ob1.isArmstrong();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description
n int To store the number.

l int To store the length of


the number.

nn int To initialize the


variable n.

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


PROGRAM 11
Design a class MatRev to reverse each element of a matrix.
Some of the members of the class are given below:
Class name : MatRev
Data members/instance
variables: arr[ ][ ] : to store
integer elements m : to
store the number of rows
n : to store the number of
columns Member
functions/methods:
MatRev(int mm, int nn) : parameterised constructor to initialise the data
members m = mm and n = nn void fillarray( ) : to enter elements in the array
int reverse( int x ) : returns the reverse of the number x void revMat( MatRev
P ) : reverses each element of the array of the parameterized object and stores
it in the array of the current object.
void show( ) : displays the array elements in matrix form
Define the class MatRev giving details of the constructor( ), void fillarray( ),
int reverse(int), void revMat(MatRev) and void show( ). Define the main( )
function to create objects and call the functions accordingly to enable the
task.

2023-23| SANCHITA SRIVASTAVA


P a g e | 65

ALGORITHM:

• Step 1 – Start, Initialize the instance variables.


• Step 2 – Make the parameterized constructor.

• Step 3 – Make the function „void fillarray‟ to enter elements in the array.

• Step 4 – Make the parameterized function „reverse‟ that returns the


reverse of the number.
• Step 5 – Make the function „revMat‟ which reverses each element of the
array of the parameterized object and stores it in the array of the current
object.

• Step 6 –Make the function „show‟ to display the array elements in matrix
form.

• Step 7 – Make the main function and all the functions. End

SOURCE CODE:
import java.util.*;
class MatRev {
int arr[][], m, n; static Scanner x = new
Scanner(System.in);

2023-23| SANCHITA SRIVASTAVA


MatRev(int nn, int mm) {
m = mm;
n = nn;
arr = new int[m][n];
}

void fillarray() {
System.out.println("Enter the elements");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
arr[i][j] = x.nextInt();
}

int reverse(int x) {
int s = 0, c = 0;
while (x != 0)
{ c = x % 10;
s = s * 10 + c; x
= x / 10;

2023-23| SANCHITA SRIVASTAVA


P a g e | 67

}
return s;
}

void revMat(MatRev P) { for (int i


= 0; i < m; i++) for (int j = 0; j < n;
j++) arr[i][j] = reverse(P.arr[i]
[j]);
}

void show() { for (int i =


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

public static void main(String args[])


{ MatRev obj = new MatRev(3, 3);
MatRev obj1 = new MatRev(3, 3);
obj.fillarray();
System.out.print("\n Original Array");
obj.show();
obj1.revMat(obj);
System.out.print("\n Reverse array");
obj1.show();

2023-23| SANCHITA SRIVASTAVA


P a g e | 68

}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description
arr int To store the
matrix.
m int For the rows of the
matrix.

n int For the columns of


the matrix.

mm int For the deafault


value of the rows.

nn int For the default


value of the
columns.

i int For the loop.

j int For the loop.

x int For the local


variable and For
the value of rows.

2023-23| SANCHITA SRIVASTAVA


P a g e | 69

rev int For the reverse of


the number.

Matrev int For the reverse of


the matrix.

y int For the value of


the columns.

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 70

PROGRAM 12
A class Rearrange has been defined to modify a word by bringing all the vowels
in the word at the beginning followed by the consonants.
Example: ORIGINAL becomes OIIARGNL Some of the members of the class are
given below:
Class name : Rearrange
Data member/instance
variable:
wrd : to store a word
newwrd : to store the rearranged word
Member functions/methods:
Rearrange( ) : default constructor.
void readword( ) : to accept the word in UPPER case.

2023-23| SANCHITA SRIVASTAVA


P a g e | 71

void freq_vow_con( ) : finds the frequency of vowels and consonants in the word
and displays them with an appropriate message.
void arrange( ) : rearranges the word by bringing the vowels at the
beginning followed by consonants. void display( ) : displays the original
word along with the rearranged word.
Specify the class Rearrange, giving the details of the constructor( ), void
readword( ), void freq_vow_con( ), void arrange( ) and void display( ). Define
the main( ) function to create an object and call the functions accordingly to
enable the task.

ALGORITHM:
Step 1 – Start; Initialize the instance variables. Step 2 – Make the default
constructor.
Step 3 – Make the function „readword‟ to accept the word in UPPER case.
Step 4 – Make the function „freq_vow_con‟ to find the frequency of vowels and
consonants in the word and displays them with an appropriate message.
Step 5 – Make the function „arrange‟ to rearrange the word by bringing the
vowels at the beginning followed by consonants.
Step 6 – Make the function „display‟ to display the original word along with the
rearranged word.
Step 7 – Make the main function and call all the functions. End.

SOURCE CODE:
import java.util.*;
class Rearrange

2023-23| SANCHITA SRIVASTAVA


P a g e | 72

{
String wrd,newwrd;
static Scanner x=new Scanner(System.in);
Rearrange()
{
}
void readword()
{
System.out.println("Enter a word" );
wrd=x.next();
wrd=wrd.toUpperCase();
}
void freq_vow_con()
{
int s=0,s1=0; char ch;
for(int i=0;i<wrd.length();i++)
{
ch=wrd.charAt(i); if("AEIOU".indexOf(ch)!
=-1)
s++;
}
s1= wrd.length()-s;
System.out.println("vowels = "+ s);
System.out.println("consonants = " + s1);
}
void arrange()
{
char ch;

2023-23| SANCHITA SRIVASTAVA


P a g e | 73

String p="",q="";
for(int i=0;i<wrd.length();i++)
{
ch=wrd.charAt(i);
if("AEIOU".indexOf(ch)!=-1)
p +=ch; else
q +=ch;
}
newwrd= p+q;
}
void display()
{
System.out.println("Original word = "+ wrd);
System.out.println("Rearranged word = "+ newwrd);
}
public static void main(String args[])
{
Rearrange obj=new Rearrange();
obj.readword();
obj.freq_vow_con(); obj.arrange();
obj.display();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Datatype Description

wrd String To store a word.

2023-23| SANCHITA SRIVASTAVA


P a g e | 74

newwrd String To store the


rearranged word.

VF int To store the frequency


of the vowels.

CF int to store the frequency


of the consonants.

ch char To separate the


character.

i int For the loop.

vowel String To store the vowels.

consonants String To store the


consonants.

OUTPUT:

PROGRAM 13

2023-23| SANCHITA SRIVASTAVA


P a g e | 75

A Prime-Adam integer is a positive integer (without leading zeros) which is a


prime as well as an Adam number.
Prime number: A number which has only two factors, i.e. 1 and the number itself.
Example: 2, 3, 5, 7 ... etc.
Adam number: The square of a number and the square of its reverse are reverse to
each other. Example: If n = 13 and reverse of 'n' = 31, then,
(13)2 = 169
(31)2 = 961 which is reverse of
169 thus 13, is an Adam
number.
Accept two positive integers m and n, where m is less than n as user input.
Display all PrimeAdam integers that are in the range between m and n (both
inclusive) and output them along with the frequency, in the format given below:
Test your program with the following data and some
random data: Example 1 INPUT: m = 5 n = 100
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
11 13 31
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3

ALGORITHM:
• Step 1 – Entering the range.
• Step 2 – Getting the reverse of prime number and squaring both.
• Step 3 – Checking if both the squares are reverse of each other.

SOURCE CODE:
import java.util.*;

2023-23| SANCHITA SRIVASTAVA


P a g e | 76

class Prime_Adam
{
public static void main(String[] args)
{
//PRIME ADAM NUMBER
Scanner sc = new Scanner(System.in);
System.out.print("m : ");
int m=sc.nextInt();
System.out.print("n : ");
int n=sc.nextInt();
System.out.println ("THE PRIME-ADAM INTEGERS ARE :");
int c=0;
if(m>n)
{
System.out.println ("INVALID INPUT");
} else { for (int i =
m; i <= n; i++) { if
(prime(i))
//prime number condition
{
if ((i * i) == reverse(reverse(i) * reverse(i)))
//Adam number condition
{
System.out.print(i + " ");
c++;
}
}
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 77

}
if(c==0)
{
System.out.println ("\nNIL");
System.out.println ("\nFREQUENCY OF PRIME-ADAM
INTEGERS IS : "+c);
}
}
//prime function return boolean
static boolean prime(int n)
{
int c=0; for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)return true;
return false;
}
//reverse function returns integer
public static int reverse(int n)
{
int rev=0; while(n!=0)
{
int d=n%10; rev=rev*10+d; n=n/10;
}
return rev;
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 78

VARIABLE DESCRIPTION TABLE:

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 79

2023-23| SANCHITA SRIVASTAVA


P a g e | 59

PROGRAM 14
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 the value of 'M'
must be greater than 0 and less than 10 and the value of 'N' must be greater
than 2 and less than 6. Allow the user to input digits (0 - 7) only at each
location, such that each row represents an octal number.

Perform the following tasks on the matrix:

1. Display the original matrix.


2. Calculate the decimal equivalent for each row and display as per the
format given below.

Test your program for the following data and some random data
Example 1:
INPUT:
M =1
N= 3
ENTER ELEMENTS FOR ROW 1: 1 4 4
OUTPUT:
FILLED MATRIX DECIMAL EQUIVALENT

1 4 4 100

2023-23| SANCHITA SRIVASTAVA


Example 2:
IN
PU
T:
M
=3
N=4
ENTER ELEMENTS FOR ROW 1: 1 1 3 7
ENTER ELEMENTS FOR ROW 2: 2 1 0 6
ENTER ELEMENTS FOR ROW 3: 0 2 4 5

2023-23| SANCHITA SRIVASTAVA


2023-23| SANCHITA SRIVASTAVA
P a g e | 61

return;
}

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

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


System.out.println("ENTER ELEMENTS FOR ROW " + (i + 1) +
": "); for (int j = 0; j < n; j+
+) { a[i][j] = in.nextInt();
if (a[i][j] < 0 || a[i][j] > 7) {
System.out.println("INVALID INPUT");
return;
}
}
}

System.out.println("FILLED MATRIX\tDECIMAL EQUIVALENT");

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


int decNum = 0;
for (int j = 0; j < n; j++) { decNum +=
a[i][j] * Math.pow(8, n - j - 1 );
System.out.print(a[i][j] + " ");
}

2023-23| SANCHITA SRIVASTAVA


VARIABLE DESCRIPTION TABLE:

2023-23| SANCHITA SRIVASTAVA

OUTPUT:
2023-23| SANCHITA SRIVASTAVA
PROGRAM 15
Write a program to accept a sentence which may be terminated by either '.', '?' or '!'
only. The words are to be separated by a single blank space and are in UPPER CASE.
Perform the following tasks:

1. Check for the validity of the accepted sentence only for the terminating
character.
2. Arrange the words in ascending order of their length. If two or more words have
the same length, then sort them alphabetically.
3. Display the original sentence along with the converted sentence.

Test your program for the following data and some random data:
Example 1:
INPUT:
AS YOU SOW SO SHALL YOU REAP.
OUTPUT:
AS YOU SOW SO SHALL YOU REAP. AS SO SOW YOU YOU REAP SHALL

ALGORITHM:
• Step 1 – Entering the sentence in UPPERCASE.
• Step 2 – Checking validity of sentence
• Step 3 – Arranging words in ascending order.

SOURCE CODE:
import java.util.*;
public class StringCheck
{
public static String sortString(String ipStr)
{
St
ri
ng

2023-23| SANCHITA SRIVASTAVA


Tokenizer st = new StringTokenizer(ipStr); int
wordCount = st.countTokens(); String
strArr[] = new String[wordCount];
for (int i = 0; i < wordCount; i++)
{
strArr[i] = st.nextToken(); }
for (int i = 0; i < wordCount - 1; i++)
{ for
(int j = 0; j < wordCount - i - 1; j++)
{
if (strArr[j].length() > strArr[j + 1].length())
{ Stri
ng t = strArr[j]; strArr[j]
= strArr[j+1]; strArr[j+1] = t;
}
if (strArr[j].length() == strArr[j +
1].length()&&(strArr[j].compareTo(strArr[j+1]) > 0))
{ Stri
ng t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
}
}
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < wordCount; i++)
{
sb.append(strArr[i]); sb.append("
"); }
return sb.toString().trim();
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
int len = str.length();
System.out.println();
if (str.charAt(len - 1) != '.' && str.charAt(len - 1) != '?'&& str.charAt(len
- 1) != '!')
{
System.out.println("INVALID INPUT");
return;
}
String sortedStr = sortString(str.substring(0, len - 1));
System.out.println(str);
System.out.println(sortedStr);
}
}

VARIABLE DESCRIPTION TABLE:

OUTPUT :

2023-23| SANCHITA SRIVASTAVA


PROGRAM 16:
Design a class Convert to find the date and the month from a given day
number for a particular year.
Example: If day number is 64 and the year is 2020, then the corresponding
date would be: March 4, 2020 i.e. (31 + 29 + 4 = 64)
Classname : Convert
Data members/instance variables: n :
integer to store the day number d :
integer to store the day of the month
(date) m : integer to store the month
y : integer to store the year
Methods/Member functions:
Convert ( ) : constructor to initialize the data members with legal
initial values. void accept( ) : to accept the day number and the year
void day_to_date( ) : converts the day number to its corresponding date for a
particular year and stores the date in ‘d’.
void display( ) : displays the month name, date and year

Specify the class Convert giving details of the constructor( ),void accept( ),
void day_to_date( ) and voiddisplay( ). Define a main( ) function to create an
object and call the functions accordingly.

ALGORITHM:
• Step 1 – Start, Initialize the instance variables.
• Step 2 – Make the default constructor.
• Step 3 – Make the function “accept” to accept the day number and the
year.

2023-23| SANCHITA SRIVASTAVA


• Step 4 – Make the function “day_to_date” to convert the day number to its
corresponding date for a particular year and stores the date in “d” and the
month in “m”.
• Step 5 – Make the function “display” to display the month name, date and
year.
• Step 6 – Make the main function and call the functions to enable the task.
End.

SOURCE CODE:
import java.util.*;
class Convert
{
int n,d,m,y;
Convert( )
{
n=0;
y=0;
}
void accept()
{
Scanner x=new Scanner(System.in);
System.out.println(("Enter day number and year"));
n=x.nextInt() ;
y=x.nextInt() ;
}
void day_to_date()
{
int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(y%4==0)
a[2]=29;
int s=0, c=0;
while(s<n)
s=s+a[c++];
s=s-a[--c];
d=n-s;
m=c;
}
void display()
{
String x[]={"","JANUARY","FEBRUARY","MARCH","APRIL","MAY",
"JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","
DECEMBER"};
System.out.print("\n Day Number: " + n);
System.out.print("\n Date: " );
System.out.print(x[m]+" " +d + "," + y);
}
public static void main(String args[])
{
Convert obj =new Convert();
obj.accept( ) ;
obj.day_to_date();
obj.display();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description

n int To store the day


number.

d int To store the day of the


month (date).

m int To store the month.

2023-23| SANCHITA SRIVASTAVA


y int To store the year.

month String To store the names of


months.
P a g e | 96

day int To store days of


months.

OUTPUT:

PROGRAM 17
Design a class BinSearch to search for a particular value in an array.

2023-23| SANCHITA SRIVASTAVA


P a g e | 97

Some of the members of the class are given below:


Classname : BinSearch Data
Members/instance variables:
arr[ ] : to store integer elements
n : integer to store the size of
the array Member
functions/methods:
BinSearch(int nn ) : parameterized constructor to initialize n=nn. void
fillarray( ) : to enter elements in the array. void sort( ) : sorts the array
elements in ascending order using any standard sorting technique. int
bin_search(int l,int u,int v) : searches for the value ‘v’ using binary search and
recursive technique and returns its location if found otherwise returns -1.
Define the class BinSearch giving details of the constructor( ), void fillarray( ),
void sort( ) and int bin_search(int,int,int).
Define the main( ) function to create an object and call the functions accordingly
to enable the task.

ALGORITHM:
• Step 1 – Start, Initialize the instance variable.
• Step 2 – Make the parameterized constructor.

• Step 3 – Make the function “fillarray” to enter elements in the array.

• Step 4 – Make the function “sort” to sort the array elements in ascending
order using any standard sorting technique.

2023-23| SANCHITA SRIVASTAVA


P a g e | 98

• Step 5 – Make the function “bin_search” to search for the value “v” using
binary search and
recursive technique and returns its location if found otherwise returns
-1.

• Step 6 – Make the main function main function.


• Step 7 – Input the array dimension.

SOURCE CODE:
import java.util.*;
class BinSearch
{ int
arr[];
int n;
static Scanner x=new Scanner(System.in);
BinSearch(int nn)
{
n=nn;
}
void fillarray()
{
arr=new int[n];
System.out.println("Enter "+n + " elements");
for(int i =0;i<n;i++) arr[i]=x.nextInt();
}
void sort()

2023-23| SANCHITA SRIVASTAVA


P a g e | 99

{
int t;
for(int i=0;i<n-1;i++)
for(int j =0;j<n-1-i;j++)
{
if (arr[j]>arr[j+1])
{
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
int bin_search(int l,int u, int v )
{
int m=(l+u)/2; if(arr[m]==v)
return m; else if(l>u)
return -1; else if (arr[m]>v)
return bin_search(l,m-1,v); else
return bin_search(m+1,u,v);
}
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);

System.out.println("Enter array dimension");


int ard=sc.nextInt();
BinSearch obj = new BinSearch(ard);

2023-23| SANCHITA SRIVASTAVA


P a g e | 100

obj.fillarray();
obj.sort();
System.out.println("Enter the number to be searched"); int
vvv=sc.nextInt();
System.out.println(" location: " + obj.bin_search(0,4,vvv) );
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description
To store integer
arr int elements.

To store the size of


n int the array.

Local variable for the


nn int constructor.

Temporary variable.
t int
i int For the loop.
j int For the loop.
Local variable for the
l int function.

2023-23| SANCHITA SRIVASTAVA


P a g e | 101

Local variable for the


u int function.

Local variable for the


v int function.

Local variable for the


p int position.

To store the
dim int dimension of the
array.
To store the search
searchNum int

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 102

2023-23| SANCHITA SRIVASTAVA


P a g e | 103

PROGRAM 18
A class Mix has been defined to mix two words, character by character, in the
following manner: The first character of the first word is followed by the first
character of the second word and so on.
If the words are of different length, the remaining characters of the longer word
are put at the end.
Example: If the First word is “JUMP” and the second word is “STROLL”, then
the required word will be “JSUTMRPOLL”.
Some of the members of the class are given below:
Classname : Mix
Data member/instance variable:
wrd : to store a word
len : to store the length of the word
Member functions/methods:
Mix( ) : default constructor to initialize the data members with legal
initial values. void feedword( ) : to accept the word in UPPER case.
void mix_word( Mix P, Mix Q ) : mixes the words of objects P and Q as stated
above and stores the resultant word in the current object. void display( ) :
displays the word

Specify the class Mix giving the details of the constructor( ), void feedword( ),
void mix_word( Mix, Mix ) and void display( ). Define the main( ) function to
create objects and call the functions.

ALGORITHM:

2023-23| SANCHITA SRIVASTAVA


P a g e | 104

• Step 1 – Start; Initialize the instance variables.


• Step 2 – Make the default constructor.
• Step 3 – Make the function “feedWord” to accept the word in UPPER
case.
• Step 4 – Make the function “mixWord” to mix the words of objects P and
Q as stated above and stores the resultant word in the current object.

• Step 5 – Make the function „display‟ to display the word.

• Step 6 – Make the main function to call the functions to enable the task.
End.

SOURCE CODE:
import java.util.*; class
Mix
{
String wrd;
int len;
static Scanner x=new Scanner(System.in);
Mix()
{
wrd="";
len=0;
}
void feedword()

2023-23| SANCHITA SRIVASTAVA


P a g e | 105

{
System.out.println( "Enter a word in UPPER CASE");
wrd=x.next(); len=wrd.length();
}
void mix_word(Mix P,Mix Q)
{
int s=(P.len <Q.len)? P.len:Q.len; for(int
i=0;i<s;i++) wrd += P.wrd.charAt(i)
+""+Q.wrd.charAt(i); if (P.len > Q.len)
wrd +=P.wrd.substring(Q.len); else
wrd +=Q.wrd.substring(P.len);
}
void display()
{
System.out.println("WORD = " + wrd);
}
public static void main(String args[])
{
Mix obj=new Mix();
Mix obj1=new Mix();
Mix obj2= new Mix();
obj.feedword();
obj1.feedword();
obj2.mix_word (obj,obj1);
obj2.display();
}

VARIABLE DESCRIPTION TABLE:

2023-23| SANCHITA SRIVASTAVA


P a g e | 106

Variable Data Type Description


To store a word
wrd String
To store the length
len int of the word.

i int For the loop.


j int For the loop.

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 107

PROGRAM 19
A Fascinating number is one which when multiplied by 2 and 3 and then , after
the results are concatenated with the original number , the new number contains
all the digits from 1 to 9 exactly once . There can be any number of zero’s and
are to ignored.
Accept Two positive integers m and n where must be less than n and the value of
both ‘m’ and ‘n’ must be grater than 99 and less than 10000 as user input.
Display all the fascinating numbers that are in range between m and n(both
inclusive) and output them along with the frequency.

ALGORITHM:
• Step 1- First, check the given number consist of three digits or not. If no,
print cannot be a fascinating number.
• Step 2- Else, multiply the given number by 2 and 3, separately.
• Step 3- Convert the results (from step 2) into a string.
• Step 4- Concatenate the strings (from step 3) with the given number (n).

2023-23| SANCHITA SRIVASTAVA


P a g e | 108

• Step 5- Iterate over the string that we get after concatenation and count the
frequency of each digit.
• Step 6- Print "not a fascinating number" if any digit is missing or appeared
multiple times. Else, print "fascinating number".

SOURCE CODE:
import java.util.*; public

class Fascinating

{
public static void main(String[] args)

//program to print fascinating numbers between a given range

Scanner sc = new Scanner(System.in);

System.out.print ("m = "); int

m=sc.nextInt(); System.out.print ("n = ");

int n=sc.nextInt();

System.out.println ("FACINATING NUMBERS BETWEEN "

+m+"AND "+n+ " ARE :"); if(m>n)

2023-23| SANCHITA SRIVASTAVA


P a g e | 109

//swapping the numbers if user give interupting inputs

int temp=m;

m=n; n=m;

int c=0; for(int

i=m;i<=n;i++)

// loop to get all the fascinating numbers between the range


{

if(fascinating(i))

System.out.print (i+" "); c++;

if(c==0)System.out.println ("NIL"); else

System.out.println ();

2023-23| SANCHITA SRIVASTAVA


P a g e | 110

System.out.println ("FREQUENCY OF THE FASCINATING NUMBERS IS


: " +c);

public static boolean fascinating(int n)

int m2 = n*2; int

m3 = n*3;

String s=Integer.toString(n)+Integer.toString(m2)+Integer.toString(m3);
int l = s.length(); long user = Long.parseLong(s); for(int i=1;i<10;i++)

int c=0;

long num=user;

for(int j=0;j<l;j++)

if(i==num%10) c++; num=num/10;

2023-23| SANCHITA SRIVASTAVA


P a g e | 111

if(c>1) return

false; else

if(c==0) return

false;

return true;

VARIABLE DESCRIPTION
TABLE:

2023-23| SANCHITA SRIVASTAVA


P a g e | 112

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 113

PROGRAM 20
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’
or ‘!’ only. The words are to be separated by a single blank space and are
UPPERCASE.

Perform the following tasks:


Check for the validity of the accepted paragraph for the terminating character.
Separate the two sentences from the paragraph and find the common words in
the two sentences with their frequency of occurrence in the paragraph.

Display both the sentences along with the common words and their frequency.

ALGORITHM:
• Step 1 – Entering the sentence and checking if it ends with ‘.’, ‘?’ or ‘!’.

• Step 2 – Finding common words in sentence.


• Step 3 – Getting the count of common words and displaying.

SOURCE CODE:

2023-23| SANCHITA SRIVASTAVA


P a g e | 114

import java.util.*;
class CommonWrd
{
public static void main(String args[])
{ String x=""; int
h=0,z=0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter para");
String n=sc.nextLine();
String a[]=new String[1000];
int l=n.length();
for(int i=0;i<l;i++)
{
char ch=n.charAt(i);
if(ch=='.'||ch=='?'||ch=='!')
{
z++;
}
}
if(z==2)
{
for(int i=0;i<l;i++)
{
char ch=n.charAt(i);
if(ch=='.'||ch=='?'||ch=='!')
{
String p=(n.substring(0,i+1));
String m=(n.substring(i+2,l)); n=p+m;

2023-23| SANCHITA SRIVASTAVA


P a g e | 115

System.out.println(n.substring(0,i+1));
System.out.println(n.substring(i+1)); break;
}
}
for(int i=0;i<l-1;i++)
{
char ch=n.charAt(i); if(ch!='.'&&ch!='?'&&ch!='!'&&ch!=' ')
{
x=x+ch;
}
else
{
a[h]=x; h+
+; x="";
}
}
System.out.println("COMMON WORDS FREQUENCY"); for(int
i=0;i<h;i++)
{
int c=1;
for(int j=i+1;j<h;j++)
{
if(a[i].equals(a[j]))
{
for(int k=j;k<h-1;k++)
a[k]=a[k+1];
h--;
c++;

2023-23| SANCHITA SRIVASTAVA


P a g e | 116

}
}
if(c>1)
System.out.println(a[i]+"\t\t"+c);
}
}
else
{
System.out.print("INVALID INPUT");
}
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description
To store the sentences
p String
To store no. of
c int
sentences
To store the sentences
S[ ] String seperately

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 117

PROGRAM 21

2023-23| SANCHITA SRIVASTAVA


P a g e | 118

Write a program to declare a single dimensional array A[] of order (M x N)


where ‘M’ is the number of rows and ‘N’ is the number of columns such that the
value of both ‘M’ and ‘N’ must be greater than 2 and less than 8 . Allow the user
to input integers into the matrix. Perform the following tasks on the matrix:

a) Sort the matrix elements in descending order using any standard sorting
technique

b) Calculate the sum of the boundary elements of the matrix before sorting and
after sorting.

c) Display the original matrix and the sorted matrix along with the sum of their
boundary elements respectively

ALGORITHM:
• Step 1 – Entering the size of matrix and its elements

• Step 2 – Getting boundary elements after sorting and before sorting and
adding them by loop

• Step 3 – Displaying original and sorted matrix with their sum of boundary
elements

SOURCE CODE:
import java.util.*;
class Sum_Of_Boundary
{

2023-23| SANCHITA SRIVASTAVA


P a g e | 119

static int mat[][]; public static void


main(String abc[])
{
//TAKE INPUT USING SCANNER METHOD
Scanner sc = new Scanner(System.in); int
m,n;
System.out.print("M : ");
m=sc.nextInt();
System.out.print("N : ");
n=sc.nextInt();
sumofboun(m,n);
}
public static void sumofboun(int r,int c)
//FUNCTION TO RETURN THE SUM OF BOUNDARY ELEMENTS
{
Scanner sc = new Scanner(System.in);
mat = new int[r][c];
System.out.println ("Enter Elements of the Matrix");
//INPUTING ELEMENTS IN THE MATRIX
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
mat[i][j]=sc.nextInt();
}
System.out.println ();
}
//ORIGINAL MATRIX

2023-23| SANCHITA SRIVASTAVA


P a g e | 120

System.out.println ("ORIGINAL MATRIX");


for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print( mat[i][j] );
}
System.out.println ( );
}
int sum = 0; for(
int i=0;i<r;i++ )
{
for( int j=0;j<c;j++ )
{
if( i==0||i==r-1 )
{
sum+=mat[i][j];
}
else if (j==0||j==c-1)
{
sum+=mat[i][j];
}
}
}
System.out.println ("SUM OF THE BOUNDARY ELEMENTS IS :
"+sum);
sortmartix(r,c);
//SORTED MATRIX

2023-23| SANCHITA SRIVASTAVA


P a g e | 121

System.out.println ("SORTED MATRIX");


for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(mat[i][j]);
}
System.out.println ();
}
sum=0; for(int
i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(i==0||i==r-1)
{
sum+=mat[i][j];
}
else if( j==0||j==c-1 )
{
sum+=mat[i][j];
}
}
}
System.out.println ("SUM OF THE BOUNDARY ELEMENTS IS
:"+sum);
}
public static void sortmartix(int a,int b)

2023-23| SANCHITA SRIVASTAVA


P a g e | 122

{
int arr[] = new int [a*b],k=0;
//CONVERTTING MATRIX TO LINEAR ARRAY
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
arr[k]=mat[i][j];
k++;
}
}
//SORTING
for(int i=0; i<a*b; i++)
{
for( int j=0; j<a*b-1; j++ )
{
if(arr[j]<arr[j+1])
{
int copy = arr[j];
arr[j]=arr[j+1];
arr[j+1] = copy;
}
}
}
//COVERTING LINEAR ARRAY TO MATRIX
k=0;
for(int i=0;i<a;i++)
{

2023-23| SANCHITA SRIVASTAVA


P a g e | 123

for(int j=0;j<b;j++)
{
mat[i][j]=arr[k]; k++;
}
}
}
}
VARIABLE DESCRIPTION TABLE:

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 124

PROGRAM 22
An Evil No. is a positive no. which has even no. of 1’s in its binary equivalent.
Example: Binary equivalent of 15 is 111, which contains even no. of 1’s.
Design a program to accept a positive whole no. and find the binary equivalent
of the no. and count the no. of 1’s in it and display whether it is an evil no. or not
with an appropriate message.

ALGORITHM:
• We first take a number.
• We then find the binary equivalent of this number and store it into another
variable.
• We find the total number of ones in the binary number.
• If we found an even number of ones in the binary equivalent number, then
the number is an evil number. Else the given number is not an evil number.

2023-23| SANCHITA SRIVASTAVA


P a g e | 125

SOURCE CODE:
import java.util.Scanner;

public class EvilNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive number: "); int n
= in.nextInt();
if (n < 0) {
System.out.println("Invalid Input");
return;
}

int count = 0;

2023-23| SANCHITA SRIVASTAVA


P a g e | 126

int p = 0;
int binNum = 0;
while (n > 0) {
int d = n % 2;
if (d == 1)
count++;
binNum += (int)(d * Math.pow(10, p ));
p ++;
n /= 2;
}

System.out.println("Binary Equivalent: "+ binNum);


System.out.println("No. of 1's: "+ count);

if (count % 2 == 0)
System.out.println("Output: Evil Number");
else
System.out.println("Output: Not an Evil Number");
}
}
VARIABLE DESCRIPTION
TABLE:

A Int Used to store no.

N Int To enter a number

2023-23| SANCHITA SRIVASTAVA


P a g e | 127

S String To store binary


equivalent

dig[] Char Used as an array

R Int To store remainder

C Int Used as a counter

I Int Used for loop

Ch Char Used to extract


characters

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 128

PROGRAM 23

ALGORITHM:
• We create a merge method that takes two sorted arrays arr1 and arr2 as input
and returns the merged array in ascending order.
• We initialize three indices: i for arr1, j for arr2, and k for the merged array.
• We iterate through both input arrays, comparing elements at indices i and j.
• We add the smaller element to the merged array and increment the respective
indices.
• After the first while loop, if any elements are remaining in arr1 or arr2, we
copy them to the merged array.
• Finally, we return the merged array.

SOURCE CODE:
public class MergeArray
{

2023-23| SANCHITA SRIVASTAVA


P a g e | 129

public static int[] merge(int[] arr1, int[] arr2)


{
int[] mergedArray = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length)
{
if (arr1[i] < arr2[j])
{
mergedArray[k++] = arr1[i++];
}
else

2023-23| SANCHITA SRIVASTAVA


{
mergedArray[k++] = arr2[j++];
}
}
while (i < arr1.length)
{
mergedArray[k++] = arr1[i++];
}
while (j < arr2.length)
{ mergedArray[
k++] =
arr2[j++];
}
return mergedArray;
}
public static void main(String[] args)
{
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
int[] merged = merge(arr1, arr2);
System.out.println("Merged Array:");
for (int num : merged)
{
System.out.print(num + " ");
}
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description
i int For updation of loop

2023-23| SANCHITA SRIVASTAVA


P a g e | 131

j int For updation of loop


k int For updation of loop
arr1 int To store 1st array
arr2 int To store 2nd array
num int
To store merged array
OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 132

PROGRAM 24

ALGORITHM:
• Initialize the constructor.
• Accept the word in UPPER case.
• Remove the repeated alphabet from the word and store the modified word.
• Display the original word along with the modified word.

2023-23| SANCHITA SRIVASTAVA


P a g e | 133

• End.

SOURCE CODE:
import java.util.*;
class repeat
{
String str,newstr;

2023-23| SANCHITA SRIVASTAVA


P a g e | 134

int len; repeat()


{ str="";
newstr="";
len=0;
}
void readword()
{
Scanner sc=new Scanner(System.in); System.out.println("Enter a
word");
str=sc.next(); str=str.toUpperCase();
len=str.length();
}
void modify()
{
for(int i=65;i<=90;i++)

{ int
f=0;
for(int j=0;j<len;j++)
{
char ch=str.charAt(j);
if(ch==(char)i)
f++;
}
if(f==1)
newstr=newstr+(char)i;
}
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 135

void show()
{
System.out.println("Original word="+str);
System.out.println("Modified word="+newstr);
}
public static void main(String args[])
{
repeat ob=new repeat();
ob.readword();
ob.modify();
ob.show();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description

str String To store the word

newstr String To store the modified word

len int To find the length of the word

i int To run the loop

j int To run the loop

f int To count the repeated words

2023-23| SANCHITA SRIVASTAVA


P a g e | 136

ch char To extract the character

OUTPUT:

PROGRAM 25
A composite Magic number is a positive integer which is composite as well as
magic number. Composite number: A composite number is a number which
has more than two factors.
For example:
Factors of 12 are 1,2,3 ,4 ,6,12

Magic number: A Magic number is a number in which the eventual sum of the
digits is equal to 1.For example: 64: =6+4=10= 1+0=1
Accept two positive integers ‘m’ and ‘n’, where m is less than n. Display all
composite magic numbers that are in the range between m and n (both
inclusive and where m<n) and output them along with frequency, in the
format specified below:
Test your program for the following data and some random data.

2023-23| SANCHITA SRIVASTAVA


P a g e | 137

Example 1:
INPUT m=10
n=100
OUTPUT:
The composite magic numbers are 10, 28, 46, 55, 64, 82, 91, 100
Frequency of composite magic numbers: 8

ALGORITHM:
• Define a function to check if a number is composite.
• Define a function to calculate the sum of digits of a number.
• Define a function to check if a number is a magic number.
• Define the main function.
• Take input for the lower and upper limits.
• Iterate over the range of numbers from the lower to the upper limit.
• Check if the number is composite and magic.
• Print the composite magic numbers and their frequency.

SOURCE CODE:
import java.util.Scanner;

public class CompositeMagicNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter m: ");
int m = in.nextInt();

2023-23| SANCHITA SRIVASTAVA


P a g e | 138

System.out.print("Enter n: ");
int n = in.nextInt();

if (m < 1 || n < 1 || m > n) {


System.out.println("Invalid input");
return;
}

System.out.println("The composite magic numbers are:"); int


count = 0; for (int i = m; i <= n; i++) {

boolean isComposite = false;


for (int j = 2; j < i; j++) { if (i
% j == 0) { isComposite =
true;
break;
}
}

if (isComposite && i != 1) {
int num = i;
while (num > 9) { int
sum = 0; while (num !
= 0) { int d = num
% 10; num /= 10;
sum += d;
}
num = sum;

2023-23| SANCHITA SRIVASTAVA


P a g e | 139

if (num == 1) {
count++;
System.out.print(i + " ");
}
}
}
System.out.println();
System.out.println("Frequency of composite magic numbers: " + count);
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description

m int To store lower limit

n int To store upper limit

i int To run the loop

j int To run the loop

count int Counter variable

2023-23| SANCHITA SRIVASTAVA


P a g e | 140

OUTPUT:

PROGRAM 26
Write a program to accept a sentence which may be terminated by full stop(.)
only. The words are to be separated by single blank space. Print an error
message if the sentence does not end with full stop. Perform the following tasks:
a) Convert first letter of each word to uppercase.
b) Find the vowel and consonants in each word and display them with proper
headings along with the words.

ALGORITHM:
• Accept a sentence.
• Check if it ends with a full stop.
• Convert the first letter of each word to uppercase.
• Then count and display the number of vowels and consonants in each word.
• If the sentence does not end with a full stop, it displays an error message.

SOURCE CODE:
import java.util.Scanner;

2023-23| SANCHITA SRIVASTAVA


P a g e | 141

public class SentenceProcessor { public


static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a sentence terminated by a full stop


(.)");
String inputSentence = scanner.nextLine();

// Check if the sentence ends with a full stop.


if (!inputSentence.endsWith(".")) {
System.out.println("Error: The sentence should end with a full stop.");
return;
}

// Remove the full stop and split the sentence into words. String[]
words = inputSentence.substring(0, inputSentence.length() - 1).split(" ");

// Process each word in the sentence.


for (String word : words) {
// Convert the first letter of each word to uppercase.
String capitalizedWord = capitalizeFirstLetter(word);

// Find and display vowels and consonants.


int vowelCount = 0; int
consonantCount = 0; for (char c :
word.toCharArray()) {

2023-23| SANCHITA SRIVASTAVA


P a g e | 142

if (isVowel(c))
{ vowelCount++;
} else if (Character.isLetter(c))
{ consonantCount++;
}
}
// Print the word along with vowel and consonant counts.
System.out.println("Word: " + capitalizedWord);
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
System.out.println();
}
}

private static String capitalizeFirstLetter(String word) { if


(word.isEmpty()) {
return word;
}
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}

private static boolean isVowel(char c) {


c = Character.toLowerCase(c); return c == 'a' || c == 'e' || c
== 'i' || c == 'o' || c == 'u';
}
}

VARIABLE DESCRIPTION TABLE:

2023-23| SANCHITA SRIVASTAVA


P a g e | 143

Variable Data Type Description


scanner Scanner Used for reading input from the standard
input
inputSentence string Stores the input sentence provided by
the user.
words string[] An array that stores words extracted
from the input sentence.
capitalizedWord string Stores the word with its first letter
capitalized.
vowelCount int Stores the count of vowels in a word.

consonantCount int Stores the count of consonants in a


word.
c char A character used for iterating through
characters in a word.

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 144

PROGRAM 27
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 and M is equal to N. Allow the
user to input integers into this matrix. Perform the following task on the
matrix. o Display the input matrix. o Find the maximum and minimum
value of matrix and display them along with their index.
o Find and display sum of left diagonal elements of an array.

ALGORITHM:
• Enter the size of the square matrix (M x N, where M = N).
• Input the matrix elements.
• Display the input matrix.
• Find and display the maximum and minimum values along with their indices.
• Calculate and display the sum of left diagonal elements.

SOURCE CODE:
import java.util.Scanner; public
class MatrixOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the size of the matrix
int M, N; do {
System.out.print("Enter the number of rows and columns (M x
N, M=N): ");
M = scanner.nextInt();

2023-23| SANCHITA SRIVASTAVA


P a g e | 145

N = scanner.nextInt();
} while (M < 3 || M > 9 || N < 3 || N > 9 || M != N);
// Declare the matrix
int[][] A = new int[M][N];

// Input matrix elements


System.out.print("Enter the matrix elements:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print("A[" + i + "][" + j + "]: ");
A[i][j] = scanner.nextInt();
}
}
// Display the input matrix
System.out.println("Input Matrix:"); displayMatrix(A);
// Find and display the maximum and minimum values along with their
indices int max = A[0][0];
int min = A[0][0]; int maxRow = 0, maxCol = 0,
minRow = 0, minCol = 0; for (int i = 0; i < M; i++) { for
(int j = 0; j < N; j++) { if (A[i][j] > max)
{ max = A[i][j]; maxRow = i;
maxCol = j;
}
if (A[i][j] < min) {
min = A[i][j];
minRow = i;
minCol = j;
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 146

}
}

System.out.println("Maximum Value: " + max + " at A[" + maxRow + "][" +


maxCol + "]");
System.out.println("Minimum Value: " + min + " at A[" + minRow
+ "][" + minCol + "]");

// Find and display the sum of left diagonal elements int


leftDiagonalSum = 0;
for (int i = 0; i < M; i++) {
leftDiagonalSum += A[i][i];
}

System.out.println("Sum of Left Diagonal Elements: " +


leftDiagonalSum);

scanner.close();
}

// Method to display a matrix


public static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 147

}
}

VARIABLE DESCRIPTION TABLE:

2023-23| SANCHITA SRIVASTAVA


2023-23| SANCHITA SRIVASTAVA
P a g e | 149

2023-23| SANCHITA SRIVASTAVA


P a g e | 150

PROGRAM 28
Design a class NumDude to check if a given number is a Dudeney number or
not. (A Dudeney number is a positive integer that is a perfect cube, such that the
sum of its digits is equal to the cube root of the number.) Example: 5832 = (5 + 8
+ 3 + 2)3 = (18)3 = 5832 Some of the members of
the class are given below:
Class name : NumDude
Data member/instance/variable:
num : to store a positive integer number
Methods/Member functions:
NumDude() : default constructor to initialise the data member with legal initial
value void input() : to accept a positive integer number
int sumDigits(int x) : returns the sum of the digits of number ‘x’ using recursive
technique void is Dude() : checks whether the given number is a
Dudeney number by invoking the function sumDigits() and displays the result
with an appropriate message.
Specify the class NumDude giving details of the constructor(), void input(), int
sumDigits(int) and void is Dude(). Define a main() function to create an object
and call the functions accordingly to enable the task.

ALGORITHM:
1. Create a classNumDude with a private instance
variable num to store a positive integer number.
2. NumDude() that
initializes num to a legal initial value, which is 0
Implement a default
in this case. constructor
3. Implement the method to accept a positive num

2023-23| SANCHITA SRIVASTAVA


P a g e | 151

variable. x) method, which is a


4. Implement the sumDigits(int
recursive function that calculates the sum of the
x.
digits of a given integer method to check if the number
5. Implement the isDude() is a Dudeney number by calculating the cube root of
num and the sum of its digits. It then compares these values and prints an
appropriate message.
6. In the main() function, create an object of the NumDude class, call the
input() method to accept a number, and then call the isDude() method to
check if it's a Dudeney number or not.

SOURCE CODE:
import java.util.Scanner;

class NumDude {
private int num; public
NumDude() { num = 0;
}
public void input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: "); num
= scanner.nextInt(); scanner.close();
}
private int sumDigits(int x) {
if (x == 0) {
return 0;
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 152

return x % 10 + sumDigits(x / 10);


}
public void isDude() { double
cubeRoot = Math.cbrt(num); int digitSum
= sumDigits(num); if (cubeRoot ==
digitSum) {
System.out.println(num + " is a Dudeney number.");
} else {
System.out.println(num + " is not a Dudeney number.");
}
}
public static void main(String[] args) {
NumDude numDude = new NumDude();
numDude.input();
numDude.isDude();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description

num int Private instance variable to


store a positive integer number.

cubeRoot double Double variable to store the


cube root of the number.

2023-23| SANCHITA SRIVASTAVA


P a g e | 153

digitSum int Integer variable to store the


sum of the digits of the number.

numDude int An instance of the NumDud


e
class used in the main()
function.

OUTPUT:

PROGRAM 29
A class Trans is defined to find the transpose of a square matrix. A transpose of a
matrix is obtained by interchanging the elements of the rows and columns. Some
of the members of the class are given below:
Class name : Trans
Data members/instance variable:

2023-23| SANCHITA SRIVASTAVA


P a g e | 154

arr[][] : to store integers in the


matrix m : integer to store the
size of the matrix
Methods/Member functions:
Trans(int mm) : parameterised constructor to initialise the
data member m = mm
void fillarray() : to enter integer elements in the matrix
void transpose() : to create the transpose of the given
matrix void display() : displays the original matrix and the
transport matrix by invoking the method transpose()
Specify the class Trans in JAVA giving details of the constructor(), void
fillarray(), void transpose() and void display().
Define a main() function to create an object and call the functions accordingly to
enable the task.

ALGORITHM
• Create a class called "Trans" with data members:
- arr[][] to store integers in the matrix
- m to store the size of the matrix
• Define a parameterized constructor "Trans(int mm)" within the class:
- Initialize m with mm.
- Create a 2D array arr with dimensions m x m.
• Define a method "fillarray()" to input elements into the matrix:
- Use nested loops to input elements into the matrix.
• Define a method "transpose()" to calculate and update the transpose:
- Create a new 2D array transposedArr with dimensions m x m.
- Calculate the transpose of the matrix by swapping rows and columns.

2023-23| SANCHITA SRIVASTAVA


P a g e | 155

- Update the original arr with transposedArr.


• Define a method "display()" to display both the original and transposed
matrices:
- Display "Original Matrix:" and use nested loops to display elements.
- Call the "transpose()" method to calculate the transpose.
- Display "Transposed Matrix:" and use nested loops to display elements.
• In the "main()" function:
- Prompt the user to enter the size of the square matrix and store it in size.
- Create an object transObj of the Trans class with size as the argument.
- Call the "fillarray()" method to input matrix elements.
- Call the "display()" method to display both matrices.

SOURCE CODE:
import java.util.Scanner;
class Trans { private int[]
[] arr; private int m;
public Trans(int mm) {
m = mm;
arr = new int[m][m];
}
public void fillarray() {
Scanner input = new Scanner(System.in);
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) {
arr[i][j] = input.nextInt();
}
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 156

}
public void transpose() { int[][]
transposedArr = new int[m][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
transposedArr[i][j] = arr[j][i];
}
}
arr = transposedArr;
}
public void display() {
System.out.println("Original Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
transpose();
System.out.println("Transposed Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {

2023-23| SANCHITA SRIVASTAVA


P a g e | 157

Scanner input = new Scanner(System.in);


System.out.print("Enter the size of the square matrix: ");
int size = input.nextInt(); Trans transObj = new Trans(size);
transObj.fillarray();
transObj.display();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Data Type Description

arr int Stores the square matrix


elements.

m int Stores the size of the


square matrix.

transposedArr int Stores the transposed matrix


temporarily.

size int Stores the size of the the


square matrix entered by user.

transObj Trans Object An instance of the Trans


class to perform matrix operations.

2023-23| SANCHITA SRIVASTAVA


P a g e | 158

OUTPUT:

PROGRAM 30
A class SortAlpha has been defined to sort the words in the sentence in
alphabetical order. Example: Input: THE SKY IS BLUE Output: BLUE IS SKY
THE Some of the members of the class are given below: Class name : SortAlpha
Data members/instance variable: sent : to store a sentence n : integer to store the
number of words in a sentence Methods/Member functions: SortAlpha() :
default constructor to initialise data members with legal initial value void
acceptsent() : to accept a sentence in UPPER CASE void sort(SortAlpha P) :
sorts the words of the sentence of object P in alphabetical order and stores the
sorted sentence in the current object void display() :
display the original sentence along with the sorted sentence by invoking the
method sort() Specify the class SortAlpha giving details of the constructor(),

2023-23| SANCHITA SRIVASTAVA


P a g e | 159

void acceptsent(), void sort(SortAlpha) and void display(). Define a main()


function to create an object and call the functions accordingly to enable the task.

ALGORITHM:
• The SortAlpha class has data members sent to store the input sentence
and n to store the number of words.
• The default constructor SortAlpha() initializes these data members with
legal initial values (empty string and 0).
• The acceptsent() method allows the user to input a sentence in uppercase
and counts the number of words in it.
• The sort(SortAlpha P) method takes another SortAlpha object P, splits
its sent into words, sorts them alphabetically, and stores the result in the
current object's sent member.
• The display() method displays both the original and sorted sentences by
invoking the sort() method.
• The main() function creates an instance of SortAlpha, accepts the
sentence, and displays both the original and sorted sentences.

SOURCE CODE:
import java.util.Arrays;
import java.util.Scanner;
class SortAlpha1
{ private String sent;
private int n; public
SortAlpha1() { sent =
"";
n = 0;
}

2023-23| SANCHITA SRIVASTAVA


P a g e | 160

public void acceptsent() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence in UPPER CASE: ");
sent = scanner.nextLine(); String[]
words = sent.split("\\s+"); n=
words.length;
}
public void sort(SortAlpha1 P) {
String[] words = P.sent.split("\\s+"); Arrays.sort(words);
this.sent = String.join(" ", words);
}
public void display() {
System.out.println("Original Sentence: " + sent); SortAlpha1
sortedObject = new SortAlpha1();
sortedObject.sent = sent; sortedObject.sort(this);
System.out.println("Sorted Sentence: " + sortedObject.sent);
}
public static void main(String[] args) { SortAlpha1
obj = new SortAlpha1();
obj.acceptsent();
obj.display();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Type Description

sent String Stores the input sentence in

2023-23| SANCHITA SRIVASTAVA


P a g e | 161

uppercase.
n int Stores the number of words
in the sentence.

words String[] An array to store individual


words from the sentence split by spaces.

obj SortAlpha An instance of the SortAlpha


class.

sortedObject SortAlpha Another instance of the


SortAlpha class used for
sorting

OUTPUT:

2023-23| SANCHITA SRIVASTAVA


P a g e | 162

2023-23| SANCHITA SRIVASTAVA


P a g e | 163

2023-23| SANCHITA SRIVASTAVA

You might also like