0% found this document useful (0 votes)
20 views167 pages

Java Programs for Prime Adam & Carton Packing

The document contains multiple Java programming tasks including displaying Prime Adam integers, packing cartons, checking for Circular Primes, identifying Goldbach numbers, and calculating dates from day numbers. Each task includes an algorithm and a complete Java program implementation. The programs cover various concepts such as prime checking, user input validation, and date manipulation.

Uploaded by

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

Java Programs for Prime Adam & Carton Packing

The document contains multiple Java programming tasks including displaying Prime Adam integers, packing cartons, checking for Circular Primes, identifying Goldbach numbers, and calculating dates from day numbers. Each task includes an algorithm and a complete Java program implementation. The programs cover various concepts such as prime checking, user input validation, and date manipulation.

Uploaded by

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

1

Number Programs
Question 1
Write a program in java to display all Prime Adam integers between the given range
with their Frequency.
Algorithm:

1. Start
2. Create class primeAdam.
3. Instance Variables:
a. Declare integers m and n.
4. Method input:
a. Use Scanner to accept values for m and n.
b. Loop until valid input (m > 0, n > 0, m < n) is given, otherwise print
"INVALID INPUT".
5. Method isPrime:
a. Accept integer s, initialize counter c = 0.
b. Loop from 1 to s, increment c if s % i == 0.
c. Return true if c == 2, else false.
6. Method reverse:
a. Accept integer a, initialize rev = 0.
b. Reverse digits of a using a while loop.
c. Return rev.
7. Method primeadam:
a. Loop from m to n. For each i, calculate sqnum = i * i, reverse i and its
square.
b. If i is prime and the reversed square equals the original square, print i
and count it.
8. Method main:
a. Create an object of primeAdam.
b. Loop to call input and primeadam methods until the user enters 0 to
stop.
9. Stop

Program:

import [Link].*;
public class primeAdam
{
int m,n;
void input()
2

{
Scanner sc=new Scanner ([Link]);
while (true)
{
[Link]("Enter the value of m");
m=[Link]();
[Link]("Enter the value of n");
n=[Link]();
if(m>0 && n>0 && m<n)
{
break;
}
else
{
[Link]("INVALID INPUT");
}
}
}
boolean isPrime(int s)
{
int c=0;
for(int i=1;i<=s;i++)
{
if(s%i==0) //checking
if number is prime or not
c++;
}
if(c==2)
return true;
else
return false;
}
int reverse(int a)
{
int rev=0;
while(a>0) //reversing the digits to
check
{
int r=a%10;
rev=rev*10+r;
a=a/10;
}
return rev;
}
void primeadam()
{
[Link]("The prime adam integers are");
3

int z ;
int c=0;
for(int i=m;i<=n;i++)
{
int num=i;
int sqnum=num*num;
int rev=reverse(num);
int revsq=rev*rev;
int revofrevsq= reverse(revsq);
if(isPrime (num)==true && revofrevsq==sqnum)
{
[Link](i+" ");
c++;
}
}
[Link]();
[Link]("The number of prime adam integers
are "+c);
}
public static void main()
{
Scanner sc=new Scanner([Link]);
primeAdam ob=new primeAdam();
while (true)
{
[Link]();
[Link]();
[Link]("Enter 0 to stop or any other
number to continue");
int ch=[Link]();
if (ch==0)
break;
}
}
}
4

Output:
5

Question 2
A company manufactures packing cartons in four sizes, i.e. cartons to
accommodate 6 boxes, 12 boxes, 24 boxes and 48 boxes. Design a program to
accept the number of boxes to be packed (N) by the user (maximum up to 1000
boxes) and display the break-up of the cartons used in descending order of capacity
(i.e. preference should be given to the highest capacity available, and if boxes left
are less than 6, an extra carton of capacity 6 should be used.)
Example:
INPUT: N = 726
OUTPUT: 48 * 15 = 720
6*1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16
Algorithm
[Link]
[Link] the class CartonPacking.
[Link] the number of cartons of size 48, 24, 12, and 6 using integer division
and modulus:
cartons48 = remainingBoxes / 48
remainingBoxes %= 48
cartons24 = remainingBoxes / 24
remainingBoxes %= 24
cartons12 = remainingBoxes / 12
remainingBoxes %= 12
cartons6 = remainingBoxes / 6
remainingBoxes %= 6
If any remainingBoxes are left, increment cartons6 by 1 and set remainingBoxes to
0.
[Link] Results:
5Stop

Program:
import [Link];

public class CartonPacking {

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the number of boxes (N): ");


6

int N = [Link]();

if (N < 0 || N > 1000) { //taking number of


boxes according to condition
[Link]("Invalid input, please enter a
number between 1 and 1000.");
return;
}

int remainingBoxes = N;
int cartons48 = remainingBoxes / 48;
remainingBoxes %= 48;

int cartons24 = remainingBoxes / 24;


remainingBoxes %= 24;

int cartons12 = remainingBoxes / 12;


remainingBoxes %= 12;

int cartons6 = remainingBoxes / 6;


remainingBoxes %= 6;

if (remainingBoxes > 0) {
cartons6++;
remainingBoxes = 0;
}

if (cartons48 > 0) { //printing according to


cartons left
[Link]("48 * " + cartons48 + " = " + (48
* cartons48));
}
if (cartons24 > 0) {
[Link]("24 * " + cartons24 + " = " + (24
* cartons24));
}
if (cartons12 > 0) {
[Link]("12 * " + cartons12 + " = " + (12
* cartons12));
}
if (cartons6 > 0) {
[Link]("6 * " + cartons6 + " = " + (6 *
cartons6));
}

[Link]("Remaining boxes = " +


remainingBoxes);
7

[Link]("Total number of boxes = " + N);


[Link]("Total number of cartons = " +
(cartons48 + cartons24 + cartons12 + cartons6));
}
}

Output:
8

Question 3
A Circular Prime is a prime number that remains prime under cyclic shifts of its
digits. When the leftmost digit is removed and replaced at the end of the remaining
string of digits, the generated number is still prime. The process is repeated until
the original number is reached again. A number is said to be prime if it has only
two factors 1 and itself.
Example: 131 311 113
Hence, 131 is a circular prime. Accept a positive number N and check whether it is
a circular prime or not. The new numbers formed after the shifting of the digits
should also be displayed.
Algorithm:

1. Start
2. Create a class named CircularPrime.
3. Prime Checking Method (isPrime):
a. Accept an integer num.
b. If num < 2, return false.
c. Loop from 2 to the square root of num:
d. If num % i == 0, return false.
e. Return true if no divisors are found, indicating the number is prime.
4. Method to Rotate Digits (shiftDigits):
a. Convert the integer num to a string.
b. Rotate the number by moving the leftmost digit to the right.
c. Convert the rotated string back to an integer and return it.
5. Main Method (main):
a. Accept an integer N from the user using a Scanner.
b. Initialize shiftedNum = N.
c. Set isCircularPrime = true.
d. For each digit in N (loop over the length of the number):
e. Print the shiftedNum.
f. Call isPrime to check if shiftedNum is prime:
g. If not prime, set isCircularPrime = false.
h. Rotate the number by calling shiftDigits.
i. After the loop, print whether N is a circular prime or not based on
the value of isCircularPrime.
6. Stop
9

Program:
import [Link];

public class CircularPrime {

public static boolean isPrime(int num) {


if (num < 2) {
return false;
}
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

public static int shiftDigits(int num) {


String numStr = [Link](num);
//Reversing the number
String shiftedStr = [Link](1) +
[Link](0);
return [Link](shiftedStr);
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the number N: ");


int N = [Link]();

String numStr = [Link](N);


int length = [Link]();
int shiftedNum = N;
boolean isCircularPrime = true;

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


[Link](shiftedNum);
if (!isPrime(shiftedNum))
{ //seeing if number is prime
isCircularPrime = false;
}
shiftedNum = shiftDigits(shiftedNum);
}

if (isCircularPrime) {
[Link](N + " IS A CIRCULAR PRIME");
10

} else {
[Link](N + " IS NOT A CIRCULAR PRIME");
}

}}
Output:
11

Question 4
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'.
Algorithm:
1. Start

[Link] the class GoldbachNumber.

[Link] Checking Method (isPrime):


a. Accept an integer num.
b. If num < 2, return false.
c. Loop from 2 to the square root of num. If num % i == 0, return false.
d. Return true if no divisors are found, indicating the number is prime.

[Link] Method (main):

a. Accept an integer N from the user using Scanner.


b. If N is invalid (not even, not between 9 and 50), print "Invalid input" and
stop.
c. Loop through all odd numbers i from 3 to N / 2. For each i:
d. Calculate complement = N - i.
e. If both i and complement are prime, print them as a prime pair.

5. Stop

Program:
import [Link];

public class GoldbachNumber {

public static boolean isPrime(int num) {


if (num < 2) {
return false;
//checking initial condition
12

}
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0)
{ //checking prime
return false;
}
}
return true;
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter an even integer N (N > 9 and N <


50): ");
int N = [Link]();

if (N <= 9 || N >= 50 || N % 2 != 0) {
[Link]("Invalid input. N must be an even
integer greater than 9 and less than 50.");
return;
}

[Link]("PRIME PAIRS ARE:");


for (int i = 3; i <= N / 2; i += 2) {
int complement = N - i;
if (isPrime(i) && isPrime(complement)) {
[Link](i + ", " + complement);
}
}
}
}
Output:
13

Question 5
Write a program in JAVA to accept day number (between 1 and 366) and year
(yyyy) from the user and display the corresponding date. Also accept ‘N’ from the
user where (1<=N<=100) to compute and display the future date ‘N’ days after the
given date. Display error message if the value of the day number or ‘N’ are not
within the limit. Day number is calculated taking 1st January of the given year as
1.
Example :
INPUT:
DAY NUMBER: 50 YEAR: 2024 N: 25
OUTPUT: ENTERED DATE: FEBRUARY 19, 2024
25 AYS LATER: MARCH 15, 2024

Algorithm:
1. Start
2. Define two arrays: daysInMonthCommon and daysInMonthLeap,
representing the number of days in each month for common and leap years.
3. Define a method isLeapYear(int year) to check if a given year is a leap year.
4. Define a method getDateFromDayNumber(int dayNumber, int year):
5. Use the isLeapYear method to select the appropriate daysInMonth array.
6. Calculate the month and day from the given dayNumber.
7. Call the displayDate method to show the date.
8. Define a method displayDate(int day, int month, int year):
9. Format and print the date in a human-readable format with the appropriate
suffix (ST, ND, RD, TH).
[Link] the main method:
[Link] user input for the dayNumber, year, and the number of days to add
(N).
[Link] the inputs. If invalid, display an error and stop.
[Link] the getDateFromDayNumber method to display the original date.
[Link] the future date by adding N days and accounting for year changes:
Loop until the day number is valid for the current year.
Call getDateFromDayNumber to display the future date.
[Link]
Program:
import [Link];

public class DateCalculatorManual {

static int[] daysInMonthCommon = {31, 28, 31, 30, 31, 30,


31, 31, 30, 31, 30, 31};
14

static int[] daysInMonthLeap = {31, 29, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31};

public static boolean isLeapYear(int year) {


return (year % 4 == 0 && year % 100 != 0) || (year % 400
== 0);
}

public static void getDateFromDayNumber(int dayNumber, int


year) {
int[] daysInMonth = isLeapYear(year) ? daysInMonthLeap :
daysInMonthCommon;
int month = 0, day = 0;

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


if (dayNumber <= daysInMonth[i]) {
month = i + 1;
day = dayNumber;
break;
} else {
dayNumber -= daysInMonth[i];
}
}

displayDate(day, month, year);


}

public static void displayDate(int day, int month, int year)


{
String[] months = {"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"};
String suffix = "TH";
if (day % 10 == 1 && day != 11) suffix = "ST";
else if (day % 10 == 2 && day != 12) suffix = "ND";
else if (day % 10 == 3 && day != 13) suffix = "RD";
[Link]("DATE: " + day + suffix + " " +
months[month - 1] + ", " + year);
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the day number (between 1 and


366): ");
int dayNumber = [Link]();
15

[Link]("Enter the year (in 4 digits): ");


int year = [Link]();

[Link]("Enter the number of days to add


(between 1 and 100): ");
int N = [Link]();

// Validate inputs for day number, year, and N


if (dayNumber < 1 || dayNumber > 366 || year <= 0 || N <
1 || N > 100) {
[Link]("Error: Invalid input values.");
return;
}

int maxDays = isLeapYear(year) ? 366 : 365;


if (dayNumber > maxDays) {
[Link]("Error: Day number exceeds the
maximum limit for the given year.");
return;
}

getDateFromDayNumber(dayNumber, year);

// Calculate future date after adding N days


int futureDayNumber = dayNumber + N;
int futureYear = year;

while (futureDayNumber > (isLeapYear(futureYear) ? 366 :


365)) {
futureDayNumber -= isLeapYear(futureYear) ? 366 :
365;
futureYear++;
}

getDateFromDayNumber(futureDayNumber, futureYear);
}
}
16

Output:
17

Question 6
A unique-digit integer is a positive integer (without leading zeros) with no
duplicate digits. For example, 7, 135, 214 are all unique-digit integers whereas 33,
3121, 300 are not. Given two positive integers m and n, where m < n, write a
program to determine how many unique-digit integers are there in the range
between m and n (both inclusive) and output them. The input contains two positive
integers m and n. Assume m < 30000 and n < 30000. You are to output the number
of unique-digit integers in the specified range along with their values in the format
specified below: Example INPUT: m = 100 n = 120 OUTPUT: THE UNIQUE-
DIGIT INTEGERS ARE: 102, 103, 104, 105, 106, 107, 108, 109, 120
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 9

Algorithm:

1. Start
2. Define a method isUniqueDigitInteger(int num):
3. Convert the number to a string.
4. Initialize a boolean array digits[] to track digits 0-9.
5. Loop through the digits of the number:
6. If the digit is already marked as true in the array, return false.
7. Otherwise, mark the digit as true.
8. Return true if all digits are unique.
9. In the main method:
[Link] values m and n from the user.
[Link] the range; if invalid, print an error and stop.
[Link] through numbers between m and n:
[Link] each number, check if it's a unique-digit integer using
isUniqueDigitInteger.
[Link] the number if true and increment the counter.
[Link] the total count of unique-digit integers.
[Link]

Program:
import [Link];

public class UniqueDigit {

public static boolean isUniqueDigitInteger(int num) {


String strNum = [Link](num);
18

boolean[] digits = new boolean[10];


//making array to check easily

for (int i = 0; i < [Link](); i++) {


int digit = [Link](i) - '0';
if (digits[digit]) { //checking true
or false and returning accordingly
return false;
}
digits[digit] = true;
}
return true;
}

public static void main() {


Scanner sc = new Scanner([Link]);
[Link]("Enter the value of m: ");
int m = [Link]();
[Link]("Enter the value of n: ");
int n = [Link]();

if (m > n || m < 0) {
[Link]("Invalid range. Please enter a
valid range.");
return;
}

int count = 0;
[Link]("THE UNIQUE-DIGIT INTEGERS ARE: ");
for (int i = m; i <= n; i++) {
if (isUniqueDigitInteger(i)) {
[Link](i + " ");
count++;
}
}
[Link]();
[Link]("FREQUENCY OF UNIQUE-DIGIT INTEGERS
IS: " + count);
}
}
19

Output:
20

Question 7:
Write a Program in Java to input a number in Decimal number system and convert
it into its equivalent number in the Octal number system
Algorithm:
1. Start
2. Initialize the class Deci_Oct:
3. Create instance variables n and oct to store the decimal number and the octal
result.
4. Method getnum(int nn):
5. Assign the input decimal number nn to n.
6. Method deci_oct():
7. Use recursion to calculate the octal representation of n.
8. At each step, calculate c = n % 8 and reduce n by dividing it by 8.
9. Append c to the octal result by updating oct.
[Link] show():
[Link] the original decimal number and call deci_oct() to convert and
display the octal result.
[Link] method:
[Link] input from the user for the decimal number.
[Link] getnum() and show() for conversion.
[Link] to run again based on user input.
[Link]
Program:
import [Link].*;
public class Deci_Oct
{
int n,oct; Deci_Oct()
{
n=0;
oct=0;
}
void getnum(int nn)
{
n=nn;
21

}
void deci_oct()
{
int c;
if(n==0)
return;
c=n%8;
n/=8;
deci_oct();
oct=(oct*10)+c; //converting the digits
}
void show()
{
[Link]("Decimal Number="+n); oct=0;
deci_oct();
[Link]("Octal number is "+oct);
}
public static void main()
{
Scanner in=new Scanner([Link]); Deci_Oct obj=new Deci_Oct();
char s='y'; do
{
[Link]("Enter decimal number:"); int m=[Link]();
[Link](m); [Link]();
[Link]("Run Again:y/n"); s=[Link]().charAt(0);
}
while(s=='y'); }} //running again if user says
}}

Output:
22
23

Question 8:
WAP that displays the composite magic numbers in the specified range. A
composite magic number is a positive integer which is composite as well as a
magic number. A magic number is a number in which the eventual sum of digits is
equal to 1

Algorithm:
1. Start
2. Initialize the class CompositeMagic.
3. Create instance variables m and n.
4. Method accept():
5. Use a Scanner to accept valid values of m and n from the user.
6. Ensure m and n are positive integers and m < n.
7. Method display():
8. Loop through numbers from m to n.
9. For each number, check if it is both composite (isComposite()) and magic
(isMagic()).
[Link] the number if both conditions are true and count how many are found.
[Link] isComposite(int num):
[Link] from 2 to num-1. If num has any divisors, return true (composite).
[Link] isMagic(int num):
[Link] sum the digits of num until a single digit is obtained.
[Link] true if the final digit is 1 (magic number).
[Link] method:
[Link] accept() to get input, and then call display() to show results.
[Link]
Program:
import [Link].*;
public class CompositeMagic
{
int m,n;

void accept()
{
Scanner in=new Scanner([Link]);
while(true)
[Link]("Enter m:");
m = [Link]();
[Link]("Enter n:");
n = [Link]();
24

if(m>0 && n>0 && m<n)


break;
}
}
void display()
{
int count=0;
for(int i=m;i<=n;i++)
{
boolean t1 = isComposite(i);
boolean t2 = isMagic(i);
if(t1==true && t2==true)
{
[Link](i+","); //counting composite magic
numbers
count++;
}
}
[Link]("The number of composite magic numbers
are:"+count);
}
boolean isComposite(int num)
{
int c=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
c++;
break;
}
}
if(c>0)
return true;
else
return false;
}
boolean isMagic(int num)
{
while(num>9)
{
int s=0;
while(num>0)
{
int r = num%10;
s=s+r; //taking sum of digits
25

num=num/10;
}
num=s;
}
if(num==1)
return true;
else
return false;
}

public static void main()


{
CompositeMagic ob = new CompositeMagic();
[Link]();
[Link]();
}
}

