[go: up one dir, main page]

0% found this document useful (0 votes)
22 views114 pages

Computer Assignment

The document outlines various programming tasks in Java, including checking for Fascinating Numbers, generating Pronic Numbers, identifying Prime-Adam integers, counting Prime Palindrome integers, determining Magic Numbers, checking for Bouncy Numbers, identifying Circular Primes, and recognizing Evil Numbers. Each task includes a detailed algorithm and example inputs and outputs. The document serves as a guide for implementing these numerical checks and classifications in Java.

Uploaded by

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

Computer Assignment

The document outlines various programming tasks in Java, including checking for Fascinating Numbers, generating Pronic Numbers, identifying Prime-Adam integers, counting Prime Palindrome integers, determining Magic Numbers, checking for Bouncy Numbers, identifying Circular Primes, and recognizing Evil Numbers. Each task includes a detailed algorithm and example inputs and outputs. The document serves as a guide for implementing these numerical checks and classifications in Java.

Uploaded by

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

Question 1

Write a Program in Java to input a number and check whether it is a


Fascinating Number or not.Fascinating Numbers: Some numbers of 3 digits or
more exhibit a very interesting property. The property is such that, when the
number is multiplied by 2 and 3, and both these products are concatenated
with the original number, all digits from 1 to 9 are present exactly once,
regardless of the number of zeroes.

Example :Consider the number 192

a. 192 x 1 = 192

b. 192 x 2 = 384

c. 192 x 3 = 576

Concatenating the results: 192 384 576 .It could be observed that
'192384576' consists of all digits from 1 to 9 exactly once. Hence, it could be
concluded that 192 is a Fascinating Number. Some examples of fascinating
Numbers are: 192, 219, 273, 327, 1902, 1920, 2019 etc.

Algorithm

Step 1: Start

Step 2: Input a number n

Step 3: Check if the number has 3 or more digits (i.e., n >= 100)
If not, terminate the program or skip checking.

Step 4: Multiply the number by 1, 2, and 3


Let:
n1 = n * 1
n2 = n * 2
n3 = n * 3

Step 5: Concatenate n1, n2, and n3 into a single string


Let: str = n1 + n2 + n3 (as a string)

Step 6: Check if the string str contains exactly 9 digits

Step 7: For each character in str, check if any digit is repeated


→ Use nested loop to compare each digit with all others
If any digit appears more than once, terminate (not fascinating)

1 | Page
Step 8: Sum all digits of the string str
Let sum = 0
For each character ch in str, convert to digit and add to sum

Step 9: If the sum of digits equals 45


→ All digits from 1 to 9 are present once
→ Then print: “Number is fascinating”
Else
→ Print: “Number is not fascinating”

Step 10: End

Program:

2 | Page
3 | Page
Output

4 | Page
Question 2

WAP to generate Pronic Number/oblong number/ rectangular number /


heteromecic number (Pronic Number : A pronic number, oblong number,
rectangular number or heteromecic number, is a number which is the
product of two consecutive integers, that is, n (n + 1). The first few pronic
numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210,
240, 272, 306, 342, 380, 420, 462 …)

Algorithm

Step 1: Start

Step 2: Input the number of Pronic numbers to generate


Prompt the user to enter a number count

Step 3: Initialize a loop from i = 0 to i < count

Step 4: Inside the loop:


→ Compute the Pronic number using the formula:
pronic = i * (i + 1)

Step 5: Display the value of pronic

Step 6: Repeat steps 4–5 until count numbers are generated

Step 7: End

Program

5 | Page
Output

Question 3

6 | Page
A Prime-Adam integer is a positive integer (without leading zeros) which is a
prime as well as an Adam number. Prime number: A number which has only
two factors, i.e. 1 and the number itself.

Example: 2, 3, 5, 7 ... etc.

Adam number: The square of a number and the square of its reverse are
reverse to each other.

Example: If n = 13 and reverse of 'n' = 31, then,

(13)2 = 169

(31)2 = 961 which is reverse of 169, thus 13, is an Adam number.

Accept two positive integers m and n, where m is less than n as user input.
Display all Prime-Adam integers that are in the range between m and n (both
inclusive) and output them along with the frequency, in the format given
below: Test your program with the following data and some random data:

Example 1 INPUT:

m=5

n = 100

OUTPUT: THE PRIME-ADAM INTEGERS ARE: 11 13 31

FREQUENCY OF PRIME-ADAM INTEGERS IS: 3

Algorithm

1) Start the program.

2) Create a Scanner object to take input from the user.

3) Input two positive integers m and n, where m < n.

4) Initialize a counter count = 0 to store the frequency of Prime-Adam


integers.

5) Display the heading: "THE PRIME-ADAM INTEGERS ARE:".

6) Start a loop from i = m to i = n (inclusive).

7) For each number i, check if it is a prime number:

a) Set a boolean variable isPrime = true.

b) If i <= 1, set isPrime = false.

7 | Page
c) Else, run a loop from j = 2 to j ≤ √i:

i) If i % j == 0, set isPrime = false.

ii) Break the inner loop.

8) If isPrime is true, check if i is an Adam number:

a) Reverse the digits of i and store in rev.

i) Initialize num = i and rev = 0.

ii) While num > 0, do:

- rev = rev * 10 + num % 10

- num = num / 10

b) Compute SquOri = i * i.

c) Compute SquRev = rev * rev.

d) Reverse SquRev and store in RevSquRev:

i) Initialize temp = SquRev and RevSquRev = 0.

ii) While temp > 0, do:

- RevSquRev = RevSquRev * 10 + temp % 10

