0% found this document useful (0 votes)
11 views151 pages

Computer Project

Uploaded by

Manas pandey
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
11 views151 pages

Computer Project

Uploaded by

Manas pandey
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 151

LUCKNOW PUBLIC COLLEGE

Sahara States, Jankipuram

2024-25

SUBMITTED BY – SUBMITTED TO –

Name – Shista Pandey


Class & Sec – XII A

Roll Number– 26
UID –

Index Number - Subject -


CERTIFICATE
Name-

Class & Sec- Roll Number-


UID- Index Number-

This is certified to be the bona fide work of the


student in the Computer Science Laboratory
during the academic year 2021-22.

No. of practical certified out of in


the subject of Computer Science.

Sign. of Internal Examiner:

Sign. of External Examiner:


ACKNOWLEDGMENT

I would like to express my special thanks of


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

Name:
Class & Sec:
Number
Programs
Question 1-

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.

Thus 9 is an evil no.

A few evil numbers are 3, 5, 6, 9 ...

Design a program to accept a positive whole no. ‘N’ where N>2 and
N<100. Find the binary equivalent of the number and count the
number of 1s in it and display whether it is an evil no. or not with an
appropriate message.

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

Example 1:

INPUT: N= 15

BINARY EQUIVALENT: 1111

NUMBER OF 1’s: 4

OUTPUT: EVIL NUMBER

→ALGORITHM
Step-1: Start
Step-2: Enter a decimal number.
Step-3: Convert the number into its binary equivalent.
Step-4: Calculate the number of 1 in binary equivalent.
Step-5: Using for loop, taking one digit at a time, check whether it
is equal to 1. Increment count1 variable by 1 if the digit is
equal to 1.
Step-6: Check whether variable count1 is even or not. If n is even,
then it is an evil number, otherwise not an evil number.
Step-7: Stop