Output:
26

Question 9:
Write a Program in Java to input a number and check whether it is a Kaprekar
number or not. A positive whole number ‘n’ that has ‘d’ number of digits is
squared and split into two pieces, a right-hand piece that has ‘d’ digits and a left-
hand piece that has remaining ‘d’ or ‘d-1’ digits. If the sum of the two pieces is
equal to the number, then ‘n’ is a Kaprekar number.

Algorithm:

1. Start
2. Method count_digits(int a):
3. Initialize a counter count = 0.
4. Loop while a is not zero, increment the counter, and divide a by 10.
5. Return the count of digits.
6. Main Method:
7. Create an object of the Kaprekar class and a Scanner for input.
8. Loop to allow repeated input:
a. Accept an integer a from the user.
b. Compute s = a * a (square of a).
c. Split s into f (first half) and l (last half) based on the digit count of a.
d. If f + l == a, print "It is a Kaprekar number"; otherwise, print "It is not
a Kaprekar number".
e. Ask the user if they want to run again.
9. Stop
Program:
import [Link].*;
public class Kaprekar
{
public int count_digits(int a)
{
int count=0; while(a!=0)
{
a/=10; //taking count of digits
count++;
}
return count;
27

}
public static void main()
{
Kaprekar obj=new Kaprekar();
Scanner in=new Scanner([Link]); int a,s=0,f,l;
char st='y'; do
{
[Link]("Enter an integer:");
a=[Link]();
int d=obj.count_digits(a);
s=a*a; f=s/(int)[Link](10,d);
l=s%(int)[Link](10,d);
if(f+l==a) //condition of kaprekar number
[Link]("It is a Kaprekar number");
else
[Link]("It is not a Kapekar Number");
[Link]("run againy/n:"); st=[Link]().charAt(0);
}
while(st=='y');
}
}

Output:
28

Array Programs:
Question 1
A class Mixarray contains an array of integer elements along with its capacity
(More than or equal to 3). Using the following description, form a new array of
integers which will contain only the first 3 elements of the two different arrays one
after another.
Example:
Array1: { 78, 90, 100, 45, 67 }
Array2: {10, 67, 200, 90 }
Resultant Array: { 78, 90, 100, 10, 67, 200}
The details of the members of the class are given below:
Class name : Mixarray
Data members/instance variables:
arr[] : integer array
cap : integer to store the capacity of the array.

Member functions/methods:
Mixarray (int mm ) : to initialize the capacity of the array
cap=mm void input( ) : to accept the elements of the array Mixarray mix(Mixarray
P, Mixarray Q) : returns the resultant array having the first 3 elements of the array
of objects P and Q
void display( ) : to display the array with an appropriate message.
Specify the class Mixarray giving details of the constructor(int), void input( ),
Mixarray mix(Mixarray,Mixarray) and void display( ). Define a main( ) function to
create objects and call all the functions accordingly to enable the task.
Algorithm:

1. Start
2. Class Mixarray Initialization:
3. Declare instance variables arr[] and cap.
4. Constructor Mixarray(int mm) initializes the array with the capacity mm.
29

5. Method input():
6. Use a Scanner to accept cap number of elements from the user into the
array.
7. Method mix(Mixarray P, Mixarray Q):
8. Create a new Mixarray object to store the first three elements of P and
Q.
9. Loop to copy the first three elements of P into the resultant array.
[Link] to copy the first three elements of Q after the copied elements of
P.
[Link] display():
[Link] all elements of the resultant array.
[Link] Method:
[Link] two Mixarray objects, P and Q.
[Link] input() to accept elements for both arrays.
[Link] a new Mixarray object and call mix() to combine the first three
elements of both arrays.
[Link] the resultant mixed array using display().
[Link]
Program:
import [Link];
class Mixarray {
int[] arr;
int cap;
Mixarray(int mm) {
cap = mm;
arr = new int[cap];
}

void input() {
Scanner sc = new Scanner([Link]);
[Link]("Enter " + cap + " elements:");
for (int i = 0; i < cap; i++) {
arr[i] = [Link]();
30

}
}
Mixarray mix(Mixarray P, Mixarray Q) {
Mixarray result = new Mixarray(6);
for (int i = 0; i < 3; i++) { //taking only first
3 elements
[Link][i] = [Link][i];
[Link][i + 3] = [Link][i]; //making
resultant array
}
return result;
}
void display() {
[Link]("Resultant Array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
[Link]();
}
public static void main() {
Mixarray P = new Mixarray(5);
Mixarray Q = new Mixarray(4);
[Link]("Input elements for Array 1:");
[Link]();
[Link]("Input elements for Array 2:");
[Link]();
Mixarray result = new Mixarray(6);
result = [Link](P, Q);
[Link]();
}}
31

Output:
32

Question 2:
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.
Example:
2 3 1 (decimal equivalent of 1st row = 153 i.e. 2x82 + 3x81 + 1x80 )
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4x82 + 0x81 + 5x80 )
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1x82 + 5x81 + 6x80 )
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.

Algorithm:

1. Start
2. Main Method:
3. Use Scanner to accept the number of rows (m) and columns (n).
4. Declare a 2D array a[m][n].
5. Input Elements:
6. Loop through the matrix to accept values for each element.
7. Ensure that each value is between 0 and 7 (valid octal digits). If not,
display an error message and stop.
8. Decimal Conversion:
9. Loop through each row of the matrix.
[Link] each row of octal values to a decimal number using the
formula:
[Link] += a[i][j] * 8^(n - j - 1).
[Link] both the octal values and the corresponding decimal number for
each row.
[Link]
33

Program:
import [Link];
public class octalnumber
{
public static void main() {
Scanner in = new Scanner([Link]);
[Link]("Enter the number of rows");
int m = [Link]();
[Link]("Enter the number of columns");
int n = [Link]();
int a[][] = new int[m][n];

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


[Link]("enter elemnts ");
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
if (a[i][j] < 0 || a[i][j] > 7) {
[Link]("enter from 0-7");
//checking condition given
return;
}
}
}
[Link]("decimal equivalent:");
for (int i = 0; i < m; i++) {
int decNum = 0; //converting number to
decimal equivalent
for (int j = 0; j < n; j++) {
decNum += a[i][j] * [Link](8, n - j - 1 );
[Link](a[i][j] + " ");
34

}
[Link](decNum);
[Link]();
}
}
}