- temp = temp / 10

e) If SquOri == RevSquRev, then:

i) Print the number i.

ii) Increment count by 1.

9) After the loop ends, print:

"FREQUENCY OF PRIME-ADAM INTEGERS IS: " followed by count.

10) End the program.

Program

8 | Page
9 | Page
10 | P a g e
Output

11 | P a g e
Question 4

A prime palindrome integer is a positive integer (without leading zeros)


which is prime as well as a palindrome.

Given two integers m and n, where m < n, write a program to determine how
many prime-palindrome integers are there in the range between m and n
(both inclusive) and output them. The input contains two positive integers m
and n where m < 3000 and n < 3000. Display the number of prime-
palindrome integers in the specified range along with their values in the
format specified below:

Test your program with the sample data and some random data:

Example 1

INPUT:

m = 100

N = 1000

OUTPUT:

THE PRIME PALINDROME NUMBERS ARE:

101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929

FREQUENCY OF PRIME PALINDROME INTEGERS: 15

Example 2

INPUT:

m = 100

n = 5000

OUTPUT: OUT OF RANGE

Algorithm

1) Start the program.

2) Prompt the user to enter a value for m such that 0 < m < 3000.

3) Read the value of m.

12 | P a g e
4) If m is not in the valid range, display "The number is out of range" and
stop the program.

5) Prompt the user to enter a value for n such that 0 < n < 3000 and m < n.

6) Read the value of n.

7) If n is not in the valid range, display "The number is out of range" and stop
the program.

8) Display the message: "The Prime Palindrome numbers are :-"

9) Initialize a counter palc = 0 to count the prime palindrome numbers.

10) Repeat steps 11 to 19 for every number i from m to n - 1.

11) Set a flag variable c = 0.

12) Repeat steps 13 to 14 for j from 2 to i - 1.

13) If i is divisible by j (i % j == 0), then:

14) Set c = 1 and break the inner loop.

15) If c is still 0, then i is a prime number.

16) Set cn = i and paln = 0.

17) While cn > 0, repeat:

18) Get last digit r = cn % 10.

19) Update paln = (paln * 10) + r and reduce cn = cn / 10.

20) After reversing, if paln equals i, then:

21) Print i followed by a comma.

22) Increment palc by 1.

23) After the loop ends, print "The number of prime palindrome are "
followed by the value of palc.

24) End the program.

13 | P a g e
Program

14 | P a g e
15 | P a g e
Output

Question 5

16 | P a g e
Write a program to input a number and check whether it is 'Magic Number' or
not. Display the message accordingly.

A number is said to be a magic number if the eventual sum of digits of the


number is one.

Sample Input : 55

Then, 5 + 5 = 10, 1 + 0 = 1

Sample Output: Hence, 55 is a Magic Number.

Similarly, 289 is a Magic Number

Algorithm

1) Start the program.

2) Prompt the user to enter a number.

3) Read the input number and store it in variable num.

4) Repeat steps 5 to 8 while num > 9.

5) Initialize sum = 0.

6) Set temp = num.

7) While temp > 0, repeat:

8) Add the last digit of temp to sum (sum += temp % 10), then update
temp = temp / 10.

9) After the inner loop, set num = sum.

10) After exiting the loop, check if num is equal to 1.

11) If yes, print "It is a Magic Number."

12) Otherwise, print "It is not a Magic Number."

13) End the program.

Program

17 | P a g e
Output

18 | P a g e
Question 6

A number is said to Bouncy number if the digits of the number are unsorted.

19 | P a g e
For example,

22344 - It is not a Bouncy number because the digits are sorted in ascending
order.

774410 - It is not a Bouncy number because the digits are sorted in


descending order. 155349 - It is a Bouncy number because the digits are
unsorted.

A number below 100 can never be a Bouncy number.

Write a program in java to accept a number. Check and display whether it is


a Bouncy number or not.

Algorithm

1) Start the program.

2) Prompt the user to enter a number greater than 99.

3) Read the number as a string and store it in variable n.

4) Initialize two counters: a = 1 (for ascending), d = 1 (for descending).

5) Check if the length of the number is at least 3 digits:

6) If not, print "The number is out of range" and end the program.

7) If the length is valid, repeat steps 8 to 10 for each index i from 0 to


n.length() - 2:

8) If the digit at position i is less than or equal to the digit at i+1,


increment a.

9) If the digit at position i is greater than or equal to the digit at i+1,


increment d.

10) After the loop ends, check the values of a and d.

11) If a equals the length of the number, print "The number is not bouncy"
(ascending).

12) Else if d equals the length of the number, print "The number is not
bouncy" (descending).

13) Else, print "The number is bouncy" (unsorted).

14) End the program.

20 | P a g e
Program

21 | P a g e
Output

22 | P a g e
Question 7

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.

Test your program with the following data and some random data:

Example 1

INPUT:

N = 197

OUTPUT:

197

971

719

197 IS A CIRCULAR PRIME.

Algorithm

1) Start the program.

2) Prompt the user to enter a 3-digit number.

3) Read the number and store it in variable n.

23 | P a g e
4) Convert n to a string and store it in variable nn.

5) Initialize a counter variable check = 0.

6) If the length of nn is less than 3:

7) Display "Out range" and terminate the program.

8) Else:

9) Repeat steps 10 to 17 for i = 0 to length of nn - 1:

10) Initialize c = 0 (to count the number of divisors of n).

11) Repeat for j = 2 to n:

12) If n % j == 0, increment c.

13) If c == 1, it means n is a prime number, so increment check.