→CODE
//Program to accept a positive whole number, find its binary
equivalent, count the number of 1s and display whether it is an evil
number or not
import java.util.Scanner;
class Evil
{
int n, a, count1=0;
String s = "";
void input ()
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter decimal number ");
n = sc.nextInt();
System.out.println("INPUT:"+n);
}
void calculate ()
{
Input ();
while(n>0)
{
a = n%2;
If (a == 1)
{
count1++;
}
s = a+" "+s;
n = n/2;
}
System.out.println("BINARY EQUIVALENT:" +s);
System.out.println("NO. OF 1's " +count1);
}
void count ()
{
Calculate ();
If ( count 1 %2 ==0)
System.out.println("\n EVIL NUMBER");
else
System.out.println("\nNOT AN EVIL NUMBER");
}
public static void main (String args[])
{
Evil bin=new Evil();
Evil();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
n to store decimal number int
a to store modulus value int
count1 to count no. of 1’s int
s to store binary equivalent String

→OUTPUT
Enter decimal number
24
BINARY EQUIVALENT:1 1 0 0 0
NO. OF 1’s 2
EVIL NUMBER
Question 2-

An emirp number is a number which is prime backwards and


forwards Example: 13 and 31 are both prime numbers. Thus 13 is an
emirp number. Design a class Emirp to check if a given number is
Emirp number or not. Some of the members of the class are given
below:
Class name: Emirp
Data Members
n : Stores the number
rev. : stores the reverse of the number
f. : stores the divisor
Member function
Emirp(int nn) : to assign n=nn, rev =0, and f=2
int isprime(int x):check if the number is prime using the recursive
technique and return 1 if prime otherwise return 0
void isEmirp():reverse the given number and check if both the
original number and the reverse number are prime, by invoking the
function isprime(int) and display the result with an appropriate
message.
Specify the class Emirp giving details of the constructor(int ), int
isprime(int) and void isEmirp(). Define a main() function to create an
object and call the methods to check for Emirp number.

→ALGORITHM
Step-1: Start
Step-2: Initialize rev =0 and divisor f=2
Step-3: Check the given number (n) is prime or not
Step-4: Check by using recursive technique and return 1 if prime
otherwise return 0
Step-5: If prime, find the reverse of the given number (n).
Step-6: Check if the reverse of the number is prime or not
Step-7: Create main and call the functions
Step-8: Stop
→CODE
import java.util.*;
public class Emirp
{
int n ,rev, f;
Emirp(int nn)
{
n=nn;
rev=0;
f=2;
}
int isprime(int x)
{
if(n==x)
{
return 1;
}
else if(n % x==0 || n==1)
{
return 0;
}
else
{
return isprime(x+1);
}
}
void isEmirp()
{
int x=n;
while(x!=0)
{
rev=(rev*10)+x%10;
x=x/10;
}
int a=isprime(f);
x=n;
n=rev;
f=2;
int b=isprime(f);
if(a==1 && b==1)
{
System.out.println(x+” is an Emirp number”);
}
else
{
System.out.println(x+” is not an Emirp number”);
}
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the number:”);
int x=sc.nextInt();
Emirp obj=new Emirp(x);
obj.isEmirp();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
N to store number to be int
checked
F to store the divisor int
nn to assign n int
X to pass value to n int
rev to store reverse int
A to store 1 if number is prime int
B to store 1 if reverse of int
number is prime

→OUTPUT
Enter the number:
13
13 is an Emirp number
Enter the number:
51
51 is not an Emirp number
Question 3-

A disarium number is a number in which the sum of the digits to the


power of their respective position is equal to the number itself.

Example-: 135=1

Design a class Disarium to check if a given number is a disarium


number or not .Some of the members of the class are given below:

Class name: Disarium

Data Members/Instance Variable

n : stores the number

size : stores the size of the number

Member Methods/Function

Disarium(int nn) : parameterized constructor to initialize the data


members n=nn and size==0

void countDigit() : counts the total number of digits and assigns it


to the size

int sumofDigits : to return the sum of the digits of the number (n) to
the power of their respective positions.

void check() : checks whether the number is a disarium number and


display the result with an appropriate message.

Specify the class Disarium giving the details of the constructor (),void
countDigit(), int sumofDigits() and void check(). Define the main()
function to create an object and call the functions accordingly to
enable the task.
→ALGORITHM

Step-1: START

Step-2: Create a class with name Disarium

Step-3: Declare instance variable nn(to store the given number)


and size( to find the no. of digits present in number).

Step-4: Disarium() function is a parameterised consturctor to


initialise n=nn and size=0.

Step-5: Function countDigits() to find out the size of digits.

int num=n;

while(num>0)

int d=num%10;;

size++;

num=num/10;

Step-6: Function sumofDigits() to return the sum of the digits of


the number (n) to the power of their respective positions.

Step-7: Function check() to check whether the given number is a


disarium number or not.

Step-8: Create an object of a class

Step-9: Call the function

Step-10: Stop
→CODE

import java.util.*;

public class Disarium

int n,size;

Disarium(int nn)

n=nn;

size=0;

void countDigits()

int num=n;

while(num>0)

int d=num%10;;

size++;

num=num/10;

int sumofDigits()
{

int num=n;

while(num>0)

int d=num%10;

sum= sum+(int)Math.pow(d,size);

num=num/10;

size--;

return sum;

void check()

if(sumofDigits()==n)

System.out.println(n+" is a Disarium number");

else

System.out.println(n+" is not a Disarium number" );

public static void main(int nn)

Disarium ob=new Disarium(nn);


ob.countDigits();

ob.check();

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


N to store given number int
Size to store the total number of int
digits
D to store the last digit of a int
number
Num to store the given number int

→OUTPUT

135 is a Disarium number

89 is a Disarium number

241 is not a Disarium number

518 is a Disarium number


Question 4-

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.
For example-
192 x 1 = 192
192 x 2 = 384
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: Multiply the given number by 2 and 3 separately
Step-3: Concatenate the results from step-2 with the given
number by converting to string
Step-4: Run for loop from 49-57(ASCII code of 1-9)
Step-5: Run nested loop till length of string
Step-6: Check whether each digit is present in the string by
extracting characters from the string
Step-7: If a digit does not appear in the string or is repeated,
terminate loop and set flag variable to false
Step-8: If flag variable is true, display “It is a fascinating number”,
else, display “It is not a fascinating number”
Step-9: Stop
→CODE
import java.util.*;
class fascinating
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,n2,n3,i,j,c;
char ch;
boolean b=true;
System.out.println("Enter a number");
n=sc.nextInt();
n2=n*2;
n3=n*3;
String str=""+n+n2+n3;
for(i=49;i<=57;i++)
{
c=0;
for(j=0;j<str.length();j++)
{
ch=str.charAt(j);
if(i==ch)
c++;
}
if(c!=1)
{
b=false;
break;
}
}
if(b)
System.out.println("It is a fascinating number");
else
System.out.println("It is not a fascinating number");
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
N To store inputted number int
n2 Number x 2 int
n3 Number x 3 int
I Looping variable int
J Looping variable int
C Counter variable int
ch To extract characters char
B Flag variable boolean
str Concatenated string String

→OUTPUT
Enter a number
192
It is a fascinating number
Enter a number
193
It is not a fascinating number
Question 5-

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

Step-1: Start

Step-2: Create a class named PrimeAdam .

Step-3: First, we will create a function to find the reverse of the


number.

Step-4: Now by creating another function we will find the square


the number inputted and the square of its reverse.

Step-5: Further we will create function: isPrime(int num) to check


for prime numbers .

Step-6: Now create main function.

Step-7: Now take the frequency of prime adam numbers in the


main function using the required code.

Step-8: Stop

→CODE

import java.util.Scanner ;

public class PrimeAdam

int reverse(int num)

int rev = 0;

while (num != 0)
{

int d = num % 10;

rev = rev * 10 + d;

num /= 10;

return rev;

boolean isAdam(int num)

int sqNum = num * num;

int revNum = reverse(num);

int sqRevNum = revNum * revNum;

int rev = reverse(sqNum);

return rev == sqRevNum;

boolean isPrime(int num)

int c = 0;

for (int i = 1; i <= num; i++)

if (num % i == 0)
{

c++;

return c == 2;

public static void main(String args[])

Scanner in = new Scanner(System.in);

System.out.print("Enter the value of m: ");

int m = in.nextInt();

System.out.print("Enter the value of n: ");

int n = in.nextInt();

int count = 0;

if (m >= n)

System.out.println("INVALID INPUT");

return;

System.out.println("THE PRIME-ADAM INTEGERS ARE:");


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

boolean adam = isAdam(i);

if (adam) {

boolean prime = isPrime(i);

if (prime) {

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

count++;

if (count == 0) {

System.out.print("NIL");

System.out.println();

System.out.println("FREQUENCY OF PRIME-ADAM INTEGERS IS: "


+ count);

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


Rev to store the reverse of int
the number inputted
m and n positive integers to fix the int
range
sqNum to store square of the int
number
revNum to store the product of int
the number and its reverse
sqRevNum to store square of the int
reverse of the number
count to store the frequency of the int
Prime Adam numbers

→OUTPUT
Question 6-

Design a class Revno which reverses an integer number.

Example: 94765 becomes 56749 on reversing the digits of the


number.

Some of the members of the class are given below:

Class name: Revno

Data member/instance variable:

num: to store the integer number

Member functions/methods:

Revno(): default constructor

void inputnum: to accept the number

int reverse(int nn): returns the reverse of number by using


recursive technique

void display(): displays the original numbe along with its reverse b
invoking the method recursive

Specify the class Revno, giving details of the constructor, void


inputnum(), int reverse(int) and void display(). Define the main()
function to create an object and call the functions accordingly to
enable the task.

→ALGORITHM

Step-1: Start
Step-2: Create default constructor
Step-3: Create function inputnum() to accept number
Step-4: Create function reverse(int nn) with return type ‘int’ to
reverse the original number
Step-5: Display the original and reversed number
Step-6: Stop

→CODE
import java.util.*;
class Revno
{
int num;
Revno()
{
num=0;
}
void inputnum()
{
Scanner sc= new Scanner (System.in);
System.out.println("Enter the number:");
num=sc.nextInt();
}
void Reverse(int num)
{
if(num<10)
{
System.out.println(num);
return;
}
else
{
System.out.print(num%10);
Reverse(num/10);
}
}
void display()
{
System.out.println("Original Number:\n"+num);
System.out.println("Reversed Number: ");
Reverse(num);
}
public static void main()
{
Revno ob= new Revno();
ob.inputnum();
ob.display();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
num to input number int

→OUTPUT
Enter the number:

123456789

Original Number:

123456789

Reversed Number:

987654321
Question 7-

Design class ArmNum to check if a given number is Armstrong


number or not.

A number is said to be Armstrong if sum of its digits to the power of


length of the number is equal to the number

Example

372 = 33+73+13

1634 = 14+64+34+44

54748 = 55+45+75+45+85

Thus, 371, 1634 and 54748 are all examples of Armen or numbers

Some of the members of the class are given below:

Class Name: ArmNum

Data members

n: to store the number

I: to store the length of the number

Methods/ Member functions

ArmNum

(int nn): parameterised constructor initialise the data member n=nn

int sum pow(int i): returns the sum of each digit raised to the power
of the length of the number using recursive technique e.g., 34 will
return 3 2 + 42 (as the length of the number is 2)
void is Armstrong(): checks whether the given number is an
Armstrong number by invoking the function sum_pow () and displays
the result with an appropriate message

Specify the class ArmNum giving details of the constructor(), int


sum_pow(int) and void isArmstrong (). Define a main() function to
create an object and call the functions accordingly to enable the task.

→ALGORITHM

Step-1: Start
Step-2: Accept the input number
Step-3: Initialize variables: n(input number), I(length of the
number), sum (to store the sum of digits raised to the
power of length)
Step-4: Calculate the length of the number using a function
'getLength(num)'
Step-5: Initialize sum as 0
Step-6: Iterate through each digit of the number:
- Extract the rightmost digit using modulo operator.
- Raise the digit to the power of the length of the
number.
- Add the result to the sum.
- Remove the rightmost digit by dividing the number
by 1 0. Repeat until all digits are processed.
Step-7: Check if the calculated sum is equal to the original
number:
- If yes, then the number is an Armstrong number.
Print a message indicating that.
- If no, then the number is not an Armstrong number.
Print a message indicating that.
Step-8: Stop

→CODE
Import java.util.*;
{
Public class ArmNum
{
int n; int l;
// Parameterized constructor to initialize data members
ArmNum(int nn)
{
n = nn;
I = getLength(n);
}
// Method to calculate length of the number int getLength(int num)
{
int length = 0; while (num !=0)
length++; num 10;
return length;
}
// Recursive function to calculate sum of digits raised to the power of
length int sum_pow(int i)
{
if (i<0){
return 0;
int digit =
return (int) Math.pow(digit,l)+ sum_pow(i/ 1 0);
// Method to check if the number is Armstrong or not
void isArmstrong(){
if (sum_pow(n) ==n)
System.out.println(n + " is an Armstrong number."); else
System.out.println(n + " is not an Armstrong number.");
}
public static void main(String[] args)
{
ArmNum armNum = new ArmNum(num); armNum.isArmstrong();
}
}
}
→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
n to input number Int
l length of inputted number Int
sum the sum of digits raised to Int
the power of the length
num Input number provided via Int
command-line argument
armnum An instance of the ArmNum Int
class

→OUTPUT
Input : 1634

1634 is an Armstrong number

Input : 216

216 is not an Armstrong number


Question 8-

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.

→ALGORITHM

Step-1: Start
Step-2: Take the input of the number and store in 'n'
Step-3: Verify whether the number is greater than 4 If not then
show invalid input
Step-4: Check whether the n in prime or not
Step-5: Make a function to get the prime pair and odd prime pair
Step-6: Print the pairs of the inputted gold batch number
Step-7: Stop

→CODE
import java.util.*;
public class Goldbach_PrimePairs
{
public static void main(String[] args)
{
//TAKE INPUT USING SCANNER METHOD
Scanner sc = new Scanner(System.in); System.out.print("N = ");
int n=sc.nextInt(); if(n>4)
//VALIDATE THE NUMBER TO BE A GOLD BACH NUMBER
{
if(n>9&&n<50)
{ if(n%2==0)
{
System.out.println ("PRIME PAIRS ARE :"); goldbach(n);
}
else
{
System.out.println ("INVALID INPUT.NUMBER IS ODD");
}
}
else
{
System.out.println ("INVALID INPUT.NUMBER OUT OF RANGE");
}
}
else
{
System.out.println ("NOT A GOLDBACH NUMBER");
}
}public static void goldbach( int num )
//FUNCTION TO GET THE PRIME PAIRS
{
for(int i=1;i<num;i++)
{
if(oddprime(i))
{
int op = num-i; if(oddprime(op)&&i<=op)
{
System.out.println (i+" , "+op);
}
}
}
}
public static boolean oddprime(int u)
//FUNCTION TO GET THE ODDPRIMES
{
if(u%2!=0&&prime(u)) return true;
else
return false;
}
public static boolean prime(int p)
//FUNCTION TO GET THE PRIMES
{
int c=0;

for(int i=1;i<=p;i++)
{
if(p%i==0) c++;
}
if(c==2) return true; else
return false;
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
num to input number int
pair[] Used for an array int
i Used for primary loop int
j Used for secondary loop int
sum Used to calculate sum int
c Used as a counter int
k Used as a counter int
flag Used as a flag int

→OUTPUT
N = 46

PRIME PAIRS ARE:


3, 43

5, 41

17, 29

23, 23
Question 9-

Design a class Perfect to check if a given number is a perfect number


or not.

[A number is said to be perfect if sum of the factors of the number


excluding itself is equal to the original number]

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


itself)

Some of the members of the class are given below: Class name:
Perfect Data members/instance variables: num: to store the number
Methods/Member functions: Perfect

(int nn): parameterized constructor to initialize the data member


num=nn

int sum_of_factors(int i): returns the sum of the factors of the


number(num), excluding itself, using a recursive technique

void check(): checks whether the given number is perfect by invoking


the function sum_of_factors() and displays the result with an
appropriate message Specify the class Perfect giving details of the
constructor(),

int sum_of_factors(int) and void check(). Define a main() function to


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

→ALGORITHM

Step-1: Start
Step-2: Class Definition:
- Define a class named `Perfect`.
Step-3: Data Members:
- Declare an integer data member `num` to store the
number.
Step-4: Constructor:
- Define a parameterized constructor `Perfect(int nn)`:
- Initialize the data member `num` with the value of `nn`.
Step-5: Method: sum_of_factors:
- Define a private method `int sum_of_factors(int i)`:
- If `i` is 1, return 0 (base case for recursion).
- If `num` is divisible by `i` (i.e., `num % i == 0`),
add `i` to the result of `sum_of_factors(i - 1)`.
- Otherwise, return the result of `sum_of_factors(i - 1)`
without adding `i`.
Step-6: Method: check:
- Define a public method `void check()`:
- Call `sum_of_factors(num - 1)` to get the sum of the
factors of `num` excluding itself.
- If the sum is equal to `num`, print that `num` is a perfect
number.
- Otherwise, print that `num` is not a perfect number.
Step-7: Main Method:
- Define the `main` method:
- Create an object of the `Perfect` class with a specific
number (e.g., `Perfect p = new Perfect(6)`).
- Call the `check()` method on the object to check if the
number is perfect.
Step-8: Stop

→CODE
class Perfect {
private int num;

// Parameterized constructor to initialize the data member num


public Perfect(int nn) {
num = nn;
}

// Function to return the sum of factors of the number excluding


itself, using recursion
private int sum_of_factors(int i) {
if (i == 1) {
return 0;
}
if (num % i == 0) {
return i + sum_of_factors(i - 1);
} else {
return sum_of_factors(i - 1);
}
}

// Function to check if the number is perfect


public void check() {
int sum = sum_of_factors(num - 1);
if (sum == num) {
System.out.println(num + " is a perfect number.");
} else {
System.out.println(num + " is not a perfect number.");
}
}

// Main function to create an object and call the functions


public static void main(String[] args) {
Perfect p = new Perfect(6); // Example: Checking for the number
6
p.check();
}
}
→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
num to input number Int
nn Parameter for the int
constructor, used to initialize
num.
i Used as a parameter in the int
sum_of_factors method to
denote the current divisor
being checked.
sum Stores the sum of factors of int
num excluding itself in the
check method.

→OUTPUT
Input: 6

6 is a perfect number

Input: 28

28 is a perfect number
Question 10-

A class Merger concatenates two positive integer that are greater


than 0 and produces a new merged integer.

Example: If the first number is 23 and the second is 764, then the
concatenated then the concatenated number will be 23764.

Some of the members of the class are given below:

CLASS NAME : Merger

DATA MEBERS:

n1- long integrers to store the first number

n2- long integers to store second number

mergNum- long integer to store the merged number

MEMBER FUNCTION:

Merger()- constructor to initialise the data members

void readNum()- to accept the values of data members n1 and n2

void JoinNum()- to concatenate the numbers n1 and n2 and store it


in mergNum

void show()- to display the original numbers and the merged number
with appropiate messages

Specify the class Merger , giving the details of the constructor(), void
readNum(), void JoinNum() and voidshow(). Define the main()
function to create an object and call the functions accordingly to
enable the task.
→ALGORITHM

Step-1: Start
Step-2: DECLARE THE DATA VARIABLES
Step-3: CREATE THE MEMBER METHODS TO ACCEPT THE VALUES
OF N1,N2
Step-4: TO CONCATENATE THE NUMBERS N1 AND N2 AND STORE
IT IN mergNum
Step-5: NOW DISPLAY ORIGINAL NO AND MERGED NO.
Step-6 Stop

→CODE
import java util.;
class Merger
{
long n1, n2;
long mergNum;
public Merger()
{
n1=1;
n2=1;
mergNum=11;
}
public void readNum()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter first number”);
n1=(int)Math.abs(sc.nextLong());
System.out.print("Enter second number:");
n2=(int)Math.abs(sc.nextLong());
if(n1==0) n1=1;
if(n2==0) n2=1;
}
public void joinNum()
{
String num1 = Long.toString(n1);
String num2 = Long.toString(n2);
String merged=num1 + num2;
mergNum=Long.parseLong(merged);
}
public void show()
{
System.out.println("First Number: "+n1);
System.out.println("Second Number: "+n2);
System.out.println("Merged Number: "+mergNum);
}
public static void main(String args[])
{
Merger obj=new Merger));
obj.readNum();
obj.joinNum();
obj.show();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
n1 to store first number long
n2 To store second number Long
mergNum To store merged number Long

→OUTPUT
Enter first number:

34567

Enter second number:

873490
First number: 34567

Second number: 873490

Merged number: 34567873490


Matrix
(Double-
Dimensional
Array)
Programs
Question 11-

Write a program to declare a matrix A[][] of order (M × N) where 'M'


is the number of rows and 'N' is the number of columns such that the
values of both 'M' and 'N' must be greater than 2 and less than 10.
Allow the user to input integers into this matrix. Perform the
following tasks on the matrix:

1. Display the original matrix.

2. Sort each row of the matrix in ascending order using any


standard sorting technique.

3. Display the changed matrix after sorting each row.

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

Example 1

INPUT:

M=4

N=3

ENTER ELEMENTS OF MATRIX:

11 -2 3

5 16 7

9 0 4

3 1 8

OUTPUT:

ORIGINAL MATRIX
11 -2 3

5 16 7

9 0 4

3 1 8

MATRIX AFTER SORTING ROWS

-2 3 11

5 7 16

0 4 9

1 3 8

→ALGORITHM

Step-1: Start

Step-2: Accept the value of m and n (rows and columns).

Step-3: Return and print matrix out of range if the condition on


step 4 is true.

Step-4: If(m<=2||m>=10||n<=2||n>=10)

Step-5: Initialization and declaration of matrix A.

Step-6: Run for loop until the value of i is less than m.

Step-7: Run for loop until the value of j is less than n.

Step-8: Enter the elements in matrix A.

Step-9: Print original matrix using for loops.


Step-10: Check in each row of the matrix whether the element next
to the previous element is greater than it or not.

Step-11: If the next element is greater than the previous one, then
swap their positions.

Step-12: Print the sorted matrix using for loops.

Step-13: Stop

→CODE

// program to sort each row of the matrix in ascending order

import java.util.Scanner;

public class ArraySort

public static void main(String args[])

Scanner in = new Scanner(System.in);

System.out.print(“ENTER THE VALUE OF M: “);

int m = in.nextInt();

System.out.print(“ENTER THE VALUE OF N: “);

int n = in.nextInt();

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

System.out.println(“MATRIX SIZE OUT OF RANGE.”);


return;

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

System.out.println(“ENTER ELEMENTS OF MATRIX:”);

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

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

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

A[i][j] = in.nextInt();

System.out.println(“ORIGINAL MATRIX”);

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

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

System.out.print(A[i][j] + “ “);

System.out.println();

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

for (int j = 0; j < n – 1; j++)

for (int k = 0; k < n – j – 1; k++)

if (A[i][k] > A[i][k + 1])

int t = A[i][k];

A[i][k] = A[i][k+1];

A[i][k+1] = t;

System.out.println(“MATRIX AFTER SORTING ROWS”);

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

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

System.out.print(A[i][j] + “ “);
}

System.out.println();

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


M To store the value of m int
N To store the value of n int
A To store the elements of int
matrix
I Variable used in for loop int
J Variable used in for loop int
K Variable used in for loop int
T Temporary variable used for int
swapping

→OUTPUT
ENTER THE VALUE OF M: 3

ENTER THE VALUE OF N: 3

ENTER ELEMENTS OF MATRIX:

22 7 9
5 36 13

19 12 6

ORIGINAL MATRIX

22 5 19

7 36 12

9 13 6

MATRIX AFTER SORTING ROWS

5 19 22

7 12 36

6 9 13
Question 12-

Design a class MatRev to reverse each element of a matrix.


Example –
Matrix A Matrix B
72 371 5 27 173 5
12 6 426 21 6 624
5 123 94 5 321 49
Some of the members of the class are given below:
Class Name: MatRev
Data Members/instance variables:
arr[][]: to store integer elements
m: to store the number of rows
n: to store the number of columns
Member Functions/methods:
MatRev(int mm , int nn): parameterized constructor to initialise
the data members m=mm and n =nn
void fillarray(): to enter elements in the array
Int reverse (int x): returns the reverse of the number x
Void revMat(MatRev P): reverses each element of the array of the
parameterized object and stores it in the
array of the current object
Void show(): displays the array elements in the matrix
form
Define the class MatRev giving details of the constructor(),void
fillarray(), int reverse(int x), void revMat(MatRev) and void
show().Define the main() function to create objects and call the
functions accordingly to enable the task.

→ALGORITHM

Step-1: Start

Step-2: Declare a class name MatRev


Step-3: Declare instance variables- arr[][],m and n

Step-4: Create a parameterized constructor to initialise the


instance variables m=mm and n=nn

Step-5: Create a function fillarray() to enter elements into the


matrix

Step-6: Create a function reverse(int x) to reverse elements of the


matrix

Step-7: Create a function revMat(MatRev P) to reverse and store


the elements into a new matrix

Step-8: Create a function show() to display the new matrix

Step-9: Create the static function and pass the values into the
constructor

Step-10: Create an object “ob” and call all the functions

Step-11: Stop

→CODE

import java.util.*;

class MatRev

int arr[][];

int m;

int n;
MatRev(int mm,int nn)

m=mm;

n=nn;

arr=new int[m][n];

void fillarray()

Scanner in=new Scanner(System.in);

System.out.println("Enter elements in the array");

int i,j;

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

for(j=0;j<n;j++)

arr[i][j]=in.nextInt();

int reverse (int x)


{

int d,r=0;

while(x!=0) //calculating reverse of a number

d=x%10;

r=r*10+d;

x=x/10;

return r;

void revMat(MatRev P)

int i,j;

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

for(j=0;j<n;j++)

this.arr[i][j]=reverse(P.arr[i][j]); //calling reverse


function

}
}

void show() //function to display the new matrix

int i,j;

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

for(j=0;j<n;j++)

System.out.print(arr[i][j]+"\t");

System.out.println();

public static void main(int a, int b)

MatRev ob=new MatRev(a,b); //passing values into the


constructor

ob.fillarray(); //calling functions

ob.revMat(ob);

ob.show();

}
}

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


arr[][] To store matrix int
m To store number of rows int
n To store number of columns int
mm To initialize value to m int
nn To initialize value to n int
i Control variable in for loop int
j Control variable in for loop int
r for calculating reverse int
d for calculating reverse int
x the number being reversed int
a to pass the value into int
constructor

→OUTPUT

Enter elements in the array

11 12 13 14 15 16 17 18 19

11 21 31
41 51 61

71 81 91
Question 13-

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 technique and display the sorted array.

2. Fill the square matrix b[][] in the following format . If the array a[]
= { 5,2,1,8} then the matrix b[][] would be fill as below:

1 2 5 8

1 2 5 1

1 2 1 2

1 1 2 5

3. Display the filled Matrix in the above format.

→ALGORITHM

Step-1: Start

Step-2: Enter the Size of N such that N >2 and N<10

Step-3: If the value of N if N< 2 or N>10 the print - matrix size out
of range

Step-4: Accept array a[N] by running a loop;


Step-5: Sort the array a[] in ascending order using bubble sort
technique

Step-6: Print the sorted array

Step-7: Accept the array b[][] of size N x N

Step-8: Check whether i+j <= N or not if b[i][j] = a[j] else b[i][j] =
a[i+j-(N-1)-1)

Step-9: Print the filled array

Step-10: Stop

→CODE

import java.util.*;

class array

public static void main(String args[])

int i,j,t,N;

Scanner in = new Scanner(System.in);

System.out.println(" enter the size of N such that N >2 &&


N<10" );

N = in.nextInt();

int a[] = new int[N];

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

System.out.println("Matrix out of range");

else

System.out.println(" enter the elements :");

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

a[i] = in.nextInt();

for( i =0; i<(N-1);i++)

for(j=0;j<((N-1)-i);j++)

if(a[j]>a[j+1])

t= a[j];

a[j] = a[j+1];

a[j+1] = t;

}
System.out.println(" sorted array in ascending order;");

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

System.out.println(a[i]);

// square matrix

int b[][] = new int[N][N];

System.out.println(" filled matrix :");

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

for(j =0;j<N;j++)

if( (i+j) <=( N -1))

b[i][j] = a[j];

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

else

int k = i+j;

b[i][j] = a[(k-(N-1))-1];

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

}
}

System.out.println();

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


a[] To store single dimensional int
array
b[][] To store single dimensional int
array
N To store size of array int
I Control variable in for loop int
J Control variable in for loop int
K To store sum of rows and int
columns

→OUTPUT

enter the size of N such that N >2 && N<10

4
enter the elements:

5 2 1 8

sorted array in ascending order;

1 2 5 8

filled matrix:

1 2 5 8

1 2 5 1

1 2 1 2

1 1 2 5
Question 14-

A class Sum_rowcol is declared as follows:

Class name: Sum_rowcol

Data members/instance variables:

mat[20][20]: Double dimensional integer array

m,n: (integers) Number of rows and number of column


mat[][].

Member functions/methods:

void row_col(int mx, int nx): To assign mx to m and nx to n

void read row_co(): To read matrix mat[][] of m x n

void display_mat(): To print the matrix of m x n order


row-wise

void sum_mat(): To store sum of all the rows and


column in their respective rows and
columns in the matrix mat [][]
and Print the newly created matrix

Specify the class Sum_rowcol giving the details of the functions void
row_col (int mx, int nx), void read row_col(), void display_mat() and
void sum_mat().

→ALGORITHM

Step-1: Start
Step-2: Creating a new matrix mat and defining member
variables.

Step-3: Defining a default constructor which initializes the


matrix’s all elements with zero.

Step-4: Defining a parameterized constructor to initialize the


variables m and n.

Step-5: Defining the read_row_col function to take input from the


user.

Step-6: Defining the display_mat function to display the final


matrix with the sum of elements of row and
columns.

Step-7: Defining the sum_mat function to calculate the sum of


rows and columns and store it in their respective indexes.

Step-8: Defining the main function.

Step-9: Creating an object of the class to call various member


functions.

Step-10: Invoking function row_col to initialize the number of rows


and columns.

Step-11: Invoking function read_row_col to take input from the


user.

Step-12: Invoking function sum_mat to calculate the required sum


of the rows and the columns.

Step-13: Invoking function display_mat to display the output.

Step-14: Stop
→CODE

import java.util.*;

public class Sum_rowcol {

int mat[][] = new int[5][5];

int m, n, i, j;

Sum_rowcol() {

for (i = 0; i < 5; i++) {

for (j = 0; j < 5; j++) {

mat[i][j] = 0;

void row_col(int mx, int nx) {

m = mx;

n = nx;

void read_row_col() {

Scanner in = new Scanner(System.in);

System.out.println("Enter a number one by one in a matrix :");

for (i = 0; i < m-1; i++) {

for (j = 0; j < n-1; j++) {


mat[i][j] = in.nextInt();

void display_mat() {

System.out.println("Elements of the matrix are : ");

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

for (j = 0; j < n; j++) {

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

System.out.print(i==m-1?" " : " ");

System.out.println();

void sum_mat() {

int c, r;

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

r = 0;

for (j = 0; j < n; j++) {

r = r + mat[i][j];

}
mat[i][n-1] = r;

for (i = 0; i < n-1; i++) {

c = 0;

for (j = 0; j < m; j++) {

c = c + mat[j][i];

mat[m-1][i] = c;

public static void main(String args[]){

Sum_rowcol obj=new Sum_rowcol();

obj.row_col(5, 5);

obj.read_row_col();

obj.sum_mat();

obj.display_mat();

}
→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


m To store size int
n To store size int
mat[] To store 2D array Int
i Used in loop Int
j Used in loop int
c To calculate the sum of int
elements of the columns
r To calculate sum of elements int
of rows

→OUTPUT

Enter a number one by one in a matrix:

1257377259756234

Elements of the matrix are:

1 2 5 7 15

3 7 7 2 19

5 9 7 5 26

6 2 3 4 15

15 20 22 18 0
Question 15-

A class Shift contains a two-dimensional integer array of order (mxn)

where the maximum values of both m and n is 5. Design the class


Shift to shuffle the matrix

(i.e., the first row becomes the last, the second row becomes the
first and so on).

The details of the members of the class are given below:

CLASS NAME: Shift

DATA MEMBERS/INSTANCE VARIABLES:

mat[][]: stores the array element

m: integer to store the number of rows

n: integer to store the number of columns

MEMBER FUNCTIONS:

Shift(int mm, int nn): to initialize the size of the matrix m=mm and
n=nn

void input(): to enter the elements of the array

void cyclic(Shift P):enables the matrix of the object (P) to shift each
row upwards in a cyclic manner and store the resultant matrix in the
current object

8void display(): displays the matrix elements

Specify the class Shift giving details of the constructor(),void input(),


void cyclic(Shift) and void display(). Define the main() function to
create an object and call the methods accordingly to enable the task
of shifting the array elements

→ALGORITHM

Step-1: Start

Step-2: Initialize the data members and declaration of array mat[]


[].

Step-3: Create a function void input() to ask the user to enter the
elements of the array.

Step-4: Create a function void cyclic(Shift p) to enable the matrix


of the object (p) to shift each row upwards in a cyclic
manner and store the resultant matrix in the current
object.

Step-5: Create a function void display() to print the changed


matrix.

Step-6: Create a main function for execution.

Step-7: Create an object and call the function accordingly

Step-8: Stop

→CODE

import java.util.*;

class Shift

int mat[][],n,m;
Shift(int mm ,int nn)

m=mm;

n=nn;

mat= new int[m][n];

void input()

Scanner in =new Scanner (System.in);

System.out.println(" Enter the elements of the array");

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

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

mat[i][j]=in.nextInt();

void cyclic(Shift p)

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


{

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

if(i==0)

this.mat[m-1][j]=p.mat[i][j];

else

this.mat[i-1][j]=p.mat[i][j];

void display()

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

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

System.out.print(mat[i][j]+"\t");
}

System.out.println();

public static void main( int mm, int nn)

Shift ob= new Shift(mm,nn);

Shift ob1=new Shift(mm,nn);

ob.input();

System.out.println("Original Matrix");

ob.display();

ob1.cyclic(ob);

System.out.println("Changed Matrix");

ob1.display();

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
Mat[][] To store double dimensional int
array
m To store number of rows int
n To store number of columns int
i Control variable in for loop int
j Control variable in for loop int

→OUTPUT

Enter the elements of the array

11 22 33 44 55 66 77 88 99

Original Matrix

11 22 33

44 55 66

77 88 99

Changed Matrix

44 55 66

77 88 99

11 22 33
Question 16-

A class Trans is defined to find the transpose of a square matrix. A


transpose of a matrix is obtained by interchanging the elements of
the rows and columns.

Example: If size of the matrix = 3, then

ORIGINAL

11 5 7

8 13 9

1 6 20

TRANSPOSE

11 8 1

5 13 6

7 9 20

Some of the member methods of the class are given below:

Class name: Trans

Data members/instance variables:

arr[ ][ ]: to store integers in the matrix

m: integer to store the size of the matrix

Methods/Member functions:

Trans(int mm): parameterised constructor to initialise the data


member m = mm
void fillarray( ): to enter integer elements in the matrix

void transpose( ): to create the transpose of the given matrix

void display( ): displays the original matrix and the transposed matrix
by invoking the method transpose( )

Specify the class Trans giving details of the constructor( ), void


fillarray( ), void transpose( ) and void display( ). Define a main ( )
function to create an object and call the functions accordingly to
enable the task.

→ALGORITHM

Step-1: Start

Step-2: Declare arr and m to store elements of Matrix and size of


square Matrix respectively.

Step-3: Initialize the data members in constructor.

Step-4: In method void fillarray( ), fill the elements of square


Matrix.

Step-5: In method transpose( ), create a temporary Matrix to


store the transpose Matrix.

Step-6: Interchange rows and columns and store them in


temporary Matrix.

Step-7: In display(), display the original Matrix and transpose


Matrix by invoking the function transpose( ).

Step-8: Create main function and call all the required functions.

Step-9: Stop
→CODE

import java.util.Scanner;

public class Trans

int arr [][];

int m;

Trans(int mm)

m=mm;

arr[ ] [ ] = new int[m][m];

void fillarray( )

int i,j;

System.out.println(“Enter elements in the Matrix “);

Scanner sc =new Scanner(System.in);

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

for( j=0;j <m ; j++)

arr[i][j]=sc.nextInt();
System.out.print(“ “);

void transpose( )

int temp[ ] [ ]= new int [m][m];

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

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

temp[i][j]=arr[j][i];

arr =temp ;

void display( )

System.out.println(“Matrix before transpose “);

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

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

System.out.print(arr [i][j]+” “);

System.out.println(“ “);

transpose( )

System.out.println(“Matrix after transpose “);

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

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

System.out.print( temp[i][j]+” “);

System.out.println(“ “);

public static void main ( int m)

{
Scanner sc = new Scanner (System.in);

Trans ob = new Tran(m);

ob.fillarray();

ob.display();

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


Arr[][] To store matrix int
m To store size of matrix int
I Control variable in for loop int
J Control variable in for loop int
temp To store transpose of matrix int

→OUTPUT

Matrix before transpose

11 5 7

8 13 9

1 6 20

Matrix after transpose


11 8 1

5 13 6

7 9 20
Question 17-

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:

A) Sort the boundary elements in ascending order using any standard


sorting technique and rearrange them in the matrix.

B) Calculate the sum of both the diagonals.

C) Display the original matrix, rearranged matrix and only the


diagonal elements of the rearranged matrix with their sum.

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

Example 1

INPUT:

M=4

9 2 1 5

8 13 8 4

15 6 3 11

7 12 23 8

OUTPUT:

ORIGINAL MATRIX

9 2 1 5

8 13 8 4
15 6 3 11

7 12 23 8

REARRANGED MATRIX

1 2 4 5

23 3 6 7

15 8 13 8

12 11 9 8

DIAGONAL ELEMENTS

1 5

3 6

8 13

12 8

SUM OF THE DIAGONAL ELEMENTS = 56

→ALGORITHM

Step 1: Start

Step 2: Accept size of matrix from user.

Step 3: Create a double dimensional matrix A[][] of order MxM


and after entering elements in it display it.

Step 4: Create a single dimensional matrix b[] of order M* M- (M-


2) * (M - 2)
Step 5: Transfer only the boundary elements of matrix in array
b[] and sort them in ascending order.

Step 6: Transfer the sorted boundary elements in array A[][] and


display the sorted matrix.

Step 7: Now display only the diagonal elements of the sorted


matrix by checking the condition if((i==j)||(i+j)==(M-1))
and calculate their sum.

Step 8: Stop

→CODE

import java.util.*;

class Matrix

public static void main()

Scanner in = new Scanner(System.in);

System.out.println("Enter value of M ");

int M=in.nextInt();

if(M < 4 || M> 9)

{ System.out.println("SIZE OUT OF RANGE");

int A[][] = new int[M][M];


int b[] = new int[M* M- (M- 2) * (M - 2)];

int k= 0;

int p= 1;

System.out.print("ENTER MATRIX ELEMENTS:");

for(int i = 0; i < M; i++)

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

A[i][j] = in.nextInt();

if(i == 0 || j == 0 || i == M- 1 || j == M - 1)

b[k++] = A[i][j];

else

{ p*= A[i][j];

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

for(int i=0;i<M;i++)

{
for(int j=0;j<M;j++)

System.out.print(A[i][j]+"\t");

System.out.println();

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

for(int j = 0; j < b.length - 1 - i; j++)

if(b[j] > b[j + 1]){

int temp = b[j];

b[j] = b[j + 1];

b[j + 1] = temp;

k = 0;

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

A[0][j] = b[k++];

for(int i = 1; i < M; i++)


A[i][M - 1] = b[k++];

for(int j = M- 2; j >= 0; j--)

A[M - 1][j] = b[k++];

for(int i = M- 2; i > 0; i--)

A[i][0] = b[k++];

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

for(int i=0;i<M;i++)

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

System.out.print(A[i][j]+"\t");

System.out.println();

int sd=0;

System.out.println("Diagonal Elements:");

for(int i=0;i<M;i++)

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

if((i==j)||(i+j)==(M-1))
{

sd=sd+A[i][j];

System.out.print(A[i][j]+"\t");

else

System.out.print("\t");

System.out.println();

System.out.println("Sum of the diagonal elements="+sd);

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


M Size of array int
A To create double dimensional array int
b Array for sorting boundary elements int
k To transfer elements int
p To keep non boundary elements int
unchanged
i To run outer for loop int
j To run inner for loop int
temp To sort array elements int
k To transfer elements int
sd To store sum of diagonal elements int

→OUTPUT

Enter value of M
4
ENTER MATRIX ELEMENTS:23 3 13 4 6 12 17 14 18 29 7 8 5 19 20 31
ORIGINAL MATRIX
23 3 13 4
6 12 17 14
18 29 7 8
5 19 20 31
REARRANGED MATRIX
3 4 5 6
31 12 17 8
23 29 7 13
20 19 18 14

Diagonal Elements:
3 6
12 17
29 7
20 14
Sum of the diagonal elements=108
Question 18-

A class ArrayPrime contains a square matrix which finds the prime


numbers in each row. Some of the members of the class are given
below:

Class Name: ArrayPrime

Data members/ Instance Variables:

a[][]- array to store integer elements

m- to store order of matrix

Member functions/methods:

ArrayPrime(int mm)- parameterised constructor to initialise


the data member m=mm

void readarray()- to enter elements in array

int isPrime(int x)- checks and returns 1 if the a number ‘x’ is


a prime number otherwise returns -1

void display()- displays the prime numbers in each row

Specify the class ArrayPrime, giving the details of the constructor(),

→ALGORITHM

Step-1: Start

Step-2: Declare data members

Step-3: Define parameterized constructor to initialise m=mm


Step-4: Define function readarray() to input array from user

Step-5: Define function to return 1 if given number is prime and


-1 if it is not prime

Step-6: Define function display() to check for prime numbers in


each row of matrix and display the prime numbers with
appropriate message.

Step-7: Define main function to create object and call all


functions accordingly for execution of task

Step-8: Stop

→CODE

import java.util.*;

class ArrayPrime

int arr[][], m;

ArrayPrime(int mm)

m=mm;

a=new int[m][m];

void readarray()

{
Scanner sc=new Scanner(System.in);

System.out.println(“Enter elements into matrix”);

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

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

arr[i][j]=sc.nextInt();

int isPrime(int x)

int i,f=0;

for(i=2;i<x/2;i++)

if(x%i==0)

f++;

if(f==0)

return 1;

else

return -1;

void display()

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

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

System.out.println(“Row”+i);

if(isPrime(arr[i][j])==1)

System.out.print(arr[i][j]);

else

System.out.print(\t);

System.out.println();

public static void main(int x)

ArrayPrime ob=new ArrayPrime(x);

ob.readarray();

ob.display();

}
→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


arr[] To store matrix int
m To store order of matrix int
i Control variable for outer int
loop
j Control variable in for inner int
loop
f flag variable int

→OUTPUT

Enter elements of Matrix


5 4 9

3 4 3

2 6 7

Row1

Row2

3 3

Row3

2 7
Question 19-

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

Perform the following tasks on the matrix:

a) Display the original matrix.

b) Calculate the decimal equivalent for each row and display as per
the format given below

→ALGORITHM

Step-1: Start

Step-2: Taking input for the number of rows (M) and columns (N)
of the matrix and check if the input values are within a
specific range (m <= 0 || m >= 10 || n <= 2 || n >= 6)

Step-3: Create a 2D array 'a' to store the elements of the matrix


with dimensions MxN.

Step-4: Using nested for loops, input elements for each row of
the matrix from the user.

Step-5: Calculate the decimal equivalent by iterating through


each row and column, converting the octal number to
decimal using the formula: decNum += a[i][j] *
Math.pow(8, n - j - 1)
Step-6: Print the filled matrix along with the decimal equivalent of
each row

Step-7: Stop

→CODE

//PROGRAM TO RETURN THE DECIMAL EQUIVALENT OF EACH ROW


OF THE MATRIX

import java.util.*;

public class Decimal_Equivalent

public static void main(String[] args)

//TAKE INPUT USING SCANNER METHOD

Scanner in = new Scanner(System.in); System.out.print("Enter the


number of rows (M): "); int m = in.nextInt();

System.out.print("Enter the number of columns (N): ");

int n = in.nextInt();

if (m <= 0 || m >= 10 || n <= 2 || n >= 6)

//SIZE OF THE MATRIX

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

}
int a[][] = new int[m][n]; for (int i = 0; i < m; i++)

//USING FOR LOOP ENTER THE ELEMENTS OF THE MATRIX

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


(int j = 0; j < n; j++)

a[i][j] = in.nextInt();

if (a[i][j] < 0 || a[i][j] > 7)

//VALIDATING USER INPUT

System.out.println("INVALID INPUT"); return;

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

//PRINTING THE DECIMAL EQUIVALENTS

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

int decNum = 0;

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

{
decNum += a[i][j] * Math.pow(8, n - j - 1 );

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

System.out.print("\t\t" + decNum); System.out.println();

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


m To store number of rows int
n To store number of columns int
a[][] To store elements int
i Control variable in for loop int
j Control variable in for loop int
decNum To store decimal equivalent int

→OUTPUT

Enter the number of rows (M): 3

Enter the number of columns (N): 3

ENTER ELEMENTS FOR ROW 1:


1 5 6

ENTER ELEMENTS FOR ROW 2:

4 2 3

ENTER ELEMENTS FOR ROW 3:

7 5 3

FILLED MATRIX

1 5 6

4 2 3

7 5 3

DECIMAL EQUIVALENT

1 5 6 110

4 2 3 275

753 491
Question 20-

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


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

(a) Sort the matrix elements in descending order using any


standard sorting technique

(b) Calculate the sum of the boundary elements of the matrix


before sorting and after sorting.

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

→ALGORITHM

Step-1: Start

Step-2: Take input for the number of rows (M) and columns (N) of
the matrix from user.

Step-3: Initialize a 2D array 'mat' to store the elements of the


matrix with dimensions MxN.

Step-4: Input elements of matrix and display the original matrix

Step-5: Calculate the sum of the boundary elements of the matrix


by iterating through each row and column.

Step-6: Print the sum of the boundary elements.


Step-7: Sort the matrix in descending order

Step-8: Calculate and print the sum of the boundary elements of


the sorted matrix

Step-9: Stop

→CODE

//PROGRAM TO PRINT THE SUM OF BOUNDARY ELEMENTS

import java.util.*;

public class Sum_Of_Boundary

static int mat[][];

public static void main(String abc[])

//TAKE INPUT USING SCANNER METHOD

Scanner sc = new Scanner(System.in); int m,n;

System.out.print("M : "); m=sc.nextInt(); System.out.print("N : ");


n=sc.nextInt(); sumofboun(m,n);

public static void sumofboun(int r,int c)

//FUNCTION TO RETURN THE SUM OF BOUNDARY ELEMENTS


{

Scanner sc = new Scanner(System.in); mat = new int[r][c];

System.out.println ("Enter Elements of the Matrix");

//INPUTING ELEMENTS IN THE MATRIX

for(int i=0;i<r;i++)

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

mat[i][j]=sc.nextInt();

System.out.println ();

//ORIGINAL MATRIX

System.out.println ("ORIGINAL MATRIX"); for(int i=0;i<r;i++)

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

System.out.print( mat[i][j] );

System.out.println ( );
}

int sum = 0;

for( int i=0;i<r;i++ )

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

if( i==0||i==r-1 )

sum+=mat[i][j];

else if (j==0||j==c-1)

sum+=mat[i][j];

System.out.println ("SUM OF THE BOUNDARY ELEMENTS IS : "+sum);


sortmartix(r,c);

//SORTED MATRIX

System.out.println ("SORTED MATRIX"); for(int i=0;i<r;i++)

{
for(int j=0;j<c;j++)

System.out.print(mat[i][j]);

System.out.println ();

sum=0;

for(int i=0;i<r;i++)

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

if(i==0||i==r-1)

sum+=mat[i][j];

else if( j==0||j==c-1 )

sum+=mat[i][j];

}
}

System.out.println ("SUM OF THE BOUNDARY ELEMENTS IS :"+sum);

public static void sortmartix(int a,int b)

int arr[] = new int [a*b],k=0;

//CONVERTTING MATRIX TO LINEAR ARRAY

for(int i=0;i<a;i++)

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

arr[k]=mat[i][j]; k++;

//SORTING

for(int i=0; i<a*b; i++)

for( int j=0; j<a*b-1; j++ )

if(arr[j]<arr[j+1])

{
int copy = arr[j]; arr[j]=arr[j+1]; arr[j+1] = copy;

//COVERTING LINEAR ARRAY TO MATRIX k=0;

for(int i=0;i<a;i++)

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

mat[i][j]=arr[k]; k++;

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
mat[][] To store matrix int
m To store number of columns int
n To store number of rows int
i Control variable in for loop int
j Control variable in for loop int
sum to sum up the values int
c to count int
k To count int
copy To copy int

→OUTPUT

M: 3

N: 3

Enter Elements of the Matrix

123456789

ORIGINAL MATRIX

1 2 3

4 5 6

7 8 9

SUM OF THE BOUNDARY ELEMENTS IS: 40

SORTED MATRIX

9 8 7

6 5 4

3 2 1

SUM OF THE BOUNDARY ELEMENTS IS: 40


String
Programs
Question 21-

A class Mystring has been defined to print the code of each word.
Code will be calculated by adding the ASCII code of each character.
Ex- the code for ACE will be 201(65+67+69). Define the class Mystring
using following methods

Class name: Mystring

Data members

str: to store a string

c: to store the code of word

Member functions

Mystring(): Constructor

void readstring(): reads the given string from input

int code(String w): returns code for word ‘w’

void display(): display each word in separate line with code of


string str

Specify the class Mystring giving details of the constructor and void
readstring(), int code(String w), void word() only. Write the main
function to create objects and call the functions accordingly.

→ALGORITHM

Step-1: Start

Step-2: Create class Mystring and initialize data members

Step-3: Create constructor


Step-4: Create function void readstring() and input string from
user in str

Step-5: Create function int code(String w) and calculate code for


word ‘w’ by extracting each character one by one

Step-6: Create function void display() and display each word along
with its code in different lines by extracting words from
String str and invoking function int code(String w)

Step-7: Create main() and call all required functions by object

Step-8: Stop

→CODE

import java.util.*;

class Mystring

String str;

int c;

Mystring()

str=" ";

c=0;

void readstring()

{
Scanner sc=new Scanner(System.in);

System.out.println("Enter a sentence");

str=sc.nextLine();

int code(String w)

int i;

for(i=0;i<w.length();i++)

c=c+w.charAt(i);

return c;

void display()

int i;

String s="";

for(i=0; i<str.length();i++)

if(str.charAt(i)==' ')

{
System.out.println(s+":"+code(s));

s="";

else

s=s+str.charAt(i);

System.out.println(s+":"+code(s));

public static void main()

Mystring ob=new Mystring();

ob.readstring();

ob.display();

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


str Inputs the string from user String
c To store code of word int
i Looping variable int
s To extract word from String
sentence

→OUTPUT
Enter a sentence
Invisible String
Invisible:933
String:631
Question 22-

Design a class WordWise to separate words from a sentence and find


the frequency of the vowels in each word. Some of the members of
class are given below
Class name: WordWise
Data members/instance variables
str: to store a sentence
Member functions/methods
WordWise(): default constructor
void readsent(): to accept a sentence in upper case
int freq_vowel(String w): returns the frequency of vowels in the
parameterized string w
void arrange(): displays each word of the sentence in a separate line
along with the frequency of vowels for each word by invoking the
function freq_vowel()
Define the class WordWise giving details of the constructor(), void
readsent(), int freq_vowel(String) and void arrange(). Define the
main() function to create an object and call the functions accordingly,
to enable the task.

→ALGORITHM
Step-1: Start
Step-2: Create a class with name WordWise
Step-3: Declare instance variable
Step-4: Function int freq_vowel(string w) is a parameterized
function to find the frequency of vowel
Step-5: Create void arrange to print the words with their
frequency
Step-6: Create an object of a class
Step-7: Call the function
Step-8: Stop
→CODE
import java.util.*;
class WordWise
{
String str;
WordWise()
{
str=" ";
}
void readsent()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence in upper case");
str=sc.nextLine();
str=str.toUpperCase();
}
int freq_vowel(String w)
{
int i,v=0;
char c;
for(i=0;i<w.length();i++)
{
c=w.charAt(i);
if(c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
v++;
}
return v;
}
void arrange()
{
int i;
String s=" ";
for(i=0; i<str.length();i++)
{
if(str.charAt(i)==' ')
{
System.out.println(s+":"+freq_vowel(s));
s=" ";
}
else
s=s+str.charAt(i);
}
System.out.println(s+":"+freq_vowel(s));
}
public static void main()
{
WordWise ob=new WordWise();
ob.readsent();
ob.arrange();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
str to store string String
i looping variable int
v to count variables int
c to extract character char
s to extract word String
→OUTPUT
Enter a sentence in upper case
THE TORTURED POETS DEPARTMENT
THE:1
TORTURED:3
POETS:2
DEPARTMENT:3
Question 23-
Write a Program to accept a sentence that may be terminated by
either “.” , “?” or “!” only. The words of sentences are separated by a
single space and are in UPPERCASE. Decode the words according to
their Potential and arrange them in ascending order of their
potential strength. Test your program with the following data and
some random data.

Example 1:

INPUT: HOW DO YOU DO?

OUTPUT: HOW = 238 DO = 147 YOU = 253 DO = 147

DO DO HOW YOU

→ALGORITHM

Step-1: Start

Step-2: Enter the sentence to find the potential and arrange it

Step-3: Find the length of the sentence

Step-4: Extract each word of the sentence

Step-5: Find the potential according to the word

Step-6: Sort potential array and words

Step-7: Print sorted sentence

Step-8: Stop
→CODE

import java.util.*;

public class abc

public static void main(String args[])

Scanner in = new Scanner(System.in);

System.out.println("ENTER THE SENTENCE:");

String ipStr = in.nextLine();

int len = ipStr.length();

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

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

System.out.println("INVALID INPUT");

return;

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

StringTokenizer st = new StringTokenizer(str);

int wordCount = st.countTokens();

String strArr[] = new String[wordCount];


int potArr[] = new int[wordCount];

for (int i = 0; i < wordCount; i++)

strArr[i] = st.nextToken();

potArr[i] = computePotential(strArr[i]);

System.out.println("Potential:");

for (int i = 0; i < wordCount; i++)

System.out.println(strArr[i] + " = " + potArr[i]);

/*

* Sort potential array and words array

* as per potential array

*/

for (int i = 0; i < wordCount - 1; i++)

for (int j = 0; j < wordCount - i - 1; j++)

if (potArr[j] > potArr[j+1])

{
int t = potArr[j];

potArr[j] = potArr[j+1];

potArr[j+1] = t;

String temp = strArr[j];

strArr[j] = strArr[j+1];

strArr[j+1] = temp;

System.out.println("Sorted Sentence");

for (int i = 0; i < wordCount; i++)

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

public static int computePotential(String word)

String str = word.toUpperCase();

int p = 0;

int l = str.length();

/*
* Substracting 64 from ASCII Value of

* letter gives the proper potentials:

* A => 65 - 64 = 1

* B => 66 - 64 = 2

* ..

* ..

*/

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

p += str.charAt(i) - 64;

return p;

→VARIABLE-DESCRIPTION TABLE

Variable Description Data Type


ipStr Inputs the string from user String
len Length of the inputted string int
lastChar Last character of the char
inputted string
Str Inputted string with last String
character removed
wordCount No. Of words in the sentence int
strArr For inputting array String
potArr To input the potential of the int
words
I Outer loop control variable int
J Inner loop control variable int
T Variable for use in sorting int
P Returning the potential of int
word to calling function

→OUTPUT

ENTER THE SENTENCE:

THE SKY IS THE LIMIT

POTENTIAL:

THE=33

SKY=55

IS=28

THE=33

LIMIT=63

Sorted sentence

IS THE THE SKY LIMIT


Question 24-

A class ConsChange has been defined with the following details


Class Name: ConsChange
Data members/Instance variables
wrd: stores the word
shiftwrd: stores shifted word
len: stores length of the word
Member Methods/functions
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 (eq spoon becomes spnoo)
void show(): displays the original word and the shifted word
Specify the class ConsChange giving the details of the constructor(),
void readword(), voidshiftcons(), void show(). Define the main()
function to create an object and call the functions accordingly to
enable the task.

→ALGORITHM
Step-1: Start
Step-2: Create class ConsChange and declare data members
Step-3: Create default constructor to initialize values to data
members
Step-4: Create function readword() to input a word from user and
store in wrd
Step-5: Create function shiftcons() to shift the consonants in front
followed by the variables and store in shiftwrd
Step-6: Create function show() for displaying original word and
shifted word
Step-7: Create main to call the functions to enable the task by
object creation
Step-8: Stop
→CODE
import java.util.*;
class ConsChange
{
String wrd, shiftwrd; int len;
ConsChange()
{
wrd="";
shiftwrd="";
len=0;
}
void readword()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a word in lower case");
wrd=sc.next().toLowerCase();
len=wrd.length();
}
void shiftcons()
{
int i;
char ch;
String c="",v="";
for(i=0;i<len;i++)
{
ch=wrd.charAt(i);
if("aeiou".indexOf(ch)==-1)
c=c+ch;
else
v=v+ch;
}
shiftwrd=c+v;
}
void show()
{
System.out.println("Original word:"+wrd);
System.out.println("Shifted word:"+shiftwrd);
}
public static void main()
{
ConsChange ob=new ConsChange();
ob.readword();
ob.shiftcons();
ob.show();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
wrd To store inputted word String
shiftwrd To store shifted word String
len To store length of word int
i Looping variable int
ch To extract character char
c To store all consonants String
v To store all vowels String

→OUTPUT
Believe
Original word: believe
Shifted word: blveiee
Question 25-

The reverse of the word HELP would be LEH (omitting the last
alphabet) and by concatenating both, the new palindrome word is
HELPLEH. Thus, the word HELP becomes HELPLEH. Write a program
to input a sentence and perform the task with each word of the
sentence, then display the new sentence.
Example-
Input: THE BIRD IS FLYING
Output: THEHT BIRDRIB ISI FLYINGNIYLF

→ALGORITHM
Step-1: Start
Step-2: Input a sentence and convert it into upper case
Step-3: Run a loop from i=0 to i<s.length
Step-4: Extract each word from the sentence
Step-5: Run a nested loop from j=0 to j<w.length
Step-6: Store the palindromic word of the original word in
another string
Step-7: Print the sentence
Step-8: Stop

→CODE
import java.util.*;
class reverse
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s,w="",w1="";
int i,j;
char ch,ch1;
System.out.println("Enter a sentence in upper case");
s=sc.nextLine().toUpperCase();
for(i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch==' ')
{
for(j=0;j<w.length()-1;j++)
{
ch1=w.charAt(j);
w1=ch1+w1;
}
w1=w+w1;
System.out.print(w1+" ");
w="";
w1="";
}
else
w=w+ch;
}
for(j=0;j<w.length()-1;j++)
{
ch1=w.charAt(j);
w1=ch1+w1;
}
w1=w+w1;
System.out.print(w1+" ");
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
s Inputs the string from user String
i Outer loop variable Int
j Inner loop variable int
ch For extracting characters char
w For extracting words String
ch1 For extracting characters char
from extracted words
w1 For changing word into String
palindrome

→OUTPUT
Enter a sentence
THE SKY IS BLUE
THEHT SKYKS ISI BLUEULB
Question 26-

Write a program to use a class with the following specifications:


Class Name : StringOP
Data members/Instance variables:
Str, rev : Variables to store strings.
Member methods/functions :
StringOP() : Constructor to initialize the variables.
Void input() : To store a sentence in str.
Void process() : To reverse string str and store the reversed string in
rev. Also print both the strings.
Void find() : Make use of StringTokenizer class to find the number of
words and blanks available in the string input from the console.
Use a main class to call the functions shown above.

→ALGORITHM
Step-1: Start
Step-2: In the function void input(),
Step-3: Enter a sentence.
Step-4: In the function void process(),
Step-5: Count the number of letters in the sentence i.e. it’s length.
Step-6: Run a loop from length -1 to 0.
Step-7: Extract the letters and add it in the new string rev.
Step-8: Print the reversed string.
Step-9: In the function void find(),
Step-10: Count the number of words using string tokenizer.
Step-11: Display the no. of words and spaces.
Step-12: Make a main function and call all the functions.
Step-13: Stop

→CODE
// A program to display String Operations
Import java.util.*;
Public class StringOP
{
String str, rev;
StringOP()
{
Str =”” ;
Rev =”” ;
}
Void input()
{
Scanner in=new Scanner(System.in);
System.out.println(“Enter a sentence”);
Str =in.nextLine();
}
Void process()
{
Char b;
Int I, p;
P = str .length();
For( I = p – 1; I >= 0 ; i--)
{
B= str .charAt(i);
Rev = rev + b;
}
System.out.println(“The reverse sentence:” + rev);
}
Void find()
{
Int w;
StringTokenizer st=new StringTokenizer(str);
W = st.countTokens();
System.out.println(“Number of words in sentence:” + w);
System.out.println(“Number of spaces in sentence:” + (w-1)); }
}
Public static void main(String args[])
{
StringOP ob=new StringOP();
Ob.input();
Ob.process();
Ob.find();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
str To store sentence String
rev To store reversed sentence String
b For extracting characters Char
i Looping variable Int
p To store length of sentence int
w To count number of words int

→OUTPUT
Enter a sentence

ISC Understanding Computer Science Class 12

The reverse sentence: 21 ssalc ecneics retupmoc gnidnatsrednU CSI

Number of words in sentence: 6

Number of spaces in sentence: 5


Question 27-

Design a class Unique, which checks whether a word begins and ends
with a vowel.
Example: APPLE, ARORA etc.
The details of the members of the class are given below.
Class name: Unique
Data members/instance variables:
Word : stores a word
Len: To store the length of the word
Methods/Member functions:
Unique() : Default constructor
Void aceptword(): To accept the word in UPPER CASE
Boolean checkUnique(): Checks and returns ‘true’ if the word starts
and ends with a vowel otherwise returns ‘false’
Void display() : displays the word along with an appropriate message
Specify the class Unique, giving details of the constructor, void
acceptword(), boolean checkUnique() and void display(). Define the
main() function to create an object and call the functions accordingly
to enable the task.

→ALGORITHM
Step-1: Start
Step-2: Declare the global variables.
Step-3: Construct the default constructor and initialize global
variables.
Step-4: Construct a function to input the word and find its length.
Step-5: Construct another function to find first and last character
and checks whether both characters are vowel.
Step-6: Construct the last function which calls the previous
function and displays appropriate message
Step-7: Write main program and call the functions required.
Step-8: Stop
→CODE
import java.util.*;
Class Unique
{
String word;
int Len;
// Default constructor
public Unique()
{
Word = “”;
Len=0;
}

// Method to accept the word in UPPER CASE


public void acceptWord()
{
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a word in Upper case”);
String word=in.next();
Len=word.length();
}
// Method to check if word starts and ends with a vowel
public boolean checkUnique()
{
If (len< 2)
{
Return false;
}
char ch1=word.charAt(0);
char ch2= word.charAt(len- 1);
If(ch1 == ‘A’ || ch1 == ‘E’ || ch1 == ‘I’ || ch1 == ‘O’ || ch1 == ‘U’)
{
If(ch2 == ‘A’ || ch2 == ‘E’ || ch2 == ‘I’ || ch2 == ‘O’ || ch2 == ‘U’)
Return true;
}
// Method to display the word along with an appropriate message
public void display()
{
System.out.println(“Word: “ + word);
If (checkUnique())
{
System.out.println(“The word starts and ends with a vowel.”);
}
Else
{
System.out.println(“The word does not start and end with a
vowel.”);
}
}
public static void main(String[] args)
{
Unique ob = new Unique();
ob.acceptWord();
ob.display();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
word To store word String
len Length of word Int
ch1 First character char
ch2 Last character char

→OUTPUT
Enter a word in Upper Case
ARORA

The word starts and ends with a vowel.


Question 28-

Design a class Exchange to accept a sentence and interchange the


first alphabet with the last alphabet for each word in the sentence,
with single letter word remaining unchanged. The words in the input
sentence are separated by a single blank space and terminated by a
full stop.
Example: Input: It is a warm day.
Output: tI si a marw yad
Some of the data members and member functions are given below:
Classname:Exchange
Data members / instance variables:
sent:stores the sentence
rev:to store the new sentence
size: stores the length of the sentence
Member functions:
Exchange(): default constructor
void readsentence():to accept the sentence
void exfirstlast():extract each word and interchange the first and last
alphabet of the word and form a new sentence rev using the changed
words
void display():display the original sentence along with the new
changed sentence.
Specify the class Exchange giving details of the constructor(), void
readsentence() , void exfirstlast() and void display(). Define the
main() function to create an object and call the functions accordingly
to enable the task.

→ALGORITHM
Step-1: Start
Step-2: Design a class name exchange.
Step-3: Declare the instant variable.
Step-4: Create function void readsentence() to accept the
sentence.
Step-5: Create function void exfirstlast() to extract each word and
interchange first and last alphabet of the word and form a
new sentence rev words
Step-6: Create void display() to display reversed string
Step-7: Stop

→CODE
import java.util.Scanner;
public class Exchange
{
String sent,rev;
int size;
Exchange()
{
sent="";
rev="";
size=0;
}

void readsentence()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a sentence");
sent=sc.nextLine();
size=sent.length();
}

void exfirstlast()
{
char ch=' ';
String wd="";
for(int i=0;i< size;i++)
{
ch=sent.charAt(i);
if(ch==' '||ch=='.')
{
if(wd.length()>1)
{
/*last character*/
rev=rev + wd.charAt(wd.length()-1);
/*middle characters*/
rev=rev + wd.substring(1,wd.length()-1);
/*first character*/
rev=rev + wd.charAt(0);
/*space or full stop*/
rev=rev+ch;
}
else
{
rev=rev+wd+ch;
}

wd="";
}
else
{
wd=wd+ch;
}
}
}
void display()
{
System.out.println("Input:"+sent);
System.out.println("Output: "+rev);
}
public static void main()
{
Exchange obj1=new Exchange();
obj1.readsentence();
obj1.exfirstlast();
obj1.display();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
sent Inputs the string from user String
rev To store new string String
size Length of sentence int
i loop variable int
ch For extracting characters char

→OUTPUT
Enter a sentence
THE SKY IS BLUE
THEHT SKYKS ISI BLUEULB
Question 29-

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 Variables:
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): parameterised constructor to assign str=ds
void count freq(): 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
numbers of consonants
Specify the class TheString giving the details of the constructors,
voidcount Freq() and void Display().
Define the main() function to create an object and call the functions
accordingly to enable the task.

→ALGORITHM
Step-1: Start
Step-2: Define the class TheString.
Step-3: Store the variables for their respective functions.
Step-4: Assign the variables in default constructor.
Step-5: Accept a string.
Step-6: Count the number of words and number of consonants
and store them.
Step-7: Display the original string and the number of consonants.
Step-8: Define the main function for the same.
Step-9: Stop

→CODE
import java.util.*;
TheString
{
String str;
int len, wordcount, cons;
TheString()
{
str=””;
len=0;
wordcount=0;
cons=0;
}
TheString(String ds)
{
str=ds;
}
void count freq()
{
len=str.length();
String Tokenizer st=new StringTokenizer(str);
wordcount= st.countTokens();
for(i=0;i<len;i++)
{
char ch=str.charAt(i);
if(ch!=’A’ && ch!=’E’ && ch!=’I’ && ch!=’O’ && ch!=’U’ && ch!=’a’
&& ch!=’e’ && ch!=’i’ && ch!=’o’ && ch!=’u’)
cons= cons+1;
}
}
void Display()
{
System.out.println(“Original String: “+str);
System.out.println(“Number of consonants: “+cons);
}
public static void main(String s)
{
TheString ob=new TheString();
ob.count freq();
ob.Display();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
Str To store original string String
Len To find length of string Int
countwords To store number of words int
Cons To count number of int
consonants
Ds To store original string String
i looping variable int

→OUTPUT
“God is great”

Original String: God is great

Number of consonants: 6
Question 30-

A class Rearrange has been defined to modify a word by bringing all


the vowels in the word at the beginning followed by the consonants.
Example: ORIGINAL becomes OIIARGNL . Some of the members of
the class are given below:
Clase Name : Rearrange
Data members/Instance variables :
wrd : to store a word
newwrd : to store the rearranged word
Member Functions/ methods:
Rearrange() : default constructor
void readword() :to accept the word in UPPER case
void freq_vow_con(): finds the frequency of vowels and consonants
in the word and displays them with an appropriate message
void arrange(): rearranges the word by bringing the vowels at the
beginning followed by consonants
void display(): displays the original word along with the rearranged
word
Specify the class Rearrange, giving the details of the constructor(),
void readword(), void freq_vow_ con(), void arrange() and void
display(). Define the main() function to create an object and call the
functions accordingly to enable the task.

→ALGORITHM
Step-1: Start
Step-2: Create a class by name of Rearrange
Step-3: Input the word in the readword()
Step-4: Find frequency of vowels and consonants in
freq_vow_con()
Step-5: Form the rearranged word in arrange()
Step-6: Display the original and rearranged word in display ()
Step-7: Stop
→CODE
import java.util.*;
public class Rearrange
{
String newwrd,wrd;
Rearrange()
{
wrd="";
newwrd="";
}
void readword()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a word in uppercase");
wrd=sc.nextLine();
wrd=wrd.toUpperCase();
}
void freq_vow_con()
{
int i,j,v=0;
for( i='A';i<='Z';i++)
{
v=0;
for(j=0;j<wrd.length();j++)
{
if(wrd.charAt(j)==(char)i)
{
v++;
}
}
if(v!=0)
System.out.println("frequency of "+(char)i+" is "+v);
else
continue;
}
}
void arrange()
{
String st="",str="";int i;
for( i=0;i<wrd.length();i++)
{
char ch=wrd.charAt(i);
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
st=st+ch;
else
str=str+ch;
}
newwrd=st+str;
}
void display()
{
System.out.println("original word is "+wrd);
System.out.println("word formed is "+newwrd);
}
public static void main(String args[])
{
Rearrange ob=new Rearrange ();
ob.readword();
ob.freq_vow_con();
ob.arrange();
ob.display();
}
}

→VARIABLE-DESCRIPTION TABLE
Variable Description Data Type
Wrd To store word String
Ch To store extracted character char
V To store frequency of each int
vowel and consonant
St To form a string with vowels char
Str To form a string with String
consonants
newwrd To store rearranged word by char
concatenating st and str

→OUTPUT
enter a word in uppercase
ORIGINAL
frequency of A is 1
frequency of G is 1
frequency of I is 2
frequency of L is 1
frequency of N is 1
frequency of O is 1
frequency of R is 1
original word is ORIGINAL
word formed is OIIARGNL

You might also like