Output:
35

Question 3
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:
12581251121211251111222155128125
3. Display the filled matrix in the above format

Algorithm:

1. Start
2. Input the size of the matrix (N):
3. Accept N from the user, ensuring it is greater than 2 and less than 10.
4. Input the elements of the 1D array (a):
5. Accept N elements into array a.
6. Sort the array a using bubble sort:
7. Perform the bubble sort on a to arrange the elements in ascending order.
8. Fill the 2D matrix b[N][N]:
9. For each element in b[i][j], assign values from the sorted array a, cycling
through the array using modulus ((i + j) % N).
[Link] the sorted array.
[Link] the filled matrix.
[Link].

Program:
import [Link];
public class ArrayMatrix {

public static void main() {


Scanner sc = new Scanner([Link]);
36

[Link]("Enter the size of the matrix (N >


2 and N < 10): ");
int N = [Link]();

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


[Link]("Invalid input. N should be
greater than 2 and less than 10.");
return;
}

int[] a = new int[N];


int[][] b = new int[N][N];
[Link]("Enter the elements of the array:");
for (int i = 0; i < N; i++) {
a[i] = [Link]();
}

// Sorting the array using bubble sort


for (int i = 0; i < N - 1; i++) {
for (int j = 0; j < N - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}

[Link]("Sorted Array:");
for (int i = 0; i < N; i++) {
37

[Link](a[i] + " ");


}
[Link]();

// Fill the matrix b[][] using the sorted array


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
b[i][j] = a[(i + j) % N];
}
}
[Link]("Filled Matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
[Link](b[i][j] + " ");
}
[Link]();
}
}}
38

Output:
39

Question 4:
The result of a quiz competition is to be prepared as follows: The quiz has five
questions with four multiple choices (A, B, C, D), with each question carrying 1
mark for the correct answer. Design a program to accept the number of participants
N such that N must be greater than 3 and less than 11.
Create a double-dimensional array of size (Nx5) to store the answers of each
participant row-wise. Calculate the marks for each participant by matching the
correct answer stored in a single-dimensional array of size 5.
Example: If the value of N = 4, then the array would be
: Q1 Q2 Q3 Q4 Q5
Participant 1 A B B C A
Participant 2 D A D C B
Participant 3 A A B A C
Participant 4 D C C A B
Key to the question: D C C B A
Note: Array entries are line fed (i.e. one entry per line

Algorithm:

1. Start
2. Input the number of participants (N):
3. Accept N from the user, ensuring it is greater than 3 and less than 11.
4. Input correct answers:
5. Accept the correct answers for 5 questions from the user and store them in
an array correctAnswers[].
6. Input participants' answers:
7. Loop through N participants and accept their answers for the 5 questions.
8. Calculate scores:
9. Compare each participant's answers with the correct answers and calculate
their scores.
[Link] the maximum score during this process.
[Link] scores:
[Link] the score for each participant.
[Link] participants with the highest score:
40

[Link] and print the participants who scored the maximum marks.
[Link].

Program:
import [Link];
public class QuizCompetition {

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the number of participants (N >


3 and N < 11): ");
int N = [Link]();

if (N <= 3 || N >= 11) {


[Link]("Invalid input. N should be
greater than 3 and less than 11.");
return;
}

char[][] participants = new char[N][5];


int[] scores = new int[N];
char[] correctAnswers = new char[5];

[Link]("Enter the correct answers for 5


questions:");
for (int i = 0; i < 5; i++) {
correctAnswers[i] = [Link]().charAt(0);
}

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


41

[Link]("Enter answers for Participant "


+ (i + 1) + ":");
for (int j = 0; j < 5; j++) {
participants[i][j] = [Link]().charAt(0);
}
}

int maxScore = 0;
for (int i = 0; i < N; i++) {
scores[i] = 0;
for (int j = 0; j < 5; j++) {
if (participants[i][j] == correctAnswers[j]) {
scores[i]++;
}
}
if (scores[i] > maxScore) {
maxScore = scores[i];
} }
[Link]("Scores for each participant:");
for (int i = 0; i < N; i++) {
[Link]("Participant " + (i + 1) + ": " +
scores[i] + " marks");
}

[Link]("Participant(s) with the highest


score:");
for (int i = 0; i < N; i++) {
if (scores[i] == maxScore) {
[Link]("Participant " + (i + 1) + "
with " + maxScore + " marks");
} } }}
42

Output:
43
44

Question 5
Write a program to declare a square matrix A[][] of order (M × M) where 'M' must
be greater than 3 and less than 10. Allow the user to input positive integers into this
matrix. Perform the following tasks on the matrix: 1. Sort the non-boundary
elements in ascending order using any standard sorting technique and rearrange
them in the matrix. 2. Calculate the sum of both the diagonals. 3. Display the
original matrix, rearranged matrix and only the diagonal elements of the rearranged
matrix with their sum.
Algorithm:

1. Start
2. Input matrix size (M):
a. Ensure M is greater than 3 and less than 10.
b. Accept M x M positive integers from the user into the matrix A[][].
3. Sort non-boundary elements:
a. Extract non-boundary elements from the matrix.
b. Sort these elements using any standard sorting technique (e.g., bubble
sort).
c. Re-insert the sorted non-boundary elements into the matrix.
4. Calculate diagonal sums:
a. Compute the sum of both diagonals.
5. Display matrices and diagonal elements:
a. Print the original matrix.
b. Print the rearranged matrix.
c. Print the diagonal elements of the rearranged matrix and their sum.
6. Stop.
Program:
import [Link];
class SquareMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the matrix (M > 3
and M < 10): ");
int M = [Link]();
if (M <= 3 || M >= 10) {
45

[Link]("Invalid input. M should be


greater than 3 and less than 10.");
return;
}

int[][] matrix = new int[M][M];


int[] nonBoundary = new int[(M - 2) * (M - 2)];
int index = 0, diagSum1 = 0, diagSum2 = 0;
[Link]("Enter elements of the matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = [Link]();
// Collect non-boundary elements
if (i > 0 && i < M - 1 && j > 0 && j < M - 1) {
nonBoundary[index++] = matrix[i][j];
}} }
for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 1 - i; j++)
{
if (nonBoundary[j] > nonBoundary[j + 1]) {
int temp = nonBoundary[j];
nonBoundary[j] = nonBoundary[j + 1];
nonBoundary[j + 1] = temp;
}
}
}

// Reinsert sorted non-boundary elements into the matrix


index = 0;
for (int i = 1; i < M - 1; i++) {
for (int j = 1; j < M - 1; j++) {
46

matrix[i][j] = nonBoundary[index++];
}
}
for (int i = 0; i < M; i++) {
diagSum1 += matrix[i][i]; // Sum of primary
diagonal
diagSum2 += matrix[i][M - 1 - i]; // Sum of
secondary diagonal
}
[Link]("Original Matrix:");
displayMatrix(matrix, M);
[Link]("Rearranged Matrix:");
displayMatrix(matrix, M);
[Link]("Diagonal elements of the rearranged
matrix:");
for (int i = 0; i < M; i++) {
[Link](matrix[i][i] + " ");
}
[Link]();
for (int i = 0; i < M; i++) {
[Link](matrix[i][M - 1 - i] + " ");
}
[Link]();
[Link]("Sum of the diagonals: " + (diagSum1
+ diagSum2));
}
public static void displayMatrix(int[][] matrix, int M) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
[Link](matrix[i][j] + " ");
}
47

[Link]();
}}}

Output:
48

Question 6
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
Algorithm:

1. Start
2. Input Matrix Dimensions
a. Prompt the user to input the number of rows m and columns n.
b. Ensure that both m and n are greater than 2 and less than 10.
c. If the input is invalid, display an error message and stop.
3. Input Matrix Elements
a. Initialize a 2D array matrix of size m x n.
b. Accept elements from the user for each position in the matrix.
4. Display Original Matrix
a. Print the original matrix by iterating through each element.
5. Sort Rows
a. For each row in the matrix, apply the bubble sort algorithm to sort the
elements in ascending order.
6. Display Sorted Matrix
7. Print the matrix again, showing the sorted rows.
8. Stop

Program:
import [Link];

class MatrixSorting {

public static void main() {


49

Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows (m > 2 and m


< 10): ");
int m = [Link]();
[Link]("Enter the number of columns (n > 2 and
n < 10): ");
int n = [Link]();

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


[Link]("Invalid input. Both m and n
should be greater than 2 and less than 10.");
return;
}

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

[Link]("Enter elements of the matrix:");


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = [Link]();
}
}

[Link]("Original Matrix:");
displayMatrix(matrix, m, n);

// Sort each row of the matrix using bubble sort


for (int i = 0; i < m; i++) {
bubbleSort(matrix[i]); // Sort each row
}
50

[Link]("Changed Matrix after sorting each


row:");
displayMatrix(matrix, m, n);
}

public static void bubbleSort(int[] row) {


int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (row[j] > row[j + 1]) {
int temp = row[j];
row[j] = row[j + 1];
row[j + 1] = temp;
}
}
}
}

public static void displayMatrix(int[][] matrix, int m, int


n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
51

Output:
52

Question 7
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 both M and N must be
greater than 2 and less than10. Allow the user to input integers into this matrix.
Display appropriate error message for an invalid input. Perform the following tasks
on the matrix.
a. Display the input matrix
b. Shift each row one step upwards so the first row will become the last row 2nd
row will be the 1st row and so on
c. Display the rotated matrix along with the highest element and its location in the
matrix
Example 1: INPUT: M =3 N = 4
Enter elements in the matrix: 100 90 87 76 200 500 167 998 77 567 89 254
OUTPUT:
FORMED MATRIX AFTER ROTATING:
200 500 167 998 77 567 89 254 100 90 87 76 Highest element: 998 ( Row: 0 and
Column: 3 )
Example 2: INPUT: M = 2 N = 3
OUTPUT: SIZE IS OUT OF RANGE. INVALID ENTRY
Algorithm:
1. Start
2. Input Matrix Dimensions
a. Prompt the user to input the number of rows M and columns N.
b. Ensure that both M and N are greater than 2 and less than 10.
c. If the input is invalid, display an error message and stop.
3. Input Matrix Elements
4. Initialize a 2D array matrix of size M x N.
5. Accept integers from the user for each position in the matrix.
6. Display Original Matrix
7. Print the original matrix by iterating through each element.
8. Rotate Matrix
9. Shift each row one step upwards, moving the first row to the last position.
[Link] the Highest Element
53

a. Iterate through the matrix to find the highest element and its position
(row and column).
[Link] Rotated Matrix
[Link] Highest Element
[Link] the highest element along with its location (row and column).
[Link]
Program:
import [Link];
class MatrixRotation {
public static void main() {
Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows (M > 2 and M


< 10): ");
int M = [Link]();
[Link]("Enter the number of columns (N > 2 and
N < 10): ");
int N = [Link]();

if (M <= 2 || M >= 10 || N <= 2 || N >= 10) {


[Link]("SIZE IS OUT OF RANGE. INVALID
ENTRY");
return;
}

int[][] matrix = new int[M][N];

[Link]("Enter elements of the matrix:");


for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = [Link]();
}
54

// Display the input matrix


[Link]("Input Matrix:");
displayMatrix(matrix, M, N);

int[][] rotatedMatrix = new int[M][N];


for (int i = 0; i < M - 1; i++) {
rotatedMatrix[i] = matrix[i + 1];
}
rotatedMatrix[M - 1] = matrix[0]; // Move the first row
to the last position

int highest = matrix[0][0];


int row = 0, col = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (matrix[i][j] > highest) {
highest = matrix[i][j];
row = i;
col = j;
}
}
}

[Link]("FORMED MATRIX AFTER ROTATING:");


displayMatrix(rotatedMatrix, M, N);
[Link]("Highest element: " + highest + "
(Row: " + row + " and Column: " + col + ")");
}
55

public static void displayMatrix(int[][] matrix, int M, int


N) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}}

Output:
56

Question 8
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 20. Allow the user to input integers into this matrix.
Perform the following tasks on the matrix:
Perform the following tasks on the matrix.
(a) Display the input matrix.
(b) Find the maximum and minimum value in the matrix and display them along
with their position
(c). Sort the elements of the matrix in descending order using any standard sorting
technique and rearrange them in the matrix.
(d) Output the rearranged matrix.
Algorithm:

1. Start
2. Input Matrix Dimensions
3. Prompt the user to input the number of rows M and columns N.
a. Ensure that both M and N are greater than 2 and less than 20.
b. If the input is invalid, display an error message and stop.
4. Input Matrix Elements
5. Initialize a 2D array matrix of size M x N.
6. Accept integers from the user for each position in the matrix.
7. Display the Input Matrix
8. Find Maximum and Minimum Values
a. Iterate through the matrix to find the maximum and minimum values
along with their positions (row and column).
9. Sort the Matrix Elements in Descending Order
[Link] all matrix elements into a 1D array.
[Link] the bubble sort algorithm to sort the array in descending order.
[Link] the Matrix
[Link] the matrix with the sorted elements from the 1D array.
[Link] the Rearranged Matrix
[Link]

Program:
import [Link];
57

class MatrixOperations {

public static void main() {


Scanner sc = new Scanner([Link]);
[Link]("Enter the number of rows (M > 2 and M
< 20): ");
int M = [Link]();
[Link]("Enter the number of columns (N > 2 and
N < 20): ");
int N = [Link]();

if (M <= 2 || M >= 20 || N <= 2 || N >= 20) {


[Link]("Invalid input. Both M and N
should be greater than 2 and less than 20.");
return;
}

int[][] matrix = new int[M][N];


int[] array = new int[M * N];
[Link]("Enter elements of the matrix:");
int index = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = [Link]();
array[index++] = matrix[i][j]; // Store
elements in a 1D array for sorting
}
}// Display the input matrix
[Link]("Input Matrix:");
displayMatrix(matrix, M, N);
58

// Find maximum and minimum values and their positions


int max = matrix[0][0], min = matrix[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 (matrix[i][j] > max) {
max = matrix[i][j];
maxRow = i;
maxCol = j;
}
if (matrix[i][j] < min) {
min = matrix[i][j];
minRow = i;
minCol = j;
}
}
}
[Link]("Maximum value: " + max + " at
position (" + maxRow + ", " + maxCol + ")");
[Link]("Minimum value: " + min + " at
position (" + minRow + ", " + minCol + ")");

bubbleSortDescending(array);

index = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = array[index++];
}
}
59

[Link]("Rearranged Matrix in Descending


Order:");
displayMatrix(matrix, M, N);
}