14) Print the current value of n.

15) Perform circular shift:

16) Extract the last digit (r = n % 10).

17) Get the remaining digits (q = n / 10).

18) Compute the rotated number:

n = r * (10^(length of nn - 1)) + q

19) After the loop, check if check == length of nn:

20) If yes, print "The number is circular prime".

21) Else, print "The number is not circular prime".

22) End the program.

24 | P a g e
Program

25 | P a g e
Output

Question 8

26 | P a g e
An Evil number is a positive whole number which has even number of 1's in
its binary equivalent. Example: Binary equivalent of 9 is 1001, which
contains even number of 1's. A few evil numbers are 3, 5, 6, 9…. Design a
program to accept a positive whole number and find the binary equivalent of
the number and count the number of 1's in it and display whether it is a Evil
number or not with an appropriate message. Output the result in format
given below:

Example 1

Input: 15

Binary Equivalent: 1111

No. of 1's: 4

Output: Evil Number

Example 2

Input: 26

Binary Equivalent: 11010

No. of 1's: 3

Output: Not an Evil Number

Algorithm:

1) Start the program.

2) Prompt the user to enter a positive whole number.

3) Read the number and store it in variable num.

4) Convert num to its binary equivalent using Integer.toBinaryString(num)


and store in variable binary.

5) Initialize a counter variable count = 0.

6) For each character in binary:

7) If the character is '1', increment count by 1.

8) Display "Binary Equivalent: " followed by the binary value.

9) Display "No. of 1's: " followed by count.

27 | P a g e
10) If count % 2 == 0:

11) Display "Output: Evil Number".

12) Else:

13) Display "Output: Not an Evil Number".

14) End the program.

Program

Output

28 | P a g e
Question 9

29 | P a g e
Write a program to input two valid dates, each comprising of Day (2 digits),
Month (2 digits) and Year (4 digits) and calculate the days elapsed between
both the dates.

Test your program for the following data values:

FIRST DATE:

Day: 24

Month: 09

Year: 1960

SECOND DATE:

Day: 08

Month: 12

Year: 1852

Output: xxxxxxxx

(these are actual number of days elapsed)

Algorithm
1. Start

2. Create a Scanner object to take input

3. Display "Enter FIRST DATE:"

4. Read day1, month1, and year1 from user

5. Display "Enter SECOND DATE:"

6. Read day2, month2, and year2 from user

7. Create a Calendar object firstDate with year1, month1 - 1, day1

8. Create a Calendar object secondDate with year2, month2 - 1, day2

9. Find the time difference in milliseconds:

diff = absolute value of (firstDate milliseconds - secondDate milliseconds)

10. Convert milliseconds to days:

BetDays = diff / (24 * 60 * 60 * 1000)

30 | P a g e
11. Display "Number of days elapsed between the two dates: " + BetDays

12. End

Program

Output

31 | P a g e
Question 10

32 | P a g e
Design a program to accept a day number (between 1 and 366), year (in 4
digits) from the user to generate and display the corresponding date. Also,
accept 'N' (1 <= N <= 100) from the user to compute and display the future
date corresponding to 'N' days after the generated date. Display an error
message if the value of the day number, year and N are not within the limit
or not according to the condition specified.

Test your program with the following data and some random data:

Example 1

INPUT:

DAY NUMBER: 255

YEAR: 2018

DATE AFTER (N DAYS): 22

OUTPUT:

DATE: 12TH SEPTEMBER, 2018

DATE AFTER 22 DAYS: 4TH OCTOBER, 2018

Algorithm

1) Start

2) Read inputs: day number d (1–366), year y (4 digits), and n (1–100)

3) Compute leap:

- If (y % 400 == 0) OR (y % 4 == 0 AND y % 100 != 0), set leap = true

- Else set leap = false

4) Set max = 366 if leap is true, otherwise max = 365

5) If (d < 1 OR d > max OR n < 1 OR n > 100), print "Invalid input!" and stop

6) Create array days = {31, (leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31,
30, 31}

7) Create array m =
{"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","S
EPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}

33 | P a g e
8) Set mon = 0

9) While d > days[mon], do:

- d = d - days[mon]

- mon = mon + 1

10) Print "DATE: d m[mon], y"

11) d = d + n

12) While d > days[mon], do:

- d = d - days[mon]

- mon = mon + 1

- If mon == 12, then:

- mon = 0

-y=y+1

- Recompute leap for new y (same rule as step 3)

- Update days[1] = (leap ? 29 : 28)

13) Print "DATE AFTER n DAYS: d m[mon], y"

14) End

34 | P a g e
Program

35 | P a g e
Output

Question 11

36 | P a g e
Design a class Convert to find the date and the month from a given day
number for a particular year.

Example: If day number is 64 and the year is 2020, then the corresponding
date would be: March 4,

2020 i.e. (31 + 29 + 4 = 64). Some of the members of the class are given
below:

Class name: Convert

Data members/instance variables:

n: integer to store the day number.

d: integer to store the day of the month (date).

m: integer to store the month.

y: integer to store the year.

Methods/Member functions:

Convert(): constructor to initialize the data members with legal initial values.

void accept(): to accept the day number and the year.

void dayToDate(): converts the day number to its corresponding date for a
particular year and stores the date in ‘d’ and the month in ‘m’.

void display(): displays the month name, date and year.

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

Algorithm

1) Start

2) Define class Convert with data members:

- n (day number)

- d (day of month)

- m (month number)

- y (year)

37 | P a g e
3) Define constructor Convert():

- Initialize n, d, m, y = 0

4) Define method accept():

