Java Programs for Prime Adam & Carton Packing
Java Programs for Prime Adam & Carton Packing
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];
int N = [Link]();
int remainingBoxes = N;
int cartons48 = remainingBoxes / 48;
remainingBoxes %= 48;
if (remainingBoxes > 0) {
cartons6++;
remainingBoxes = 0;
}
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];
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
5. Stop
Program:
import [Link];
}
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0)
{ //checking prime
return false;
}
}
return true;
}
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;
}
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];
static int[] daysInMonthLeap = {31, 29, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31};
getDateFromDayNumber(dayNumber, year);
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];
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
num=num/10;
}
num=s;
}
if(num==1)
return true;
else
return false;
}
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];
}
[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 {
[Link]("Sorted Array:");
for (int i = 0; i < N; i++) {
37
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 {
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");
}
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
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 {
[Link]("Original Matrix:");
displayMatrix(matrix, m, n);
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]);
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 {
bubbleSortDescending(array);
index = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = array[index++];
}
}
59
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
Program:
import [Link];
public class SymmetricMatrixCheck {
public static void main() {
Scanner sc = new Scanner([Link]);
}
}
[Link]("Original Matrix:");
displayMatrix(matrix, M);
if (isSymmetric) {
[Link]("THE GIVEN MATRIX IS SYMMETRIC");
} else {
[Link]("THE GIVEN MATRIX IS NOT
SYMMETRIC");
}
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
4. If the sentence does not end with them, send an error message.
5. Extract Words
8. Sort Words
[Link] two or more words have the same length, sort them alphabetically.
[Link] Results
[Link]
Program:
import [Link];
return;
words[j + 1] = temp;
[Link](lastChar);
}
68
Output
69
Question 2:
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
[Link]
Program
import [Link];
return;
} else {
[Link](c);
}}
}}
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.
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];
Question 4:
Algorithm
1. Start
9. Display Vertically
[Link]
Program
76
import [Link];
if (N <= 2 || N >= 9) {
[Link]("Invalid number of teams.");
return;
}
int maxLen = 0;
for (String team : teams) {
maxLen = [Link](maxLen, [Link]());
}
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 ('.', '?', '!').
[Link]
79
Program
import [Link];
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
}
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 ‘?’.
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];
return;
[Link]("Word\tVowels\tConsonants");
char ch = [Link](i);
if (![Link]()) {
if ("AEIOUaeiou".indexOf(letter) != -1)
{
vowels++;
} else if ([Link](letter)) {
consonants++;
word = "";
85
} else {
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
6. Generate Series
8. Display Series
[Link]
Program
import [Link];
int n = [Link]();
if (n >= 1) {
if (n >= 2) {
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];
char ch = [Link](i);
if (![Link]()) {
if ([Link]([Link](0))) {
word = "";
} else {
Output:
92
Call By Reference
Question 1:
Algorithm
1. Start
2. Input Arrays
3. Accept two sorted arrays, A and B.
4. Initialize Pointers
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] Result
Program
import [Link];
arr1[i] = [Link]();
}
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];
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];
start++;
end--;
}
}
[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 {
}}}
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];
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];
if (arr[mid] == target)
return mid;
110
if (result == -1)
[Link]("Element not present in the
array.");
else
111
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
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 {
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];
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 {
Output:
123
Data Structures
Question 1:
Methods/Member functions:
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;
}
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[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.
Class name:Queue
Data members/Instance variables:
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;
return value;
}
}
q.add_dat(10);
q.add_dat(20);
q.add_dat(30);
[Link]();
130
[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
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
}
[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.
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;
}
}
}
for (int i = 0; i <= rear; i++) {
[Link](cq[i] + " ");
}
}
[Link]();
}
}
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]();
[Link](50);
[Link]();
[Link](60);
[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
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
Program
import [Link];
class Book {
private String[] name;
private int point;
private int max;
} else {
name[++point] = v; // Increment point and add the
book
[Link]("Added book: " + v);
}
}
[Link]("ISC Physics");
[Link]("ISC Computers");
[Link]("ISC Maths");
[Link]();
[Link]();
[Link]("Macbeth");
[Link]("ISC Chemistry");
145
[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:
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
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 {
pid = id;
pname = name;
pdemand = demand;
}
148
pproduced = produced;
prate = rate;
}
149
[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.
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
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
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;
}
[Link]();
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
Methods/Member functions:
EmpSal(...): parameterized constructor to assign values to data members
void show(): to display the details of the employee
Methods/Member functions:
157
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
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:
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;
}
}
class Volume extends Circle {
private double height;
private double volume;
public Volume(double r, double h) {
super(r);
height = h;
volume = 0;
}
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:
Data members/instance variables:
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
Output:
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.