public static void bubbleSortDescending(int[] arr) {


int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

public static void displayMatrix(int[][] matrix, int M, int


N) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
60

Output:
61

Question 9
Write a program to declare a square matrix A[ ][ ] of order M × M where `M' is the
number of rows and the number of columns, such that M must be greater than 2
and less than 10. Accept the value of M as user input. Display an appropriate
message for an invalid input. Allow the user to input integers into this matrix.
Perform the following tasks:
1. Display the original matrix
2. Check if the given matrix is Symmetric or not

. A square matrix is said to be Symmetric, if the element of the ith row and jth
column is equal to the element of the jth row and ith column.
3. Find the sum of the elements of left diagonal and the sum of the elements of
right diagonal of the matrix and display them. Test your program for the
following data and some random data:
Example 1 INPUT: M = 3
Enter elements of 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
The sum of the left diagonal = 11
The sum of the right diagonal = 10
Example 2 INPUT: M = 12
OUTPUT: SIZE IS OUT OF RANGE
Algorithm:

1. Start
2. Input Matrix Size
3. Accept M (size of the matrix) such that 3 ≤ M < 10.
4. If M is invalid, display an error and stop.
5. Input Matrix Elements
6. Initialize matrix A[M][M].
7. Accept integer values into the matrix.
8. Display Original Matrix
9. Print the original matrix.
[Link] Symmetry
62

[Link] each element A[i][j] with A[j][i].


[Link] any pair is unequal, set a flag indicating the matrix is not symmetric.
[Link] Diagonal Sums
[Link] the sum of the left diagonal (A[i][i]) and right diagonal (A[i][M-1-
i]).
[Link] Results
[Link] if the matrix is symmetric or not.
[Link] the sums of both diagonals.
[Link]

Program:
import [Link];
public class SymmetricMatrixCheck {
public static void main() {
Scanner sc = new Scanner([Link]);

[Link]("Enter the size of the matrix (M > 2


and M < 10): ");
int M = [Link]();

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


[Link]("Invalid input. M should be
greater than 2 and less than 10.");
return;
}

int[][] matrix = new int[M][M];

[Link]("Enter elements of the matrix:");


for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = [Link]();
63

}
}

[Link]("Original Matrix:");
displayMatrix(matrix, M);

boolean isSymmetric = true;


for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
if (matrix[i][j] != matrix[j][i]) {
isSymmetric = false;
break;
}
}
}

if (isSymmetric) {
[Link]("THE GIVEN MATRIX IS SYMMETRIC");
} else {
[Link]("THE GIVEN MATRIX IS NOT
SYMMETRIC");
}

// Calculate the sum of left diagonal and right diagonal


int leftDiagonalSum = 0, rightDiagonalSum = 0;
for (int i = 0; i < M; i++) {
leftDiagonalSum += matrix[i][i]; //
Left diagonal elements
rightDiagonalSum += matrix[i][M - 1 - i]; //
Right diagonal elements
}
64

[Link]("The sum of the left diagonal = " +


leftDiagonalSum);
[Link]("The sum of the right diagonal = " +
rightDiagonalSum);
}
public static void displayMatrix(int[][] matrix, int M) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}

Output:
65

String Programs
Question 1:
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.

Algorithm:

1. Start

2. Input Sentence

3. Accept a sentence that ends with either '.', '?' or '!'.

4. If the sentence does not end with them, send an error message.

5. Extract Words

6. Remove the terminating character from the sentence.

7. Split the sentence into words.

8. Sort Words

9. Sort the words in ascending order of their length.

[Link] two or more words have the same length, sort them alphabetically.

[Link] Results

[Link] the original sentence.

[Link] the sorted sentence with the original terminating character.


66

[Link]

Program:
import [Link];

public class SentenceSorter {

public static void main() {

Scanner sc = new Scanner([Link]);

[Link]("Enter a sentence ending with '.', '?'


or '!': ");

String sentence = [Link]();

// Check if the sentence ends with a valid terminating


character

char lastChar = [Link]([Link]() - 1);

if (lastChar != '.' && lastChar != '?' && lastChar !=


'!') {

[Link]("Invalid sentence. Must end with


'.', '?' or '!'.");

return;

// Remove the terminating character and split the


sentence into words

String[] words = [Link](0, [Link]()


- 1).split(" ");
67

for (int i = 0; i < [Link] - 1; i++) {

for (int j = 0; j < [Link] - 1 - i; j++) {

if (words[j].length() > words[j + 1].length() ||

(words[j].length() == words[j + 1].length()


&& words[j].compareTo(words[j + 1]) > 0)) {

// Swap words if the current word is longer


or alphabetically larger

String temp = words[j];

words[j] = words[j + 1];

words[j + 1] = temp;

[Link]("Original Sentence: " + sentence);

[Link]("Sorted Sentence: ");

for (String word : words) {

[Link](word + " ");

[Link](lastChar);

}
68

Output
69

Question 2:

Caesar Cipher is an encryption technique which is implemented as ROT13 ('rotate


by 13 places'). It is a simple letter substitution cipher that replaces a letter with the
letter 13 places after it in the alphabets, with the other characters remaining
unchanged.

Write a program to accept a plain text of length L, where L must be greater than 3
and less than 100. Encrypt the text if valid as per the Caesar Cipher.
Algorithm:

1. Start

2. Input Plain Text

3. Accept a plain text of length L.


4. Check if L is greater than 3 and less than 100.

5. If L is invalid, display an error and stop.


6. Encrypt Text

7. For each character in the text:

a. If the character is a letter:


b. Replace it with the letter 13 places after it in the alphabet.
c. Wrap around to the start of the alphabet if necessary.
d. If the character is not a letter, leave it unchanged.

8. Display Encrypted Text


9. Print the encrypted text.

[Link]

Program
import [Link];

public class CaesarCipher {

public static void main() {


70

Scanner sc = new Scanner([Link]);

[Link]("Enter plain text (length 3-100):");

String plainText = [Link]();

if ([Link]() <= 3 || [Link]() >= 100) {

[Link]("Invalid input length.");

return;

StringBuilder cipherText = new StringBuilder();

for (char c : [Link]()) {

if (c >= 'a' && c <= 'z') { //to replace the


letters

[Link]((char) ((c - 'a' + 13) % 26 +


'a'));

} else if (c >= 'A' && c <= 'Z') {

[Link]((char) ((c - 'A' + 13) % 26 +


'A'));

} else {

[Link](c);

}}

//printing new text

[Link]("The cipher text is: " + cipherText);

}}

Output:
71
72

Question 3:

Write a program to accept a sentence which may be terminated by either '.', '?' or '!'
only. The words may be separated by more than one blank space and are in
UPPER CASE.

Perform the following tasks:


1. Find the number of words beginning and ending with a vowel.
2. Place the words which begin and end with a vowel at the beginning,
followed by the remaining words as they occur in the sentence.

Algorithm:
1. Start
2. Input Plain Text
3. Accept a plain text of length L.
4. Check if L is greater than 3 and less than 100.
5. If L is invalid, display an error and stop.
6. Encrypt Text
7. For each character in the text:
a. If the character is a letter:
b. Replace it with the letter 13 places after it in the alphabet.
c. Wrap around to the start of the alphabet if necessary.
d. If the character is not a letter, leave it unchanged.
8. Display Encrypted Text
9. Print the encrypted text.
[Link]

Program

import [Link];

public class VowelWordSorter {

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter a sentence ending with '.', '?'


or '!': ");
73

String sentence = [Link]().trim();

char lastChar = [Link]([Link]() - 1);


if (lastChar != '.' && lastChar != '?' && lastChar !=
'!') {
[Link]("Invalid sentence. Must end with
'.', '?' or '!'.");
return;
}

sentence = [Link](0, [Link]() -


1).trim() + " ";

String word = "", vowelWords = "", otherWords = "";


int vowelWordCount = 0;

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

if (ch == ' ') {


if (![Link]()) {
char firstChar = [Link](0);
char lastCharWord =
[Link]([Link]() - 1);

// Check if the word begins and ends with a


vowel
if (isVowel(firstChar) &&
isVowel(lastCharWord)) {
vowelWords += word + " ";
vowelWordCount++;
} else {
otherWords += word + " ";
}

// Reset the word to process the next one


word = "";
}
} else {
// Build the word one character at a time
word += ch;
}
}

// Display the number of words beginning and ending with


vowels
74

[Link]("Number of words beginning and ending


with a vowel = " + vowelWordCount);

// Display the combined vowel words followed by other


words
[Link](vowelWords + [Link]() +
lastChar);
}

public static boolean isVowel(char ch) {


return "AEIOU".indexOf(ch) != -1;
}
}
Output:
75

Question 4:

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).

Algorithm

1. Start

2. Input Number of Teams

3. Accept the number of teams, N.

4. Check if 2 < N < 9.


5. If N is invalid, display an error and stop.

6. Input Team Names


7. Accept the names of N teams.

8. Determine the maximum length of the team names.

9. Display Vertically

[Link] each character position from 0 to the maximum length:

For each team:


a. Print the character at the current position if it exists, otherwise print a spa
ce.
b. Print a horizontal tab after each character from each team.

[Link]

Program
76

import [Link];

public class VerticalTeams {

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the number of teams (2 < N < 9):


");
int N = [Link]();
[Link]();

if (N <= 2 || N >= 9) {
[Link]("Invalid number of teams.");
return;
}

String[] teams = new String[N];

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


[Link]("Team " + (i + 1) + ": ");
//printing team names
teams[i] = [Link]();
}

int maxLen = 0;
for (String team : teams) {
maxLen = [Link](maxLen, [Link]());
}

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


for (int j = 0; j < N; j++) {
if (i < teams[j].length()) {
[Link](teams[j].charAt(i));
//printing for the banners
} else {
[Link](" ");
}
[Link]("\t");
}
[Link]();
}
}}
Output:
77
78

Question 5:

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:
Convert the non-palindrome words of the sentence into palindrome words by
concatenating the word by its reverse (excluding the last character).

Algorithm:

1. Start

2. Input Sentence

3. Validate Sentence
4. Accept sentence with either '.', '?' or '!', and ensure it is in upper case

5. Check if the sentence ends with a valid terminating character ('.', '?', '!').

6. If invalid, display an error and stop.


7. Process Words

8. Split the sentence into words.


9. For each word:

a. Check if the word is a palindrome.


[Link] it is not a palindrome, convert it by concatenating the word with its rever
e (excluding the last character).
[Link] Sentence

[Link] the words back into a sentence.

[Link] the terminating character back.


[Link] Result

[Link] the modified sentence.

[Link]
79

Program
import [Link];

public class PalindromeConverter {

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter a sentence ending with '.', '?'


or '!': ");
String sentence = [Link]().trim();

char lastChar = [Link]([Link]() - 1);


if (lastChar != '.' && lastChar != '?' && lastChar !=
'!') {
[Link]("Invalid sentence. Must end with
'.', '?' or '!'.");
return;
}

sentence = [Link](0, [Link]() -


1).trim() + " ";

String word = "", result = "";

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

if (ch == ' ') {


if (![Link]()) {

boolean isPalindrome = true;


int len = [Link]();
for (int j = 0; j < len / 2; j++) {
if ([Link](j) != [Link](len -
j - 1)) {
isPalindrome = false;
break;
}
}

// If the word is not a palindrome, convert


it into a palindrome
80

if (!isPalindrome) {
String reverse = "";
for (int j = len - 2; j >= 0; j--) {
reverse += [Link](j);
}
result += word + reverse + " ";
} else {
result += word + " "; // Keep the
palindrome word as is
}

word = ""; // Reset word to process the


next one
}
} else {
word += ch; // Build the word character by
character
}
}

[Link]("Transformed Sentence: " +


[Link]() + lastChar);
}
}
Output:
81
82

Question 6:

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. Print an error message
if the input does not terminate with ‘.’ or ‘?’.

Perform the following tasks:

1. Convert the first letter of each word to uppercase.


2. Find the number of vowels and consonants in each word and display them with
proper headings along with the words.

Algorithm
1. Start
2. Input Sentence
3. Accept a sentence ending with either '.' or '?'.
4. Check if the sentence ends with a valid terminating character ('.' or '?').
5. If invalid, display an error message and stop.
6. Process Words
7. Split the sentence into words.
8. For each word:
• Convert the first letter to uppercase.
• Count the number of vowels and consonants.
9. Display Results
[Link] each word with its first letter capitalized.

[Link] the number of vowels and consonants for each word with proper headings.
[Link]

Program
import [Link];

public class SentenceProcessor {

public static void main() {


83

Scanner sc = new Scanner([Link]);

// Input: Accept a sentence

[Link]("Enter a sentence ending with '.' or


'?': ");

String sentence = [Link]().trim();

// Check if the sentence ends with a valid terminating


character

char lastChar = [Link]([Link]() - 1);

if (lastChar != '.' && lastChar != '?') {

[Link]("Invalid sentence. Must end with


'.' or '?'.");

return;

// Remove the terminating character for processing

sentence = [Link](0, [Link]() -


1).trim() + " ";

String word = "";

[Link]("Word\tVowels\tConsonants");

for (int i = 0; i < [Link](); i++) {


84

char ch = [Link](i);

// When a space is encountered, process the word

if (ch == ' ') {

if (![Link]()) {

// Convert the first letter to uppercase

word = [Link](0, 1).toUpperCase() +


[Link](1).toLowerCase();

// Count vowels and consonants

int vowels = 0, consonants = 0;

for (int j = 0; j < [Link](); j++) {

char letter = [Link](j);

if ("AEIOUaeiou".indexOf(letter) != -1)
{

vowels++;

} else if ([Link](letter)) {

consonants++;

[Link](word + "\t" + vowels +


"\t" + consonants);

word = "";
85

} else {

word += ch; }}}}

Output:
86

Question 7
Write a program that prints a series of Fibonacci strings
["a","b","ba","bab","babba" pattern]
Algorithm

1. Start

2. Initialize

3. Set the first two strings: S0 = "a" and S1 = "b".

4. Input Number of Terms

5. Accept the number of terms, N, to generate in the series.

6. Generate Series

7. Use a loop to generate the next terms:

a. For each term from 2 to N-1:


b. Concatenate the two previous strings to form the next string.

8. Display Series

9. Print each string in the series.

[Link]

Program
import [Link];

public class FibonacciStrings {

public static void main() {

Scanner sc = new Scanner([Link]);


87

[Link]("Enter the number of terms for


Fibonacci string series: ");

int n = [Link]();

// Initialize the first two Fibonacci strings

String fib1 = "a";

String fib2 = "b";

// Print the first term if n is at least 1

if (n >= 1) {

[Link](fib1 + " ");

// Print the second term if n is at least 2

if (n >= 2) {

[Link](fib2 + " ");

for (int i = 3; i <= n; i++) {

String nextFib = fib2 + fib1; // Fibonacci string


logic

[Link](nextFib + " ");


88

fib1 = fib2; // Move to the next Fibonacci string

fib2 = nextFib;

[Link]();

Output:
89

Question 8
WAP in java to swap first and last letter of each word, and arranging characters of
word in alphabetical order

Algorithm:

1. Start
2. Input the Sentence
a. Accept a sentence input from the user.
b. Add a space at the end of the sentence to ensure the last word is
processed.
3. Initialize Variables
a. Create an empty string word to store each word in the sentence.
b. Process Each Character
Loop through each character in the sentence.
If a space is encountered:
a. Check if word is non-empty.
b. If the first character of word is an uppercase letter, print the word.
c. Reset word to an empty string.
4. If the character is not a space, append it to word.
5. Display Capital Letter Words
a. Print all words that start with a capital letter.
6. Stop

Program:
import [Link];

public class CapitalLetterCheck {

public static void main() {

Scanner sc = new Scanner([Link]);

[Link]("Enter a sentence: ");


90

String sentence = [Link]().trim() + " ";

String word = "";

[Link]("Words beginning with a capital


letter:");

// Process the sentence character by character

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

if (ch == ' ') {

if (![Link]()) {

if ([Link]([Link](0))) {

[Link](word); // Print the


word if it starts with a capital letter

word = "";

} else {

word += ch; }}}}


91

Output:
92

Call By Reference
Question 1:

Write a program to merge two sorted arrays in ascending order.

Algorithm
1. Start

2. Input Arrays
3. Accept two sorted arrays, A and B.

4. Initialize Pointers

5. Set two pointers, i and j, to 0 (for array A and array B respectively).

6. Merge Arrays
7. Create an empty array, C, to store the merged result.
8. While both pointers are within the bounds of their respective arrays:

[Link] the elements at A[i] and B[j].

[Link] the smaller element to C and increment the corresponding pointer.


9. If any elements are left in array A, append them to C.
[Link] any elements are left in array B, append them to C.

[Link] Result

[Link] the merged array, C.


[Link]

Program
import [Link];

public class MergeSortedArrays {


93

public static void mergeArrays(int[] arr1, int n1, int[]


arr2, int n2, int[] merged) {
int i = 0, j = 0, k = 0;

while (i < n1 && j < n2) {


if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}

while (i < n1) {


merged[k++] = arr1[i++];
}

while (j < n2) {


merged[k++] = arr2[j++];
}
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the size of the first sorted


array: ");
int n1 = [Link]();
int[] arr1 = new int[n1];
[Link]("Enter the elements of the first
sorted array:");
for (int i = 0; i < n1; i++) {
94

arr1[i] = [Link]();
}

[Link]("Enter the size of the second sorted


array: ");
int n2 = [Link]();
int[] arr2 = new int[n2];
[Link]("Enter the elements of the second
sorted array:");
for (int i = 0; i < n2; i++) {
arr2[i] = [Link]();
}

int[] merged = new int[n1 + n2];

// Call by reference to merge the arrays


mergeArrays(arr1, n1, arr2, n2, merged);

[Link]("Merged sorted array:");


for (int i = 0; i < [Link]; i++) {
[Link](merged[i] + " ");
}
[Link]();
}}
95

Output:
96

Question 2
Write a program to add two time intervals.
Algorithm:

1. Start
2. Input Time Intervals
a. Accept the first time interval (hours and minutes) as an integer array
time1[].
b. Accept the second time interval (hours and minutes) as an integer array
time2[].
3. Add Minutes and Hours
a. Add the minutes of both intervals and store in result[1].
b. Add the hours of both intervals and the carryover from minutes (if
minutes exceed 60) into result[0].
4. Adjust Minutes
a. If minutes exceed 59, adjust the minutes using modulo 60.
5. Display Result
a. Print the total time in hours and minutes format.
6. Stop

Program:

import [Link];

public class TimeAddition {

public static void addTime(int[] time1, int[] time2, int[]


result) {
result[1] = time1[1] + time2[1]; // Add minutes
result[0] = time1[0] + time2[0] + result[1] / 60; // Add
hours and carry over if minutes exceed 60
result[1] = result[1] % 60; // Adjust minutes to be
within 0-59 range
}
97

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the first time interval (hours


and minutes): ");
int[] time1 = new int[2];
time1[0] = [Link]();
time1[1] = [Link]();

[Link]("Enter the second time interval (hours


and minutes): ");
int[] time2 = new int[2];
time2[0] = [Link]();
time2[1] = [Link]();

int[] result = new int[2];

// Call by reference to add the time intervals


addTime(time1, time2, result);

// Output the added time interval


[Link]("Total Time: " + result[0] + " hours
and " + result[1] + " minutes");
}}
98

Output:
99

Question 3:
Write a program to reverse the elements of a double dimensional array with integer
elements.
Algorithm
1. Start
2. Input Array Dimensions
3. Accept the dimensions of the 2D array, M x N.
4. Initialize Array
5. Accept integer values into the array.
6. Reverse Elements
7. Create a new 2D array to store the reversed elements.
8. Reverse the elements row by row and column by column:
[Link] each element in the original array at position (i, j), place it in the new a
rray at position (M-1-i, N-1-j).
9. Display Reversed Array
[Link] the reversed array.
11. Stop

Program
import [Link];

public class Reverse2DArray {

public static void reverseArray(int[][] arr, int rows, int


cols) {
int start = 0;
int end = rows * cols - 1;

while (start < end) {


100

int rowStart = start / cols;


int colStart = start % cols;
int rowEnd = end / cols;
int colEnd = end % cols;

// Swap the elements at start and end positions


int temp = arr[rowStart][colStart];
arr[rowStart][colStart] = arr[rowEnd][colEnd];
arr[rowEnd][colEnd] = temp;

start++;
end--;
}
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows: ");


int rows = [Link]();
[Link]("Enter the number of columns: ");
int cols = [Link]();

int[][] arr = new int[rows][cols];

[Link]("Enter the elements of the matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = [Link]();
}
101

// Call by reference to reverse the array


reverseArray(arr, rows, cols);

[Link]("Reversed Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](arr[i][j] + " ");
}
[Link]();
}}}
102

Output:
103

Question 4
WAP to rotate all elements of an integer Double Dimensional Array by 90.

Algorithm:

1. Start
2. Input Matrix Size
a. Accept the number of rows (rows) and columns (cols) from the user.
b. If the input values are invalid (out of range), display an error message
and terminate the program.
3. Input Matrix Elements
a. Initialize a 2D array arr[rows][cols].
b. Input values for each element in the matrix.
4. Shift Rows Up
5. Store the first row in a temporary array firstRow.
6. For each row from the second row to the last row, shift the row up by
copying it to the previous row's position.
7. Move the original first row to the last row.
8. Display the Updated Matrix
Print the modified matrix after performing the row shift.
9. Stop

Program:
import java,util,*;
public class ShiftRowsUp {

public static void shiftRowsUp(int[][] arr, int rows, int


cols) {
int[] firstRow = arr[0];
// Shift all rows up by one
for (int i = 0; i < rows - 1; i++) {
arr[i] = arr[i + 1]; // Move each row to the
previous position
}
104

// Place the first row at the last position


arr[rows - 1] = firstRow;
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows: ");


int rows = [Link]();
[Link]("Enter the number of columns: ");
int cols = [Link]();

int[][] arr = new int[rows][cols];

[Link]("Enter the elements of the matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = [Link]();
}
}

// Call by reference to shift the rows up


shiftRowsUp(arr, rows, cols);

[Link]("Matrix after shifting rows up:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](arr[i][j] + " ");
}
[Link]();
105

}}}

Output:
106

Question 5
Write a program to check if two matrices are equal, or not.
Algorithm
1. Start
2. Input Matrices
3. Accept two matrices, A and B, of the same dimensions.
4. Check Dimensions
5. Verify that the dimensions of the matrices are the same.
6. If the dimensions are not same then print error message.
7. Compare Elements
8. For each element in the matrices:
a. Compare the corresponding elements of A and B.
b. If any pair is not equal print error message.
9. If all corresponding elements are equal, print that the matrices are equal.
[Link]
Program:
import [Link];

public class MatrixEquality {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input dimensions of the matrices


[Link]("Enter the number of rows: ");
int rows = [Link]();
[Link]("Enter the number of columns: ");
int cols = [Link]();
107

int[][] matrixA = new int[rows][cols];


int[][] matrixB = new int[rows][cols];

// Input elements of matrix A


[Link]("Enter the elements of matrix A:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrixA[i][j] = [Link]();
}
}

// Input elements of matrix B


[Link]("Enter the elements of matrix B:");
for (int i = 0; j < rows; i++) {
for (int j = 0; j < cols; j++) {
matrixB[i][j] = [Link]();
}
}

// Check if the matrices are equal


boolean isEqual = true;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrixA[i][j] != matrixB[i][j]) {
isEqual = false;
break;
}
}
if (!isEqual) break;
}
108

// Display the result


if (isEqual) {
[Link]("The matrices are equal.");
} else {
[Link]("The matrices are not equal.");
}}}

Output:
109

Recursion:
Question 1:
WAP to search a number using binary search. Use recursive technique.
Algorithm:

1. Start
2. Input the Size and Elements of the Array
3. Input the Target Element
a. Accept the target element to search for in the array.
4. Perform Binary Search
a. Call the recursive function binarySearch(arr, left, right, target) with left =
0 and right = n - 1.
b. If the target is found at arr[mid], return the index.
c. If arr[mid] is greater than the target, recursively search the left subarray.
d. If arr[mid] is smaller, recursively search the right subarray.
e. If left > right, return -1 indicating the target is not found.
5. Output the Result
a. If the binary search function returns -1, print "Element not present."
b. Otherwise, print the index of the target element.
6. Stop

Program:
import [Link];

public class BinarySearchRecursion {

public static int binarySearch(int[] arr, int left, int


right, int target) {
if (right >= left) {
int mid = left + (right - left) / 2;
//binary search logic

if (arr[mid] == target)
return mid;
110

if (arr[mid] > target)


return binarySearch(arr, left, mid - 1, target);

return binarySearch(arr, mid + 1, right, target);


}
return -1; //end recursion
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the size of the array: ");


int n = [Link]();
int[] arr = new int[n];

[Link]("Enter elements of the sorted


array:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

[Link]("Enter the element to search: ");


int target = [Link]();

int result = binarySearch(arr, 0, n - 1, target);

if (result == -1)
[Link]("Element not present in the
array.");
else
111

[Link]("Element found at index " +


result);
}

Output:
112

Question 2
WAP to check if the number is Dudney number using recursive technique.
Algorithm:
1. Start
2. Input Number
3. Accept an integer number from the user.
4. Process Number
5. While the number has more than one digit:
a. Calculate the sum of the digits of the number.
b. Replace the number with this sum.
6. Check Result
7. If the final number is 1, it is a Dudney Number.
8. Otherwise, it is not a Dudney Number.
9. Display Result
[Link] whether the number is a Dudney Number or not.
[Link]

Program
import [Link].*;
public class NumDude
{
int num;
public NumDude()
{
num=0;
}
public void input()
{
Scanner in=new
Scanner([Link]);
[Link]("Enter a
number:"); num=[Link]();
}
113

public int sumDigits(int x)


{
if(x==
0)
return
0;
else
return x%10+sumDigits(x/10); //recursion
}
public void isDude()
{
int n=sumDigits(num);
//logic of dudney number
if(n*n*n==num)
[Link](“Dudney
Number”);
else
[Link]("Not a Dudeney Number");
}
public static void main()
{
NumDude obj=new
NumDude(); [Link]();
[Link]();
}}

Output:
114

Question 3:
WAP to check if the number is an Armstrong number[sum of squares of digits is
equal to the original number] using recursive technique.
Algorithm:
1. Start
2. Input Number
3. Accept an integer number from the user.
4. Calculate Number of Digits
5. Determine the number of digits in the number.
6. Compute Armstrong Condition
7. Initialize a sum variable to 0.
8. For each digit in the number:
a. Raise the digit to the power of the number of digits.
b. Add this value to the sum
9. Check Result
[Link] the sum is equal to the original number, it is an Armstrong Number.
[Link], it is not an Armstrong Number.
[Link] Result
[Link] whether the number is an Armstrong Number or not.
[Link]
Program
import [Link];
public class ArmstrongNumber {

public static boolean isArmstrong(int num) {


int digits = countDigits(num);
return num == armstrongHelper(num, digits);
}

public static int armstrongHelper(int num, int digits) {


if (num == 0)
return 0;
//recursive method
115

return (int) [Link](num % 10, digits) +


armstrongHelper(num / 10, digits);
}

public static int countDigits(int num) {


if (num == 0)
return 0;
return 1 + countDigits(num / 10);
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

if (isArmstrong(num)) //comparing with condition


[Link](num + " is an Armstrong
number.");
else
[Link](num + " is not an Armstrong
number.");
}}
116

Output:
117

Question 4:
WAP to check if the number is an Disarium number[sum of digits to the power of
their respective position is equal to the original number] using recursive technique.
Algorithm:

1. Start
2. Input the Number
a. Accept an integer num from the user.
3. Count the Digits
[Link] a recursive function countDigits(num) to determine the number of
digits in the given number.
4. Calculate the Disarium Value
[Link] a recursive function calculateDisarium(num, digits) that
calculates the sum of each digit raised to the power of its respective position
in the number.
5. Compare and Output
[Link] the result of the Disarium calculation with the original number.
[Link] they are equal, print that the number is a Disarium number.
[Link], print that it is not.
6. Stop

Program
import [Link];

public class DisariumNumber {

public static int calculateDisarium(int num, int power) {


if (num == 0) {
return 0;
}
return (int) [Link](num % 10, power) +
calculateDisarium(num / 10, power - 1);
}
118

public static int countDigits(int num) {


if (num == 0) {
return 0;
}
return 1 + countDigits(num / 10);
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

int digits = countDigits(num);

// Call the recursive function to calculate the sum


int result = calculateDisarium(num, digits);

if (result == num) {
[Link](num + " is a Disarium number.");
} else {
[Link](num + " is not a Disarium
number.");
}}}
119

Output:
120

Question 5:
WAP to calculate the sum of a given series: ((x2)/(1!))+((x4)(3!))+ ((x6)/(5!))+...+
((xn)/((n-1)!)), using recursive technique
Algorithm:
1. Start
2. Input Value of x and n
3. Accept the values of x and n from the user.
4. Define Recursive Function
5. Implement a recursive function to calculate the sum of the series.
6. Base Case
7. If the term is zero, return 0.
8. Recursive Case
9. Calculate the current term using
[Link] the current term to the sum of the series for the remaining terms.
[Link] Series Sum
[Link] the recursive function with initial parameters.
[Link] Result
[Link] the calculated sum of the series.
[Link]
Program
import [Link];
public class SeriesSum {

public static double seriesSum(int x, int n) {


if (n < 2)
return 0;
//calculating sum
return [Link](x, n) / factorial(n - 1) + seriesSum(x,
n - 2);
121

public static int factorial(int num) {


if (num == 0 || num == 1)
return 1;
//finding factorial using recursion
return num * factorial(num - 1);
}

public static void main() {


Scanner sc = new Scanner([Link]);

[Link]("Enter the value of x: ");


int x = [Link]();

[Link]("Enter the value of n: ");


int n = [Link]();

double result = seriesSum(x, n);


[Link]("Sum of the series: " + result);
}}
122

Output:
123

Data Structures
Question 1:

Define a class CardGame with the following details:

Class name: CardGame

Data members/Instance variables:


1. cards[]: An array to store integers as cards.
2. cap: An integer to store the maximum capacity of the array.
3. top: An integer to store the index of the topmost element of the array.

Methods/Member functions:

1. CardGame(int cc): A constructor to initialize cap = cc and top = -1, and


create the integer array cards[].
2. void addCard(int v): To add the card at the top index if possible, otherwise
display the message "CARD PILE IS FULL".
3. int drawCard(): To remove and return the card from the top index of the card
pile, if any, else return the value -9999.
4. void display(): To display all the cards in the card pile.

Specify the class CardGame giving the details of the above functions. Define a
main() function to create an object and call all the functions accordingly to enable
the task.

Algorithm:
1. Start
2. Initialize: Create the CardGame class with variables cards[], cap, and top.
3. Constructor: Initialize cap and top = -1.
4. Add a Card: Check if the pile is full; if not, add the card and update top.
5. Draw a Card: Check if the pile is empty; if not, return the top card and
decrement top.
6. Display: Show all cards from 0 to top.
7. Stop
124

Program:
class CardGame {
private int[] cards;
private int cap;
private int top;
// Constructor to initialize the capacity and set top to -1
(empty pile)
public CardGame(int cc) {
cap = cc;
cards = new int[cap];
top = -1;
}

public void addCard(int v) {


if (top == cap - 1) {
[Link]("CARD PILE IS FULL");
} else {
cards[++top] = v;
[Link]("Added card: " + v);
}
}

public int drawCard() {


if (top == -1) {
[Link]("CARD PILE IS EMPTY");
return -9999; // Return -9999 if no cards in pile
} else {
return cards[top--];
}
125

public void display() {


if (top == -1) {
[Link]("CARD PILE IS EMPTY");
} else {
[Link]("Cards in pile: ");
for (int i = 0; i <= top; i++) {
[Link](cards[i] + " ");
}
[Link]();
}
}

public static void main() {


CardGame game = new CardGame(5);

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

// Try adding another card to check if the pile is full


[Link](60);

// Display current state of the card pile


[Link]();

[Link]("Drew card: " + [Link]());


126

[Link]();

[Link]("Drew card: " + [Link]());

[Link]();
}}

Output:
127

Question 2:
A Queue is a linear data structure in which operations are performed based on the
FIFO(First In First Out) principle.

Define a class Queue with the following details:

Class name:Queue
Data members/Instance variables:

1. dat[]: Array to hold the integer elements.


2. cap: Stores the maximum capacity of the queue.
3. front: To point the index of the front.
4. rear: To point the index of the rear.
Member functions/methods:

1. Queue(int max): Constructor to initialize the data member cap = max, front =
rear = 0, and create the integer array.
2. void add_dat(int v): To add integers from the rear index if possible, else
display the message "Queue full".
3. int pop_dat(): To remove and return elements from the front, if any, else
returns -999.
4. void display(): To display the elements of the queue.
Specify the class Queue giving the details of void add_dat(int) and int pop_dat().
Assume that the other functions have been defined.
Algorithm:
1. Start
2. Create a class Queue with variables dat[], cap, front, and rear.
3. Initialize in the constructor with front = rear = 0.
4. Add data: Add element at rear and increment rear, print "Queue full" if full.
5. Pop data: Return element at front and increment front, print "Queue empty"
if empty.
6. Display: Print all elements between front and rear.
7. Call the methods to add, remove, and display data.
8. Stop.

Program
128

import [Link];

class Queue {
int[] dat;
int cap;
int front;
int rear;

public Queue(int max) {


cap = max;
dat = new int[cap];
front = rear = 0;
}

public void add_dat(int v) {


if (rear == cap) {
[Link]("Queue full");
} else {
dat[rear++] = v; // Add element at rear and
increment rear
[Link]("Added: " + v);
}
}

public int pop_dat() {


if (front == rear) {
[Link]("Queue empty");
return -999;
} else {
int value = dat[front++]; // Remove element at
front and increment front
129

return value;
}
}

public void display() {


if (front == rear) {
[Link]("Queue is empty");
} else {
[Link]("Queue elements: ");
for (int i = front; i < rear; i++) {
[Link](dat[i] + " ");
}
[Link]();
}
}

public static void test() {


Scanner sc = new Scanner([Link]);
[Link]("Enter the maximum capacity of the
queue: ");
int size = [Link]();

Queue q = new Queue(size);

q.add_dat(10);
q.add_dat(20);
q.add_dat(30);

[Link]();
130

[Link]("Removed: " + q.pop_dat());

[Link]();
}
}

Output:
131

Question 3:
A double-ended queue (deQueue) is a linear data structure that enables the user to
add and remove integers from either end, i.e., from the front or rear.
The details of the class `deQueue` are given below:
Class name: `deQueue`
Data members/instance variables:
1. `Qm[]`: Array to hold integer elements.
2. `lim`: Integer to store the maximum capacity of the deQueue.
3. `front`: Integer to point to the index of the front end.
4. `rear`: Integer to point to the index of the rear end.
Methods/Member functions:
1. `deQueue(int l)`: Constructor to initialize `lim = l`, `front = 0`, and `rear = 0`.
2. `void addFront(int v)`: To add integers in the deQueue at the front end if
possible, otherwise display the message "OVERFLOW FROM FRONT".
3. `void addRear(int v)`: To add integers in the deQueue at the rear end if possible,
otherwise display the message "OVERFLOW FROM REAR".
4. `int popFront()`: Removes and returns the integers from the front end of the
deQueue if any, else returns `-999`.
5. `int popRear()`: Removes and returns the integers from the rear end of the
deQueue if any, else returns `-999`.
6. `void show()`: Displays the elements of the deQueue.
Spicify a class `deQueue` giving the details of the above functions. Define a
`main()` function to create an object and call all the functions accordingly to enable
the task.

Algorithm:
1. Start
2. Initialize deQueue with lim (capacity), front and rear as -1.
3. addFront():
[Link] for overflow.
132

[Link] the value at the front.


4. addRear():
[Link] for overflow.
[Link] the value at the rear.
5. popFront():
[Link] if queue is empty.
[Link] and return value at front.
6. popRear():
[Link] if queue is empty.
[Link] and return value at rear.
7. show():
8. Display elements in the queue.
9. Stop

Program
import [Link];

class deQueue {
private int[] Qm;
private int lim;
private int front;
private int rear;

public deQueue(int l) {
lim = l;
Qm = new int[lim];
front = -1; // Front set to -1, indicating an empty
queue
rear = -1; // Rear set to -1, indicating an empty
queue
}

public void addFront(int v) {


133

if (front == 0 && rear == lim - 1 || front == rear + 1)


{
[Link]("OVERFLOW FROM FRONT");
} else if (front == -1) {
front = rear = 0;
Qm[front] = v;
} else if (front == 0) {
front = lim - 1;
Qm[front] = v;
} else {
Qm[--front] = v;
}
}

public void addRear(int v) {


if (front == 0 && rear == lim - 1 || front == rear + 1)
{
[Link]("OVERFLOW FROM REAR");
} else if (rear == -1) {
front = rear = 0;
Qm[rear] = v;
} else if (rear == lim - 1) {
rear = 0;
Qm[rear] = v;
} else {
Qm[++rear] = v;
}
}

public int popFront() {


if (front == -1) {
134

[Link]("DEQUEUE IS EMPTY FROM FRONT");


return -999;
}
int value = Qm[front];
if (front == rear) {
front = rear = -1;
} else if (front == lim - 1) {
front = 0; // Wrap front to the beginning
} else {
front++;
}
return value;
}

public int popRear() {


if (rear == -1) {
[Link]("DEQUEUE IS EMPTY FROM REAR");
return -999;
}
int value = Qm[rear];
if (front == rear) { // Queue becomes empty after
removing
front = rear = -1;
} else if (rear == 0) {
rear = lim - 1; // Wrap rear to the end
} else {
rear--;
}
return value;
}
135

public void show() {


if (front == -1) {
[Link]("DEQUEUE IS EMPTY");
} else {
[Link]("Elements in dequeue: ");
if (front <= rear) {
for (int i = front; i <= rear; i++) {
[Link](Qm[i] + " ");
}
} else {
for (int i = front; i < lim; i++) {
[Link](Qm[i] + " ");
}
for (int i = 0; i <= rear; i++) {
[Link](Qm[i] + " ");
}
}
[Link]();
}
}

public static void main() {


deQueue dq = new deQueue(5);

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]();
136

[Link]();
[Link]();
[Link]();
}}

Output:
137

Question 4
A Circular queue is a linear data structure that works on the principle of FIFO. It
enables the user to enter data from the rear end and remove data from the front end
with the rear end connected to the front end to form a circular pattern.

Define a class CirQueue with the following details:


Class name: CirQueu
Data members/Instance variables:
1. cq[]: Array to store the integers.
2. cap: Stores the maximum capacity of the array.
3. front: To point the index of the front end.
4. rear: To point the index of the rear end.

Member functions:
1. CirQueue(int max): Constructor to initialize `cap = max`, `front = -1`, and `rear
= -1`.
2. void push(int n): To add an integer in the queue from the rear end if possible,
otherwise display the message "QUEUE IS FULL".
3. int pop(): Removes and returns the integer from the front end of the queue if
any, else returns `-9999`.
4. void show(): Displays the queue elements.
Specify a class CirQueue giving the details of the above functions. Define a main()
function to create an object and call all the functions accordingly to enable the task.

Algorithm:
1. Start
2. Initialize a circular queue with size cap, front and rear as -1.
3. push():
[Link] for overflow.
[Link] the value at the rear position.
138

4. pop():
[Link] if the queue is empty.
[Link] and return the element at front.
5. show():
[Link] elements from the circular queue in the correct order.
6. Stop
Program
import [Link];
class CirQueue {
private int[] cq;
private int cap;
private int front;
private int rear;

public CirQueue(int max) {


cap = max;
cq = new int[cap];
front = -1;
rear = -1;
}

public void push(int n) {


if ((rear + 1) % cap == front) { // Circular queue is
full
[Link]("QUEUE IS FULL");
} else {
if (front == -1) { // If the queue is empty
front = 0;
}
rear = (rear + 1) % cap;
cq[rear] = n;
[Link]("Added: " + n);
139

}
}

public int pop() {


if (front == -1) {
[Link]("QUEUE IS EMPTY");
return -9999;
}
int value = cq[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % cap;
}
return value;
}

public void show() {


if (front == -1) {
[Link]("QUEUE IS EMPTY");
} else {
[Link]("Queue elements: ");
if (rear >= front) {
for (int i = front; i <= rear; i++) {
[Link](cq[i] + " ");
}
} else {
for (int i = front; i < cap; i++) {
[Link](cq[i] + " ");
140

}
for (int i = 0; i <= rear; i++) {
[Link](cq[i] + " ");
}
}
[Link]();
}
}

public static void main() {


CirQueue queue = new CirQueue(5);

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]();

[Link](50);
[Link]();

[Link](60);

[Link]("Removed: " + [Link]());


[Link]("Removed: " + [Link]());

[Link]();
}
}
141

Output:
142

Question 5:

A bookshelf is designed to store books in a stack with LIFO (Last In First Out)
operation. Define a class Book with the following specifications:
Class name:Book

Data members/instance variables:

1. name[]: Stores the names of the books.


2. point: Stores the index of the topmost book.
3. max: Stores the maximum capacity of the bookshelf.

Methods/Member functions:
1. Book(int cap): Constructor to initialize the data members max = cap and
point = -1.
2. void tell(): Displays the name of the book which was last entered in the
shelf. If there is no book left in the shelf, displays the message "SHELF
EMPTY".
3. void add(String v): Adds the name of the book to the shelf if possible,
otherwise displays the message "SHELF FULL".
4. void display(): Displays all the names of the books available in the shelf.

Specify a class Book giving the details of the above functions. Define a main()
function to create an object and call all the functions accordingly to enable the task.

Algorithm:
1. Start
2. Initialize a bookshelf with a name[] array to hold book names, a point to
track the last added book, and max for the shelf capacity.
3. tell():
a. Check if the shelf is empty.
b. Display the last entered book.
4. add():
a. Check if the shelf is full.
b. Add a new book to the shelf and increment point.
5. display():
143

[Link] all books in the shelf.


6. Stop

Program
import [Link];

class Book {
private String[] name;
private int point;
private int max;

public Book(int cap) {


max = cap;
name = new String[max];
point = -1;
}

public void tell() {


if (point == -1) {
[Link]("SHELF EMPTY");
} else {
[Link]("Last entered book: " +
name[point]);
}
}

public void add(String v) {


if (point == max - 1) {
[Link]("SHELF FULL");
144

} else {
name[++point] = v; // Increment point and add the
book
[Link]("Added book: " + v);
}
}

public void display() {


if (point == -1) {
[Link]("SHELF EMPTY");
} else {
[Link]("Books in shelf:");
for (int i = 0; i <= point; i++) {
[Link](name[i]);
}
}
}

public static void main() {


Book shelf = new Book(5); // Create a bookshelf with
capacity 5

[Link]("ISC Physics");
[Link]("ISC Computers");
[Link]("ISC Maths");

[Link]();

[Link]();
[Link]("Macbeth");
[Link]("ISC Chemistry");
145

[Link]("ISC Total English");

[Link]();
}}

Output:
146

Inheritance:

Question 1:

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

Data members/instance variables:

1. pid: String to store the product ID.


2. pname: String to store the product name.
3. pdemand: Integer to store the quantity demanded for the product.

Methods/Member functions:
1. Demand(...): Parameterized constructor to assign values to the data
members.
2. void display(): To display the details of the product.

Class name:Demand

Data members/instance variables:


1. pproduced: Integer to store the quantity of the product produced.
2. prate: To store the cost per unit of the product in decimal.
Methods/Member functions:
1. Supply(...): Parameterized constructor to assign values to the data members
of both the classes.
2. double calculation(): Returns the difference between the amount of demand
(rate × demand) and the amount produced (rate × produced).
3. void display(): To display the details of the product and the difference in the
amount of demand and the amount of supply by invoking the method
calculation().
147

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
calculation(), and void display().

Algorithm:

1. Start
2. Create a class Demand with pid, pname, and pdemand as protected data
members.
3. Initialize these data members through a constructor.
4. Define a display() method to show the product's details.
5. Create a subclass Supply inheriting from Demand, with additional
pproduced and prate variables.
6. Initialize the Supply data members via constructor and calculate the
difference between demand and supply using the calculation() method.
7. Override the display() method to show both demand and supply details.
8. In the main method, create a Supply object and call display().
9. Stop

Program:
class Demand {

protected String pid;

protected String pname;

protected int pdemand;

public Demand(String id, String name, int demand) {

pid = id;

pname = name;

pdemand = demand;

}
148

public void display() {

[Link]("Product ID: " + pid);

[Link]("Product Name: " + pname);

[Link]("Product Demand: " + pdemand);

class Supply extends Demand {

private int pproduced;

private double prate;

public Supply(String id, String name, int demand, int


produced, double rate) {

super(id, name, demand);

pproduced = produced;

prate = rate;

// Method to calculate the difference between demand and


supply

public double calculation() {

double amountDemanded = pdemand * prate;

double amountProduced = pproduced * prate;

return amountDemanded - amountProduced;

}
149

// Overridden display method to display the details of the


product and the difference

public void display() {

[Link](); // Call the display method from the


superclass

[Link]("Product Produced: " + pproduced);

[Link]("Product Rate: " + prate);

double difference = calculation();

[Link]("Difference in amount of demand and


amount of supply: " + difference);

public class Main {

public static void main() {

// Creating an object of the Supply class

Supply supply = new Supply("P101", "Laptop", 100, 80,


50000.0);

[Link]();}}

Output:
150
151

Question 2:
A superclass Godown has been defined to store the details of the stock of a retail
store. Define a subclass Update to store the details of the items purchased with the
new rate and update the stock.

Class Name: Godown

Data members/instance variables:

1. item: A string to store the name of the item.


2. qty: An integer to store the quantity of the item.
3. price: A float to store the price per unit of the item.

Methods/Member functions:
1. Godown(...): Parameterized constructor to assign values to the data
members.
2. void show(): Displays the details of the stock in the godown.
Class name:Update

Data members/instance variables:

1. purchased_qty: An integer to store the quantity of the item purchased.


2. new_price: A float to store the new price per unit of the item.

Methods/Member functions:
1. Update(...): Parameterized constructor to assign values to the data members
of both classes.
2. void update(): Updates the stock and price of the item in the godown after
the purchase.
3. void show(): Displays the updated details of the item.

Algorithm:

1. Start
2. Define the Update class, which extends the Godown class. Initialize
instance variables for purchased_qty and new_price.
3. Create a constructor in the Update class to initialize both the Godown and
Update class variables, calling the superclass constructor.
152

4. Implement the update method:


5. Add purchased_qty to the qty.
6. Update the price with new_price.
7. Override the show method in Update to display updated stock details using
[Link]() for initial data.
8. In the test method:
9. Accept user input for item details and purchase updates.
[Link] original details using show.
[Link] update to adjust stock and price.
[Link] updated details using the overridden show method.
[Link]

Program:
class Godown {
protected String item;
protected int qty;
protected float price;
// Parameterized constructor to assign values to the data
members
Godown(String item, int qty, float price) {
[Link] = item;
[Link] = qty;
[Link] = price;
}

// Method to display the details of the stock in the godown


void show() {
[Link]("Item: " + item);
[Link]("Quantity: " + qty);
[Link]("Price per unit: " + price);
}
}
153

class Update extends Godown {


private int purchased_qty;
private float new_price;

// Parameterized constructor to assign values to the data


members of both classes
Update(String item, int qty, float price, int purchased_qty,
float new_price) {
super(item, qty, price);
this.purchased_qty = purchased_qty;
this.new_price = new_price;
}

// Method to update the stock and price of the item in the


godown
void update() {
qty += purchased_qty;
price = new_price;
}

// Method to display the updated details of the item


@Override
void show() {
[Link]();
[Link]("Purchased Quantity: " +
purchased_qty);
[Link]("New Price per unit: " + price);
[Link]("Updated Quantity: " + qty);
}
}
154

Update update = new Update("Laptop", 10, 50000.0f, 5, 45000.0f);


[Link]("Initial Stock Details:");
[Link]();

[Link]();

[Link]("Updated Stock Details:");


[Link]();
}}
155

Output:
156

Question 3:
A superclass EmpSal has been defined to store the details of an employee. Define a
subclass Overtime to compute the total salary of the employee, after adding the
overtime amount based on the following criteria:

If hours are more than 40, then ₹ 5000 are added to salary as an overtime amount.
If hours are between 30 and 40 (both inclusive), then ₹ 3000 are added to salary as
an overtime amount.
If hours are less than 30, then the salary remains unchanged.
The details of the members of both the classes are given below:
Class name: EmpSal

Data members/instance variables:


empnum: to store the name of the employee
empcode: integer to store the employee code
salary: to store the salary of the employee in decimal

Methods/Member functions:
EmpSal(...): parameterized constructor to assign values to data members
void show(): to display the details of the employee

Class name: Overtime


Data members/instance variables:
hours: integer to store overtime in hours
total: to store the total salary in decimal

Methods/Member functions:
157

-Overtime(...): parameterized constructor to assign values to data members of both


classes
void calSal(): calculates the total salary by adding the overtime amount to the
salary as per the criteria given above
void show(): to display the employee details along with the total salary (salary +
overtime amount)

Algorithm:
1. Start
2. Define a superclass EmpSal to store the employee details (name, ID, basic
salary).
3. Inside EmpSal, define a constructor to initialize the name, ID, and salary.
4. Create a method show() in EmpSal to display the employee details.
5. Define a subclass Overtime that extends EmpSal and adds the hoursWorked
and totalSalary attributes.
6. Create a constructor in Overtime that accepts hours worked and calls the
superclass constructor to initialize employee details.
7. Define a method calculateOvertime() in Overtime to calculate the total
salary based on hours worked:
a. Add ₹5000 if hours are more than 40.
b. Add ₹3000 if hours are between 30 and 40.
c. Keep the salary unchanged if hours are less than 30.
8. Override the show() method in Overtime to display the employee details
along with hours worked and total salary.
9. Stop

Program
class EmpSal {
protected String empName;
protected int empId;
protected double basicSalary;
158

// Constructor to initialize employee details


public EmpSal(String name, int id, double salary) {
empName = name;
empId = id;
basicSalary = salary;
}

// Method to display employee details


public void show() {
[Link]("Employee Name: " + empName);
[Link]("Employee ID: " + empId);
[Link]("Basic Salary: " + basicSalary);
}
}
class Overtime extends EmpSal {
private int hoursWorked;
private double totalSalary;

// Constructor to initialize details for both EmpSal and


Overtime
public Overtime(String name, int id, double salary, int
hours) {
super(name, id, salary); // Call the superclass
constructor
hoursWorked = hours;
}

// Method to calculate total salary with overtime


public void calculateOvertime() {
if (hoursWorked > 40) {
totalSalary = basicSalary + 5000;
159

} else if (hoursWorked >= 30 && hoursWorked <= 40) {


totalSalary = basicSalary + 3000;
} else {
totalSalary = basicSalary; // Salary remains
unchanged
}
}

// Method to display the updated salary after overtime


public void show() {
[Link](); // Display original employee details
[Link]("Hours Worked: " + hoursWorked);
[Link]("Total Salary (after overtime): " +
totalSalary);
}
}

Output:
160

Question 4:
A superclass Circle has been defined to calculate the area of a circle. Define a
subclass Volume to calculate the volume of a cylinder.
The details of the members of both the classes are given below:

Data members/instance variables:

1. radius: to store the radius in decimals.


2. area: to store the area of a circle.
Methods / Member functions:

1. Circle(...): Parameterized constructor to assign values to the data members.


2. void cal_area(): Calculates the area of a circle using the formula πr2\pi
r^2πr2.
3. void display(): Displays the area of the circle.
Class name:Circle
Data members/instance variables:

1. height: to store the height of the cylinder in decimals.


2. volume: to store the volume of the cylinder in decimals.

Methods / Member functions:


1. Volume(...): Parameterized constructor to assign values to the data members
of both the classes.
2. double calculate(): Calculates and returns the volume of the cylinder using
the formula πxrxrxh where r is the radius and h is the height.
3. void display(): Displays the area of a circle and volume of a cylinder.
Assume that the superclass Circle has been defined. Using the concept of
inheritance, specify the class Volume.

Input radius=4 and height=2.

Algorithm:
1. Start
161

2. Define a superclass Circle to represent a circle with attributes for radius and
area.
3. Create a constructor in Circle to initialize the radius and set the area to 0.
4. Define a method cal_area() to calculate the area of the circle using the
formula:
area=π×radiusxradius
5. Define a display() method in Circle to output the area of the circle.
6. Define a subclass Volume that extends Circle and includes an attribute for
height and volume.
7. Create a constructor in Volume to initialize radius (via the superclass
constructor) and height.
8. Define a method calculate() in Volume to compute the volume of the
cylinder using the formula:
volume=π×radiusxradius×height
9. Override the display() method in Volume to display both the area of the
circle and the volume of the cylinder.
[Link]

Program
class Circle {
protected double radius;
protected double area;
public Circle(double r) {
radius = r;
area = 0;
}

// Method to calculate the area of the circle


public void cal_area() {
area = [Link] * radius * radius;
}
public void display() {
[Link]("Area of the circle: " + area);
}
162

}
class Volume extends Circle {
private double height;
private double volume;
public Volume(double r, double h) {
super(r);
height = h;
volume = 0;
}

// Method to calculate the volume of the cylinder


public double calculate() {
volume = [Link] * radius * radius * height;
return volume;
}
public void display() {
[Link](); // Display the area of the circle
[Link]("Volume of the cylinder: " + volume);
}
}
163

Output:
164

Question 5:

A superclass Bank has been defined to store the details of the customer in a bank.
Define a subclass Interest to calculate the compound interest.
The details of the members of both the classes are given below:

Class Name: Bank

Data members/instance variables:

1. name: To store the name of the customer.


2. acc_no: Integer to store the account number.
3. principal: To store the principal amount in decimals.
Methods / Member functions:
1. Bank(...): Parameterized constructor to assign values to the data members.
2. void display(): To display the customer details.

Class name:
Data members/instance variables:

1. rate: To store the interest rate in decimals.


2. time: To store the time period in decimals.
Methods / Member functions:

1. Interest(...): Parameterized constructor to assign values to the data members


of both classes.
2. double calculate(): To calculate and return the compound interest using the
formula:
CI=principal×(1+100rate )^time−principal
3. void display(): To display the customer details along with the compound
interest.

Assume that the superclass Bank has been defined. Using the concept of
inheritance, specify the class Interest giving the details of the constructor, double
calculate(), and void display().

Algorithm:
165

1. Start
2. Define a superclass Bank with attributes name, acc_no, and principal.
3. Create a constructor in Bank to initialize customer details and principal
amount.
4. Define a display() method in Bank to show customer details.
5. Define a subclass Interest that extends Bank, with additional attributes rate
and time.
6. Create a constructor in Interest to initialize customer details, interest rate,
and time period.
7. Define a calculate() method to compute compound interest using the
formula:
CI=principal×(1+100rate )^time−principal
8. Override display() in Interest to show customer details and calculated
compound interest.
9. Stop

Program
class Bank {
protected String name;
protected int acc_no;
protected double principal;
public Bank(String customerName, int accountNumber, double
principalAmount) {
name = customerName;
acc_no = accountNumber;
principal = principalAmount;
}
public void display() {
[Link]("Customer Name: " + name);
[Link]("Account Number: " + acc_no);
[Link]("Principal Amount: " + principal);
}
}
class Interest extends Bank {
166

private double rate;


private double time;
public Interest(String customerName, int accountNumber,
double principalAmount, double interestRate, double timePeriod)
{
super(customerName, accountNumber, principalAmount); //
Call the superclass constructor
rate = interestRate;
time = timePeriod;
}

// Method to calculate compound interest


public double calculate() {
double CI = principal * [Link](1 + (rate / 100), time)
- principal;
return CI;
}
public void display() {
[Link](); // Display the original customer
details
double compoundInterest = calculate();
[Link]("Interest Rate: " + rate);
[Link]("Time Period: " + time);
[Link]("Compound Interest: " +
compoundInterest);
}
}
167

Output:

Common questions

Powered by AI

The logic involves generating strings where each is formed by concatenating the two previous strings, akin to Fibonacci number addition. Starting with 'a' and 'b', subsequent strings are generated through concatenation, reflecting recursive dependency properties similar to numerical Fibonacci sequences with intrinsic part dependency . This logical parallel allows for structured growth through sequential buildup, making the method kinetically akin to traditional sequence properties.

The program requires sentence input validation, ensuring it ends with '.' or '?'. Each word is then capitalized at the start while vowels and consonants are counted by iterating through characters. The results display in tabular format, ensuring clear presentation of word transformation and character statistics . Key structural adherence is day through delimiter-based analysis and procedural integrity checks, like valid termination character enforcement, to maintain proper sentence processing.

A ROT13 cipher is implemented by shifting each alphabetical character 13 places. For letters 'a-z' and 'A-Z', the transformation wraps around the alphabet, effectively using modulo operation. Non-alphabetic characters are left unchanged to maintain the integrity of the text structure . The program accepts a string, checks, and skips non-letter characters, ensuring only letters are enciphered. This is crucial to ensuring unintended alterations to the sentence layout or punctuation do not occur.

The steps are: first, prompt the user to enter matrix dimensions within the allowed range (greater than 2 and less than 10); next, if dimensions are valid, prompt the user to fill the matrix. If invalid, display an error message and stop. After matrix entry, display its original form, sort each row using bubble sort, and display the sorted matrix .

The algorithm involves accepting a matrix of permissible size, then rotating rows such that each becomes the preceding one with the first shifting to the last. This simulates a cyclic shift upwards. Additionally, it includes an iterative search through the matrix to find the highest element along with its coordinates. This procedure ensures both spatial transformation and data analysis within the given constraints .

The process begins with sentence retrieval, ensuring processing continuity by appending a space. Each word is isolated, with its first and last letters swapped before sorting the intermediate characters alphabetically. Proper processing requires accurate splitting and reconstruction, ensuring only intra-word letter arrangements alter while maintaining external word structure. Managing word delimiters and flow continuity ensures transformation efficiency while maintaining sentence integrity . It showcases the importance of structured procedural handling in string manipulation tasks.

The method calculates the sum of both the primary and secondary diagonals in a matrix. The primary diagonal sum is calculated by iterating over the matrix where each element [i][i] is considered, while the secondary diagonal sum considers [i][M-1-i] for a matrix of size M x M . After processing, these sums are printed along with the matrix content for visual verification and analysis.

The algorithm involves processing a sentence, identifying words beginning and ending with vowels, and placing them first while maintaining the occurrence order of other words. This is implemented by iterating through each word, using conditions to classify, accumulating vowel-start-and-end words separately, and finally reconstructing the sentence . A function checks vowels, aiding classification, ensuring correct reordering without altering intrinsic word order beyond requirement.

The process requires first checking if a word is a palindrome by comparing characters symmetrically. For non-palindromes, append the reverse of the word (excluding the last character) to itself, effectively making it mirror-symmetric. Maintaining word boundaries and sentence order is ensured by processing them individually within delimiters, like spaces, thus keeping checks and transformations isolated appropriately . The algorithm includes iterative checks, enabling transformation in controlled, bounded steps.

You might also like