- Read day number n

- Read year y

5) Define method dayToDate():

- Create array days = {31,28,31,30,31,30,31,31,30,31,30,31}

- If (y % 400 == 0) OR (y % 4 == 0 AND y % 100 != 0), set days[1] = 29

- Set m = 0

- While (n > days[m]):

- n = n – days[m]

-m=m+1

- Set d = n

- Set m = m + 1

6) Define method display():

- Create array monthName =


{"January","February","March","April","May","June","July","August","Septemb
er","October","November","December"}

- Print "Corresponding date: monthName[m-1] d, y"

7) In main():

- Create object obj of Convert

- Call obj.accept()

- Call obj.dayToDate()

- Call obj.display()

8) End

Program

38 | P a g e
Output

39 | P a g e
Question 12

40 | P a g e
Write a program to accept a date in the string format dd/mm/yyyy and
accept the name of the day on 1st of January of the corresponding year. Find
the day for the given date.

Example:

Input:

Date: 5/7/2001

Day on 1st January : MONDAY

Output:

Day on 5/7/2001 : THURSDAY

Algorithm

1. Start

2. Input date in the format dd/mm/yyyy.

3. Input the day on 1st January of that year.

4. Extract the following from the date:

- day = first 2 characters of date

- month = characters 4 and 5 of date

- year = characters from position 6 onwards

5. Initialize an array daysInMonth with values:

{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

6. Check leap year condition:

IF (year % 400 == 0) OR (year % 4 == 0 AND year % 100 != 0) THEN

Set daysInMonth[1] = 29

END IF

7. Calculate totalDays:

- Set totalDays = 0

- FOR each month from 1 to (month - 1):

41 | P a g e
totalDays = totalDays + daysInMonth[i]

- END FOR

- Add (day - 1) to totalDays

8. Initialize array week with values:

{"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY",

"THURSDAY", "FRIDAY", "SATURDAY"}

9. Find startIndex:

- FOR i = 0 to 6

IF week[i] = firstDay THEN

startIndex = i

BREAK

END IF

- END FOR

10. Calculate dayIndex:

dayIndex = (startIndex + totalDays) MOD 7

11. Output:

"Day on <date> : week[dayIndex]"

12. End

Program

42 | P a g e
Output

43 | P a g e
Question 13

44 | P a g e
Write a program that reads a string and a character. Each occurrence of the
given character (regardless of its case) is converted to opposite case.

INPUT: AabrAcadabrA and ‘a’

OUTPUT: aAbracAdAbra ( see each ‘a’ or ‘A’ is converted to opposite case ie.
upper to lower or vice-versa)

Algorithm

Step 1: Start.

Step 2: Read a string str from the user.

Step 3: Read a character t from the user.

Step 4: Initialize an empty string r to store the result.

Step 5: Repeat for each character ch in str:


a. Convert both ch and t to lowercase and compare.
b. If they are equal:
• If ch is uppercase → convert it to lowercase and add to r.
• Else if ch is lowercase → convert it to uppercase and add to r.
c. Otherwise, directly add ch to r.

Step 6: After the loop ends, print the final string r.

Step 7: Stop.

Program

45 | P a g e
Output

46 | P a g e
Question 14

47 | P a g e
Write a program to Input a word in uppercase and check for the position of
the first occurring vowel and perform the following operation.

(i) Words that begin with a vowel are concatenated with “Y”.

For example, EUROPE becomes EUROPEY.

(ii) Words that contain a vowel in-between should have the first part from the
position of the vowel till the end, followed by the part of the string from
beginning till the position of the vowel and is concatenated by “C”.

For example, PROJECT becomes OJECTPRC.

(iii) Words which do not contain a vowel are concatenated with “N”.

For example, SKY becomes SKYN.

Algorithm

1. Start

2. Input a word in UPPERCASE

3. Set vowels = "AEIOU"

4. Set pos = -1

5. For i = 0 to word.length - 1 do

If word[i] is in vowels then

pos = i

Break

6. If pos == 0 then

result = word + "Y"

7. Else if pos > 0 then

p1 = substring(word, pos, end)

p2 = substring(word, 0, pos)

48 | P a g e
result = p1 + p2 + "C"

8. Else

result = word + "N"

9. Print result

10. Stop

Program

Output

49 | P a g e
Question 15

50 | P a g e
A class TheString accepts a string of a maximum of 100 characters with only
one blank space between the words. Some of the members of the class are
as follows:

Class name : TheString

Data member/instance variable:

str : to store a string

len : integer to store the length of the string

wordcount : integer to store the number of words

cons : integer to store the number of consonants

Member functions/methods:

TheString( ) : default constructor to initialize the data members

TheString( String ds) : parameterized constructor to assign str=ds

void countFreq() : to count the number of words and the number of


consonants and store them in wordcount and cons respectively

void Display( ) : to display the original string, along with the number of words
and the number of consonants

Specify the class TheString giving the details of the constructors, void
countFreq() and void Display( ). Define the main( ) function to create an
object and call the functions accordingly to enable the task.

Algorithm

1. Start

2. Initialize class TheString with data members:

 str → string to store input

 len → integer to store length of string

 wordcount → integer to store number of words

 cons → integer to store number of consonants

3. Define constructors:

 Default constructor: set str = " ", len = 0, wordcount = 0, cons = 0

51 | P a g e
 Parameterized constructor: assign str = ds

4.Define method countFreq()

 Remove leading and trailing spaces using trim()

 Set len = str.length()

 If len == 0, set wordcount = 0 and cons = 0, then return

 Initialize wordcount = 1

 Initialize cons = 0

 For each character in str

o Convert to lowercase

o If character is a space → increment wordcount

o If character is a letter and not a vowel → increment cons

5.Define method Display()

 Print the original string

 Print the number of words

 Print the number of consonants

6.In main() method:

 Accept a string from user (max 100 characters)

 Create object of TheString using parameterized constructor

 Call countFreq()

 Call Display()

7.End

Program

52 | P a g e
Output

53 | P a g e
Question 16

A class ConsChange has been defined with the following details:

54 | P a g e
Class name : ConsChange

Data members/instance variables:

word : stores the word

len : stores the length of the word

Member functions/methods:

ConsChange( ) : default constructor

void readword( ) : accepts the word in lowercase

void shiftcons( ) : shifts all the consonants of the word at the beginning
followed by the vowels (e.g. spoon becomes spnoo)

void changeword( ) : changes the case of all occurring consonants of the


shifted word to uppercase, for e.g. (spnoo becomes SPNoo)

void show( ) : displays the original word, shifted word and the changed word
Specify the

class ConsChange giving the details of the constructor(),void readword( ),


void shiftcons( ), void changeword() and void show( ). Define the main( )
function to create an object and call the functions accordingly to enable the
task.

Algorithm

1.Start

2.Initialize class ConsChange with:

 word → to store the input word.

 len → to store the length of the word.

 sw → to store the shifted word (consonants first, vowels after).

 cw → to store the changed word (uppercase consonants).

3.Constructor (ConsChange())

 Set word = ""

 Set len = 0

4.Function readword()

55 | P a g e
 Input a word from the user in lowercase.

 Trim extra spaces.

 Store it in word.

 Find length of word → store in len.

5.Function shiftcons()

 Initialize two empty strings: consonants = "", vowels = "".

 Loop through each character of word.

o If character is a vowel (a, e, i, o, u) → add to vowels.

o Else if it is a consonant → add to consonants.

 Concatenate consonants and vowels.

 Store result in sw.

6.Function changeword()

 Initialize cw = "".

 Loop through each character of sw.

o If character is a consonant → convert to uppercase and add to


cw.

o If character is a vowel → add as it is.

7.Function show()

 Display the original word (word).

 Display the shifted word (sw).

 Display the changed word (cw).

8.Main function (main())

 Create object ob of class ConsChange.

 Call ob.readword().

 Call ob.shiftcons().

 Call ob.changeword().

 Call ob.show().

56 | P a g e
9.End

Program

57 | P a g e
58 | P a g e
Output

Question 17

59 | P a g e
Write a program to accept a sentence as input. The words in the string are to
be separated by a blank. Each word must be in upper case. The sentence is
terminated by either “.”,”!” or “?”. Perform the following tasks:

(i) Obtain the length of the sentence. (measured in words)

(ii) Arrange the sentence in alphabetical order of the words.

Test your program with the sample data and some random data:

Example 1:

INPUT: NECESSITY IS THE MOTHER OF INVENTION.

OUTPUT:

Length: 6

Rearranged Sentence:

INVENTION IS MOTHER NECESSITY OF THE

Algorithm

Step 1: Start

Step 2: Input the sentence in uppercase ending with ., !, or ?.

Step 3: Check the last character of the sentence.

 If it is ., !, or ?, remove this punctuation mark.

 Otherwise, display "Invalid sentence ending" and stop the program.

Step 4: Split the remaining sentence into individual words using space " " as
a delimiter.

Step 5: Count the number of words and store it as length.

Step 6: Sort the array of words in alphabetical order using the following
process:
a. For each word position i from 0 to length - 2:
- Compare words[j] with words[j+1].
- If words[j] is greater (comes later in dictionary order), swap them.

Step 7: Display the length (number of words).

Step 8: Print the rearranged sentence with words in alphabetical order.

60 | P a g e
Step 9: End

Program

Output

61 | P a g e
Question 18

62 | P a g e
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:

Check for the validity of the accepted sentence only for the terminating
character.

Arrange the words in ascending order of their length. If two or more words
have the same length, then sort them alphabetically.

Display the original sentence along with the converted sentence.

Test your program for the following data and some random data:

Example 1:

INPUT:

AS YOU SOW SO SHALL YOU REAP.

OUTPUT:

AS YOU SOW SO SHALL YOU REAP.

AS SO SOW YOU YOU REAP SHALL

Example 2:

INPUT:

SELF HELP IS THE BEST HELP.

OUTPUT:

SELF HELP IS THE BEST HELP.

IS THE BEST HELP HELP SELF

Algorithm

1.Start

2.Input sentence from the user.

 The sentence must be in UPPER CASE.

 The sentence must terminate with one of the following: . , ? , !.

63 | P a g e
3.Check validity of sentence termination

 Extract the last character of the sentence.

 If it is not . or ! or ?, display "Invalid termination." and stop.

4.Store the original sentence in a variable (origstr) for later display.

5.Remove the last character (terminating symbol) from the sentence.

6.Split the sentence into words using " " (space) as a delimiter.

7.Sort the words using the following criteria:

 Primary key: Word length (ascending).

 Secondary key: If two words have the same length, arrange them
alphabetically.

 Use nested loops (Bubble Sort) to compare adjacent words:

o If length(word[j]) > length(word[j+1]), swap them.

o If length(word[j]) == length(word[j+1]) and word[j] > word[j+1]


(lexicographically), swap them.

8.Display the original sentence (origstr).

9.Display the rearranged sentence (words after sorting).

10.End

64 | P a g e
Program

65 | P a g e
Output

66 | P a g e
Question 19

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

You can assume that no word in the sentence exceeds 15 characters, so that
you get a proper formatted output.

Perform the following tasks:

(i) Convert the first letter of each word to uppercase.

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

Test your program with the following inputs:

Example 1

INPUT: Intelligence plus character is education.

OUTPUT:

Intelligence Plus Character Is Education.

Word Vowels Consonants

Intelligence 5 7

Plus 1 3

Character 3 6

Is 1 1

Education 5 4

Example 2

INPUT: God is great.

OUTPUT:

God Is Great.

Word Vowels Consonants

God 1 2

Is 1 1

67 | P a g e
Great 2 3

Example 3

INPUT: All the best!

OUTPUT:

Invalid Input

Algorithm

1. Start

2. Input a sentence from the user.

3. Trim leading and trailing spaces from the sentence.

4. Extract the last character of the sentence.

5. IF the last character is NOT '.' AND NOT '?'

THEN print "Invalid Input" and stop.

6. Remove the last character ('.' or '?') from the sentence.

7. Split the sentence into words using a single space as the delimiter.

8. Initialize an empty string `formstr` for storing formatted sentence.

9. FOR each word in the list of words DO

a. Capitalize the first letter of the word and make the rest lowercase.

b. Append this capitalized word to `formstr` with a space.

c. Replace the word in the array with its capitalized form.

10. Print the formatted sentence (`formstr`).

11. Print the headings: "Word Vowels Consonants".

12. FOR each word in the list DO

a. Initialize counters `vowels = 0` and `consonants = 0`.

b. FOR each character `ch` in the word DO

i. Convert `ch` to lowercase.

ii. IF `ch` is a letter THEN

68 | P a g e
- IF `ch` is 'a', 'e', 'i', 'o', or 'u' THEN increment `vowels`.

- ELSE increment `consonants`.

c. Print the word, vowels count, and consonants count in tabular format.

13. End

Program

69 | P a g e
70 | P a g e
Output

Question 20
71 | P a g e
Write a program to print the initials of string recursively

A class Initials Print has been defined to print the initials of the name. Some
of the members of the class are given below:

Class name : InitialsPrint

Data members/instance variables:

String initials : to store the initials of the name

Member functions:

initialsPrint(): constructor to assign blank to initials.

void initRecursive(String s, int i): to store the initials of the name in the
variable initials as shown in the sample output using Recursive technique.

Sample Input: Narendra Damodardas Modi

Sample Output: N.D.M.

display(): to accept full name from the user and print the initials of string as
shown in the sample output.

Specify the class Initials Print the initials of string giving details of the
constructor, void initRecursive (String s, int i) and void display (). Write main
() to create and object and call the respective methods.

Algorithm

1.Start

2.Define class InitialsPrint with:

 Data member:

o String initials → stores the initials.

 Constructor InitialsPrint() → initializes initials to blank ("").

 Method void initRecursive(String s, int i) → recursively extracts initials.

 Method void display() → accepts input name, calls initRecursive(), and


displays initials.

3.Inside initRecursive(String s, int i):

 If i >= length of string s, then return (base case of recursion).

72 | P a g e
 Else if:

o i == 0 (first character of string) OR character at position i-1 is a


space:

 Append uppercase of s.charAt(i) followed by "." to initials.

 Recursive call: initRecursive(s, i + 1) to process the next character.

4.Inside display():

 Create a scanner to accept user input.

 Prompt user → "Enter full name:".

 Read full name into string name.

 Call initRecursive(name, 0).

 Print → "Initials: " + initials.

5.In main() method:

 Create object ob of class InitialsPrint.

 Call ob.display() to execute the program.

6.End

Program

73 | P a g e
Output

74 | P a g e
Question 21

75 | P a g e
Write a program to accept a sentence which may be terminated by either ‘.’
or ‘?’ or ‘!’ only. Any other character may be ignored. The words may be
separated by more than one blank space and are in uppercase.

Perform the following tasks:

(a) Accept a sentence and remove all the extra blank space between two
words to a single blank space.

(b) Accept any word from the user along with its position and insert the word
in the given position. The position is calculated by place value of each word
where first word is in position 1, second word in position 2 and so on.

(c) Display the modified sentence.

Algorithm

1.Start

2.Accept sentence from the user.

 Trim extra spaces from start and end.

 Check if the last character is either ., ?, or !.

o If not, display "Invalid sentence!" and stop.

 Replace multiple spaces between words with a single space.

3.Insert word at given position:

 If the sentence is empty, stop.

 Accept a word (str) from the user.

 Accept the position (pos) where the word should be inserted.

 Remove the last punctuation mark (end) temporarily.

 Split the sentence into words (arr).

 Check if pos is valid:

o If pos < 1 or pos > number of words + 1, print "Invalid position!"


and stop.

 Create a new sentence string newst:

o For each word in arr:

76 | P a g e
 If the index = position - 1, insert the new word first.

 Then add the current word.

o If position is at the end (arr.length + 1), append the new word


last.

 Add back the punctuation mark at the end.

 Save the modified sentence in st.

4.Display modified sentence.

5.End

Program

77 | P a g e
Output
78 | P a g e
79 | P a g e
Question 22

Write a program to accept a paragraph containing two sentences only. The


sentences may be terminated by either '.', '?' or '!' only. Any other character
may be ignored. The words are to be separated by a single blankspace and
must be in uppercase.

Perform the following tasks:

(a) Check for the validity of the accepted paragraph for the number of
sentences and for the

terminating character.

(b) Separate the two sentences from the paragraph and find the common
words in the two sentences with their frequency of occurrence in the
paragraph.

(c) Display both the sentences separately along with the common words and
their frequency, in the format given below.

Test your program for the following data and some random data:

EXAMPLE

INPUT:

IS IT RAINING? YOU MAY GET WET IF IT IS RAINING.

OUTPUT:

IS IT RAINING?

YOU MAY GET WET IF IT IS RAINING.

COMMON WORDS FREQUENCY

IS 2

IT 2

RAINING 2

80 | P a g e
Algorithm

Step 1: Start.

Step 2: Input a single string containing two sentences.

Step 3: Trim leading and trailing spaces from the string.

Step 4: Check for sentence-ending punctuation (., ?, or !).

 If more than two sentences are found → print "Invalid Input" and stop.

 Otherwise, split the string into sentence1 and sentence2 at the


punctuation mark.

Step 5: Verify that both sentences end with ., ?, or !.

 If not, print "Invalid!" and stop.

Step 6: Remove the punctuation marks from the end of both sentences.

Step 7: Break both sentences into words using a tokenizer (split by spaces).

 Convert each word into uppercase.

 Store words of sentence1 in array arr1.

 Store words of sentence2 in array arr2.

Step 8: Compare words from arr1 with words in arr2.

 For each word in arr1, count how many times it matches with words in
arr2.

 For every match, increase frequency by 2 (because it appears once in


each sentence).

Step 9: If frequency ≥ 2, print the word and its frequency.

Step 10: End.

81 | P a g e
Program

82 | P a g e
83 | P a g e
Output

84 | P a g e
Question 23

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:

(a) Find the number of words beginning and ending with a vowel.

(b) Place the words which begin and end with a vowel at the beginning,
followed by the remaining words as they occur in the sentence.

Test your program for words that start and end with a vowel with the sample
data and some random data: words that start and end with a vowel

Example 1

INPUT: ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.

OUTPUT: NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL= 3

ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL

Algorithm

1. Start

2. Input a sentence from the user (must be in uppercase and end with ., ?,
or !).

3. Check validity:

 Find the last character of the sentence.

 If the last character is not ., ?, or !, then print "INVALID SENTENCE!"


and stop.

4. Remove punctuation:

 Remove the last character from the sentence for further processing.

5. Split into words:

 Use a StringTokenizer to separate words.

 Store each word in an array.

6. Initialize variables:

85 | P a g e
 c = 0 (counter for words starting and ending with vowels).

 vowelWords = "" (string to store words beginning and ending with a


vowel).

 otherWords = "" (string to store all other words).

7. Process each word:

 For every word in the array:


a. Find the first and last character of the word.
b. If both are vowels (A, E, I, O, U):

o Increment c by 1.

o Add the word to vowelWords.


c. Otherwise, add the word to otherWords.

8. Output results:

 Print "NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = "


followed by c.

 Print the rearranged sentence: first all vowelWords, then all


otherWords, followed by the punctuation.

9. End

Program

86 | P a g e
87 | P a g e
Output

88 | P a g e
Question 24

A class Circular has been signed to print a set of elements in a circular


fashion. For example, if input is 1,2,3,4

output should be:

1,2,3,4

4,1,2,3

3,4,1,2

2,3,4,1

Class name: CircularShift

Data members/ instance variables:

list[ ]: store the elements

size: to store the number of elements

Member functions:

void input(): to input the size and the elements in the array

void Circular_Shift():to shift the elements of the array one place to the right.
First element comes to the second position, second element to the third and
ultimately the last element comes to the first position and so on.

void reverse(): reverse the array without using any temporary variable to
swap its elements.

89 | P a g e
void display(): to display the array in a circular fashion.

Specify the class CircularShift giving details of the constructor and member
functions void input(), void Circular_Shift(), void reverse(). void display()
define the main() function to create an object and call the functions
accordingly.

Algorithm

Step 1: Start

Step 2: Input array size

 Prompt the user to enter the number of elements n.

 Initialize an array arr of size n.

Step 3: Input array elements

 Repeat for i = 0 to n-1:

o Prompt the user to enter each element.

o Store the element in arr[i].

Step 4: Perform Circular Shift (Right Shift)

 Store the last element of the array in a temporary variable temp =


arr[n-1].

 Shift elements one position to the right:

o For i = n-1 down to 1:

 arr[i] = arr[i-1].

 Place the last element (temp) at the beginning:

o arr[0] = temp.

Step 5: Reverse the array (without using extra variable)

90 | P a g e
 Initialize two pointers: start = 0, end = n-1.

 While start < end:

o Swap arr[start] and arr[end] using arithmetic operations:

 arr[start] = arr[start] + arr[end]

 arr[end] = arr[start] - arr[end]

 arr[start] = arr[start] - arr[end]

o Increment start and decrement end.

Step 6: Display the array in circular fashion

 For i = 0 to n-1:

o For j = 0 to n-1:

 Print arr[(i + j) % n] (ensures wrap-around effect).

o Print newline after each row.

Step 7: End

Program

91 | P a g e
92 | P a g e
Output

93 | P a g e
Question 25

94 | P a g e
A class matrix contains an integer array of order [m * n]. The maximum
value possible for both m and n is 10.

Design a class matrix to find the difference of the two matrices. The details
of the members of the class are given below:

Class name : matrix

Data members:

atm[][] : to store the matrix

m, n : integer to store the number of rows and columns

Member functions:

Matrix(…..) : initialize m, n and to allocate memory to member array

void fnGet() : to fill the member array

void fnDisplay() : to show the member matrix

Matrix fnSub(Matrix A) : Subtract the current object from the matrix of


parameterized object and return the resulting object.

Specify the class Matrix, Define main (), giving the details of the above
member data and methods only.

Algorithm

1.Start

2.Input Matrix Dimensions

 Prompt the user to enter the number of rows r.

 Prompt the user to enter the number of columns c.

3.Create First Matrix (A)

 Initialize a Matrix object A of size r × c.

 Call fnGet() to input all elements of Matrix A.

4.Create Second Matrix (B)

 Initialize a Matrix object B of size r × c.

 Call fnGet() to input all elements of Matrix B.

95 | P a g e
5.Display Both Matrices

 Call fnDisplay() for Matrix A.

 Call fnDisplay() for Matrix B.

6.Perform Subtraction

 Call fnSub(A) using Matrix B.

 Inside fnSub():

1. Create a new Matrix result of size r × c.

2. For each element (i, j):

 Compute result[i][j] = B[i][j] - A[i][j].

3. Return the result matrix.

7.Display Result Matrix

 Call fnDisplay() for the resultant matrix C.

8.End

Program

96 | P a g e
97 | P a g e
98 | P a g e
Output

99 | P a g e
Question 26

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:

Sort the non-boundary elements in ascending order using any standard


sorting technique

and rearrange them in the matrix.

Calculate the sum of both the diagonals.

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


→ Display: "Enter the size of matrix (m > 3 && m < 10):"
→ Accept m.

3.Check validity

 If m ≤ 3 or m ≥ 10, display "Out of range!" and stop.

 Else, continue.

4.Input matrix elements

 Create a 2D array mat[m][m].

 For each row r from 0 to m-1:

o For each column c from 0 to m-1:

 Accept element and store in mat[r][c].

5.Display original matrix

 Print all elements of mat in matrix form.

6.Extract inner matrix elements

100 | P a g e
 Inner matrix = elements excluding boundary rows and columns.

 Copy them into a 1D array innerArr[].

7.Sort inner elements

 Arrange innerArr[] in ascending order using bubble sort / selection


sort logic.

8.Place back sorted inner elements

 Refill the sorted elements into their original inner matrix positions.

9.Display rearranged matrix

 Print the modified matrix in proper format.

10.Find diagonal elements & sum

 Traverse matrix and print only elements that belong to:

o Primary diagonal (r == c).

o Secondary diagonal (r + c == m - 1).

 While printing diagonals, add them into diagSum.

11.Display sum of diagonals

 Print: "Sum of diagonals = diagSum"

12.End

101 | P a g e
Program

102 | P a g e
103 | P a g e
Output

104 | P a g e
Question 27

105 | P a g e
Write a program to declare a square matrix A[][] of order MxM where ‘M’ is
the number of rows and thenumber 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 tasks:

Display the original matrix

Rotate the matrix 90 clockwise as shown below:

original matrix

123

456

789

Rotated matrix

741

852

963

Find the sum of the elements of the four corners of the matrix.

Algorithm

1. Start

2. Input matrix size m

o Display: "Enter the size of matrix (m > 2 && m < 10):"

o Accept m.

3. Check validity

o If m ≤ 2 or m ≥ 10, display "Out of range!" and stop.

o Else, continue.

4. Input matrix elements

o Create a 2D array a[m][m].

106 | P a g e
o For each row r from 0 to m-1:

 For each column c from 0 to m-1:

 Input element at (r, c) and store in a[r][c].

5. Display original matrix

o Print the elements of a[][] in proper matrix form.

6. Rotate the matrix 90° clockwise

o Create a new 2D array rot[m][m].

o Initialize k = m - 1.

o For each row r from 0 to m-1:

 For each column c from 0 to m-1:

 Set rot[c][k] = a[r][c].

 Decrease k by 1.

7. Display rotated matrix

o Print the elements of rot[][] in proper matrix form.

8. Calculate sum of corner elements

o Compute:

o sum = rot[0][0] + rot[0][m-1] + rot[m-1][0] + rot[m-1][m-1]

o Display "Sum of Corner Elements is " + sum.

9. End

Program

107 | P a g e
Output

108 | P a g e
Question 28

109 | P a g e
Write a program to declare a matrix A[][] of order (MXN) where ‘M’ is the
number of rows and ‘N’ is the number of columns such M and N must be
greater than w and less than 20

Allow the user to input integers into this 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 ascending order using any standard
sorting technique and rearrange them in the matrix.

Algorithm

1.Start

2.Input matrix size

 Read number of rows m and columns n.

 Check if (m > 2 && m < 20) and (n > 2 && n < 20).

 If not, display “Out of range !” and stop.

3.Input matrix elements

 Create a 2D array p[m][n].

 For each row i from 0 to m-1


For each column j from 0 to n-1
→ Read element into p[i][j].

4.Display the original matrix.

5.Find the minimum and maximum elements with positions

 Initialize min[0] = max[0] = p[0][0] and positions (0,0).

 Traverse each element of the matrix:

o If current element < min[0], update min[0] and its position.

o Else if current element > max[0], update max[0] and its position.

 Print the smallest and largest elements with their positions.

110 | P a g e
6.Flatten the matrix into a 1D array s

 Copy all elements of p row-wise into s.

7.Sort the array s in ascending order

 Use nested loops to compare and swap elements.

8.Reconstruct the sorted matrix

 Copy back elements from s into p, row by row.

9.Display the sorted matrix.

10.End

Program

111 | P a g e
112 | P a g e
Output

113 | P a g e
114 | P a g e

You might also like