0% found this document useful (0 votes)
6 views104 pages

Java Programs for Class XII Project

Computer file

Uploaded by

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

Java Programs for Class XII Project

Computer file

Uploaded by

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

1

ᵜASSESSMENT SHEETᵜ

➤NAME:- SAMARTH SINGH MANRAL


➤CLASS:- XII
➤ROLL NO:- 5
➤SESSION:- 2025-26
□SIGNATURES□

INTERNAL EXAMINER:-_____________________

EXTERNAL EXAMINER:-

PRINCIPAL:- _

2
ACKNOWLEDGEMENT
I would like to express my special thanks
of gratitude to Sir Manager and Ma’am
Principal for giving us the opportunity to
complete this project.

I would also like to thank my


computer teacher for her able guidance
and support in completing this project.

SAMARTH SINGH
MANRAL

3
INTRODUCTION

This project consists of 20 programs on the


topics like Arrays, String, Methods and
functions, Constructors, data structure and
various other topics which have been
covered by us during the academic session.
Each program contains the algorithm,
program code, output and variable
description table to explain the
functionality well.

4
⩩INDEX⩩
S. No. Program Page no Signatures

1. CHARACTER MATRIX. 3-7

2. DATE AND MONTH. 8-13

3. PALINDROME 14-18
PROGRAM.

4. GOLDBACH NUMBER. 19-23

5. MATRIX ROTATION. 24-28

6. MATRIX SORTING. 29-34

7. CIRCULAR QUEUE. 35-38

8. ACHILLES NUMBER. 39-42

9. PRIME ADAM INTEGER. 43-47

10. PRIME PALINDROME. 48-52

11. REVERSE MATRIX. 53-57

1
12. IDENTITY MATRIX. 58-62

13. HAPPY NUMBER. 63-65

14. LOWER OR UPPER 66-71


TRIANGLE.
15. UPPER CASE. 72-76

16. SMITH NUMBER. 77-80

17. REMOVE DUPLICATE 81-83


CHARACTER.
18. RESULT OF QUIZ 84-89
COMPETITION.
19. BOX PACKING. 90-93

20. EVIL NUMBER. 94-97

2
⫷Program-1⫸

Write a program to declare a square matrix m[][] of order


‘N’ where ‘N’ must be greater than 3 and less than 10.
Allow the user to accept three different characters from
the keyboard and fill the array according to the instruction
given below:
1. Fill the four corners of the square matrix with the
first character.
2. Fill the boundary of the matrix (except the four corners)
with the second character.
3. Fill the non-boundary elements of the matrix with the
third character.
Test your program with the following data and some random
data:
INPUT:
N=4
First character: @
Second character: ?
Third character: #
OUTPUT:
@??@
?##?
?##?
@??@

3
#ALGORITHM#
Step 1: Class fillMatrix created
Step 2: Size of the matrix is entered by the user.
Step 3: Condition is checked for size entered by the user.
Step 4: Characters to be filled in the matrix is entered by the user.
Step 5: Characters are filled according to the condition given in
the question.
Step 6: Resultant matrix is printed.

4
import [Link].*;
class FillMatrix
{

5
public static void main (String args [])

{
Scanner sc = new Scanner([Link]);
[Link]("Matrix size: ");
int n = [Link]();
if(n < 4 || n > 9){
[Link]("Size out of range!")

return;
}

char m[][] = new char[n][n];


[Link]("First character: "); char
first = [Link]().charAt(0);
[Link]("Second character: ");
char second = [Link]().charAt(0);
[Link]("Third character: "); char
third = [Link]().charAt(0);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(i == 0 || j == 0 || i == n - 1 || j == n -
1) m[i][j] = second;
else

6
m[i][j] = third;
}
}

m[0][0] = first;
m[n - 1][n - 1] = first;
m[0][n - 1] = first;
m[n - 1][0] = first;
[Link]("Resultant Matrix:");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
[Link](m[i][j] + "\t");
}

[Link]();
}
1OUT4UT1

7
::VDT::
VARIABLE DATA-TYPE DESCRIPTION

N int Size of the matrix

M char Matrix

I int Loop variable

J int Loop variable

First char First character

Second char second character

Third char third character

8
⫷4ROGRAM-2⫸

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

#ALGORITHM#
Step1: Class Convert created.
Step 2: Day number and Year will be entered by the user in the
function accept.
Step 3: Day number and year is validated as per the given
conditions.
Step 4: If either the day number or the year is invalid, the
compiler will exit the program.
Step 5: If the day and year is valid, then the day number
will be converted to a date in the function dayToDate.
Step 6: Calculated date will be printed by the function display.
Step 7: End.

9
import [Link].*;
class Convert
{
int n;
int d;
int m;
int y;
public Convert()
{
n = 0;
d = 0;

m = 0;

y = 0;

public void accept()

Scanner sc = new Scanner([Link]);


[Link]("Day number: ");
d = [Link]();
[Link]("Year: ");
y= [Link]();
if((y % 100 == 0 && y % 400 == 0) || y % 4 == 0){

10
if(d > 366){

[Link]("Invalid day number!");


[Link](0);
}

else if(d > 365){

[Link]("Invalid day number!"); [Link](0);


}

public void dayToDate(){

int a[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

if((y % 100 == 0 && y % 400 == 0) || y % 4 == 0)

a[1] = 29;

int sum = 0;
if(d <= 31)
m = 0;

else

11
{

while(d > 0)

d -= a[m];
m++;
if(d <= a[m])
break;
}

public void display(){

String months[] = {"January", "February", "March", "April",


"May", "June", "July", "August", "September", "October",
"November", "December"};
[Link](months[m] + " " + d + ", " + y);

public static void main(String args[])

12
Convert obj = new Convert();
[Link](); [Link]();
[Link]();
}

⧫OUT4UT⧫

13
VARIABLE DATA TYPE DESCRIPTION

d int Day number

y int Year

m int position

a int Array

month int Array of month

sum int To calculate the


date

14
⫷4ROGRAM-3⫸
Write a program to accept a sentence which may be terminated
by either ‘.’, ‘?’ or ‘!’ only. The words are to be separated by a
single blank space and are in uppercase.

Perform the following tasks:

a) Check for the validity of the accepted sentence.

b) Convert the non-palindrome words of the sentence into


palindrome words by concatenating the word by its reverse
(excluding the last character).
Example: The reverse of the word HELP would be LEH (omitting

the last alphabet) and by concatenating both, the new

palindrome word is HELPLEH. Thus, the word HELP becomes

HELPLEH.

Note: The words which end with repeated alphabets, for


example ABB would become ABBA and not ABBBA and
XAZZZ becomes XAZZZAX.

[Palindrome word: Spells same from either side. Example: DAD,


MADAM etc.]

c) Display the original sentence along with the converted

15
sentence.

#ALGORITHM#
Step1: Class Convert created.
Step 2: Accepting sentence
Step 3:Checking for the validity of accepted sentence
Step 4: Convert non-palindrome sentences into palindrome
words by concatenating the word by its reverse (excluding
the last character).
Step 5: Printing result
Step 6: End.

import [Link].*;
import [Link];
class Palindrome{
public static void main(String args[])

{
Scanner sc= new Scanner([Link]);
[Link]("Sentence: ");
String s = [Link]().trim().toUpperCase(); char
ch = [Link]([Link]() - 1);
if(ch != '.' && ch != '?' && ch != '!'){
[Link]("INVALID INPUT");

16
return;
}

StringTokenizer st = new StringTokenizer(s, " ?.!,"); int


count = [Link]();
String p = new String();

for(int i = 1; i <= count; i++){ String


word = [Link]();
if(isPalindrome(word))
p += word + " ";
else
p += generate(word) + " ";

}
[Link](s);
[Link](p);
}

public static boolean isPalindrome(String w){


String r = new String();
for(int i = [Link]() - 1; i >= 0; i--) r
+= [Link](i);
return ([Link](r));

}
public static String generate(String w){
17
String r = new String();
for(int i = [Link]() - 2; i >= 0; i--) r
+= [Link](i);
while([Link]() > 1 && [Link]([Link]() - 1) ==
[Link]([Link]() - 2))
w = [Link](0, [Link]() - 1);
return w + r;
}

}
?OUTPUT?

18
::VDT::
VARIABLE DATATYPE DESCRIPTION

s String To store the sentence entered by


the user
ch char To make the non palindrome
word a palindrome
p String String object

r String String object

w String String object

word String To check the words in the


sentence
count int To count the no. of tokens

19
⫷4ROGRAM-4⫸
A Goldbach number is a positive even integer that can be
expressed as the sum of two odd primes.

Note: All even integer numbers greater than 4 are Goldbach


numbers.

Example:

6=3+3

10 = 3 + 7

10 = 5 + 5

Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has

two odd prime pairs, i.e. 3, 7 and 5, 5.

Write a program to accept an even integer ‘N’ where N > 9 and


N < 50. Find all the odd prime pairs whose sum is equal to the
number ‘N’.

20
#ALGORITHM#
Step1: Class Convert created.
Step 2: Entering the number.
Step 3: Finding Prime Number of Number
Step 4: Adding Prime Number
Step 5: Checking
Step 6: Printing Result
Step 7: End.

import [Link].*;
class Goldbach
{

public static void main(String args[])


{
int n = 0;
int p = 3;
int q = 0;
Scanner sc=new Scanner([Link]);
[Link]("N = ");
n = [Link]();
if(n % 2 != 0){
[Link]("Invalid input. Number is odd.");

21
return;
}

else if(n < 10 || n > 49){


[Link]("Invalid input. Number is out of
range.");
return;

}
[Link]("Prime pairs are:"); while(p <
n){
q = n - p;

if(isPrime(p) && isPrime(q) && p <= q)


[Link](p + ", " + q);
p += 2;

}
}
public static boolean isPrime(int n){ int
f = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0)
f++;

}
if(f == 2) return
22
true;
return false;

}
}
⧫OUT4UT⧫

23
::VDT::
VARIABLE DATATYPE DESCRIPTION

p int To store the number

n int Factor

q int Factor

f int Factor count

24
⫷4ROGRAM-5⫸
Write a program to declare a square matrix a[][] of order M × M
where ‘M’ is the number of rows and the number of columns,
such that M must be greater than 2 and less than
10. Accept the value of M as user input. Display an appropriate
message for an invalid input. Allow the user to input integers into
this matrix. Perform the following tasks:

(a) Display the original matrix.


(b) Rotate the matrix 90o clockwise
(c) Find the sum of the elements of the four corners of the
matrix.

#ALGORITHM#

Step1: Class Convert created.


Step 2: Entering size of Matrix
Step 3: Displaying the original Matrix
Step 4: Rotating the Matrix 90 ° Clockwise.
Step 5: Finding the sum of elements of the four corners of Matrix
Step 6: Printing the result.
Step 7: End.

25
import [Link].*;
class Rotate{
public static void main(String args[])

{
Scanner sc= new Scanner ([Link]);
[Link]("M = ");
int m = [Link]();
if(m < 3 || m > 9){
[Link]("SIZE OUT OF RANGE");
return;
}

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


[Link]("Enter matrix elements:"); for(int
i = 0; i < m; i++){
for(int j = 0; j < m; j++){
a[i][j] = [Link]();
}

}
[Link]("ORIGINAL MATRIX");
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
[Link](a[i][j] + "\t");
}

26
[Link]();
}
int r[][] = new int[m][m];
int row = 0; int col = m - 1;
for(int i = 0; i < m; i++){
row = 0;

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


r[row++][col] = a[i][j];
}

col--;
}
[Link]("MATRIX AFTER ROTATION"); for(int i =
0; i < m; i++){
for(int j = 0; j < m; j++){
[Link](r[i][j] + "\t");
}

[Link]();
int last = m - 1;
int sum = a[0][0] + a[0][last] + a[last][0] + a[last][last];
[Link]("Sum of the corner elements = " +
sum);

}
}
27
⧫OUTpUT⧫

28
::VDT::

VARIABLE DATATYPE DESCRIPTION

m int Size of the matrix

i int Loop variable

j Int Loop variable

r int Array to store rotated matrix

a int Array to store the elements

29
⫷4ROGRAM-C⫸
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 non-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.

Step1: creating the class


Step 2: entering the size of the matrix
Step 3: sorting the non-boundary elements in ascending
order
Step 4: calculating the sum of both the diagnols
Step 5: displaying the original matrix
Step 6: printing the result

30
Step 7: End.

import [Link].*;
class MatrixSort{
public static void main(String args[])

{
Scanner sc = new Scanner([Link]);
[Link]("M = ");
int m = [Link]();
if(m < 4 || m > 9){
[Link]("THE MATRIX SIZE IS OUT OF
RANGE.");
return;

}
int a[][] = new int[m][m];
[Link]("Enter positive integers:");
for(int i = 0; i < m; i++)
for(int j = 0; j < m; j++)

a[i][j] = [Link]([Link]());
[Link]("ORIGINAL MATRIX");
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
[Link](a[i][j] + "\t");

31
}

[Link]();
}
int b[] = new int[(m - 2) * (m - 2)];
int k = 0;
for(int i = 1; i < m - 1; i++){

for(int j = 1; j < m - 1; j++){


b[k++] = a[i][j];
}

}
for(int i = 0; i < [Link]; i++){
for(int j = 0; j < [Link] - 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 i = 1; i < m - 1; i++){
for(int j = 1; j < m - 1; j++){
a[i][j] = b[k++];
32
}
}
[Link]("REARRANGED MATRIX"); for(int i
= 0; i < m; i++){
for(int j = 0; j < m; j++){
[Link](a[i][j] + "\t");
}

[Link]();
}
int sum = 0;
[Link]("DIAGONAL ELEMENTS");
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
if(i == j || i + j == m - 1){
[Link](a[i][j] + "\t");
sum += a[i][j];
}

else
[Link]("\t");
}
[Link]();
}
[Link]("SUM OF THE DIAGONAL ELEMENTS
= " + sum);

33
}
}

⧫OUT4UT⧫

34
::VDT::

Variable Data type Description


m int Size of the matrix

j int Loop Variable

i int Loop Variable

sum int Sum of the elements

35
⫷4ROGRAM-7⫸
A Circular Queue is a linear data structure which works on the
principle of FIFO, enabling the user to enter data from the rear
end and remove data from the front end with the rear end
connected to the front end to form a circular pattern.

#ALGORITHM#
Step1: Creating the class
Step 2:Enables the user to enter data
Step 3:Remove data from the front end
Step 4: Connecting to the front end to form a circular pattern
Step 5: Checking
Step 6: Printing
Step 7: End.

import [Link].*;
class CirQueue
{
int cq[];
int cap;

36
int front;
int rear;
public CirQueue(int max){
cap = max;
front = 0;

rear = 0;
cq = new int[cap];
}
public void push(int n){ if((rear +
1) % cap != front){
rear = (rear + 1) % cap;
cq[rear] = n;
}

else
[Link]("QUEUE IS FULL");
}
public int pop(){
if(front != rear){
int n = cq[front];

front = (front + 1) % cap;


return n;
}

else
37
return -9999;
}
public void show(){
if(front != rear){
for(int i = front; i <= rear; i = (i + 1) % cap)
[Link](cq[i] + "\t");
[Link]();

}
else
[Link]("QUEUE IS EMPTY");
}
}

⧫OUTPUT⧫

38
::VDT::
Variable Data type Description

cq[] int To store a matrix

cap int To store the


maximum value

rear int To store the rear


end position

front int To store the front


position

39
⫷4ROGRAM-8⫸
An Achilles Number is a number that is powerful but not a perfect
power.
A Powerful Number is a positive integer N, such that for every
prime factor p of N, p 2 is also a factor.
A Perfect Power is a positive integer N such that it can be
expressed as ab, where a and b are natural numbers > 1.
72, 108, 200, 288 are some of the first few Achilles Numbers.

The prime factors of 72 = 2 × 2 × 2 × 3 × 3.


Both 2 and 22 = 4 are factors of 72.
Both 3 and 32 = 9 are factors of 72.
Also, 72 can’t be represented as ab.
Therefore, 72 is an Achilles Number.
Write a program in Java to input an integer from the user
and check whether it is an Achilles Number or not.

#ALGORITHM#
Step1: creating the class
Step 2:entering the number
Step 3: finding the prime number
Step 4: checking
Step 5: printing result
Step 6: end

40
import [Link].*;
class Power
{
public static boolean isPerfectPower(int num){

for(int i = 2; i <= num; i++){


for(int j = 2; j <= num; j++){
if([Link](i, j) == num){
return true;
}

else if([Link](i, j) > num)


break;
}

}
return false;
}
public static void main(String args[]){
Scanner sc=new Scanner([Link]);
[Link]("Enter the number: ");
int num = [Link]();
boolean status = true;
if(!isPerfectPower(num)){
int n = num;
int pf = 2;

41
while(n != 1){
if(n % pf == 0){
int s = pf * pf;
if(num % s != 0){
status = false;
break;
}

n /= pf;
}
else
pf++;
}
}
else
status = false;
if(status)
[Link](num + " is an Achilles Number.");
else
[Link](num + " is not an Achilles
Number.");
}
}

42
⧫OUT4UT⧫

::VDT::
Variable Data type Description

n int To store a number

i int row

j int colomb

pf int To store 2

43
⫷4ROGRAM-9⫸
A Prime-Adam integer is a positive integer (without leading
zeroes) 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’ is 31, then, 132 = 169, and 312 = 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
44
#ALGORITHM#
Step1: creating the class
Step 2: entering the number
Step 3: checking whether the entered number is prime
number or not
Step 4: squaring the number
Step 5: reversing the number
Step 6: checking
Step 7: printing the result
step8: end

import [Link].*;
class PrimeAdam
{
public static void main(String args[])

Scanner sc= new Scanner([Link]);


[Link]("m = ");
int m = [Link]();
[Link]("n = ");
45
int n = [Link]();
if(m >= n){ [Link]("Invalid
input."); return;
}

int count = 0;

[Link]("The Prime-Adam integers are:"); for(int i =


m; i <= n; i++){
if(isPrime(i)){

int rev = reverse(i);


int s1 = i * i;
int s2 = rev * rev;
if(reverse(s1) == s2){
if(count == 0) [Link](i);
else

[Link](", " + i);


count++;
}

if(count == 0) [Link]("NIL");
else

46
[Link]();

[Link]("Frequency of Prime-Adam integers is: "


+ count);
}

public static boolean isPrime(int n){ int


f = 0;
for(int i = 1; i <= n; i++)

if(n % i == 0)
f++;
}

return f == 2;

public static int reverse(int n){


int rev = 0;
for(int i = n; i > 0; i /= 10)
rev = rev * 10 + i % 10;
return rev;

47
}

⧫OUT4UT⧫

::VDT::
Variable Data type Description

num int To store the number


entered by the user

i int Loop variable

j int Loop variable

n int To assign n=num

48
⫷4ROGRAM-10⫸
Prime Palindrome

A prime palindrome integer is a positive integer (without


leading zeroes) which is prime as well as a palindrome.
Given two positive 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.

#ALGORITHM#
Step1: creating the class
Step 2:entering the number
Step 3: finding the prime number
Step 4: reversing the number
Step 5: checking
Step 6: printing the result
Step 7: End.

import [Link].*;
49
class PrimePalindrome

public static void main(String args[])

Scanner sc= new Scanner ([Link]);

[Link]("m = ");

int m = [Link]();

[Link]("n = ");

int n = [Link]();

if(m > 3000 || n > 3000 || m > n){

[Link]("OUT OF RANGE.");

return;

int count = 0;

[Link]("THE PRIME PALINDROME INTEGERS


ARE:");

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

if(isPalindrome(i) && isPrime(i))

if(count == 0)

[Link](i);

else

[Link](", " + i); count++;

}
[Link]();
[Link]("FREQUENCY OF PRIME PALINDROME
INTEGERS: " + count);

public static boolean isPalindrome(int n){ int

51
rev = 0;

for(int i = n; i > 0; i /= 10)

rev = rev * 10 + i % 10;

return n == rev;

public static boolean isPrime(int n){ int

f = 0;

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

if(n % i == 0)

f++;

if(f > 2)

return false;

}
return f == 2;

52
⧫OUT4UT⧫

::VDT::

Variable Data type Description

m int To store positive no.

n int To store the no.

53
COUNT INT ADDING

⫷4rOGraM-11⫸
Reverse Matrix Elements
Example:

becomes

27 173 5

#ALGORITHM#

Step1: creating the class.


Step 2:entering the size of the matrix .
Step 3:reversing the matrix.
Step 4: printing.

54
Step 5: end.

import [Link].*;
class MatRev{
private int arr[][];
private int m;
private int n;
public MatRev(int mm, int nn){
m = mm;
n = nn;

arr = new int[m][n];


}
public void fillArray()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter matrix elements:"); for(int
i = 0; i < m; i++){
for(int j = 0; j < n; j++){
arr[i][j] = [Link]();
}

}
}
public int reverse(int x){
int rev = 0;
55
for(int i = x; i != 0; i /= 10)
rev = rev * 10 + i % 10;
return rev;

}
public void revMat(MatRev p){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++)
{
[Link][i][j] = reverse([Link][i][j]);
}

}
}
public void show(){ for(int
i = 0; i < m; i++){
for(int j = 0; j < n; j++){
[Link](arr[i][j] + "\t");
}

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

56
[Link]("Enter number of rows: ");
int x = [Link]();
[Link]("Enter number of columns: ");
int y = [Link]();
MatRev obj1 = new MatRev(x, y);
MatRev obj2 = new MatRev(x, y);
[Link](); [Link](obj1);
[Link]("Original Matrix");

[Link]();

[Link]("Matrix with reversed elements");


[Link]();
}

⧫OUT4UT⧫

57
::VDT::

Variable Data type Description

m int To store positive


no.

n int To store the no.

J INT COLOMB

58
⫷4ROGRAM-12⫸
Program to check whether the matrix entered is
Identity matrix or not.

#ALGORITHM#
Step1: creating the class
Step 2:entering the size of the matrix
Step 3:Checks whether given matrix is a square matrix or not
Step 4:Checks if diagonal elements are equal to 1 and rest of
elements are 0
Step 5: checking
Step 6: printing the result
Step 7: End.

import [Link].*;
public class IdentityMatrix
{
public static void main(String[] args)
{
Scanner sc= new Scanner([Link]); int
row, cols;
boolean flag = true;

[Link]("Enter the row and column size"); row=


59
[Link]();
cols=[Link]();

//Initialize matrix a
int a[][] =new int [row][cols];
[Link]("Enter the elements of matrix");
for(int i=0; i<row; i++)
{

for(int j=0;j<cols;j++)
{
a[i][j]= [Link]();
}
}
//Checks whether given matrix is a square matrix or not if(row
!= cols)
{

[Link]("Matrix should be a square matrix");


}
else
{
//Checks if diagonal elements are equal to 1 and rest of
elements are 0
for(int i = 0; i < row; i++){

60
for(int j = 0; j < cols; j++){
if(i == j && a[i][j] != 1){
flag = false;
break;
}

if(i != j && a[i][j] != 0){


flag = false; break;
}

}
}

if(flag)
[Link]("Given matrix is an identity
matrix");
else
[Link]("Given matrix is not an identity
matrix");
}
}
}

61
⧫OUT4UT⧫

62
::VDT::
VARIABLE DATA-TYPE DESCRIPTION

N int Size of the matrix

M char Matrix

I int Loop variable

J int Loop variable

First char First character

Second char second character

Third char third character

62
⫷4ROGRAM-13⫸
A happy number is a number in which eventual sum of the square
the digit is equal to one.
Example:- 100= 1^2 + 0^2+0^2=1. Hence, number is a happy
number
Design a class Happy to check whether a number is happy or not.
Class Name : Happy
Data members \instant variables :-
n : Stores the number
Member functions :-
Happy( ) : Constructor to assign 0 to n.
void getnum(int nn) : to assign a parameter value to n=nn.
void int sum_sq_digits(int x) : to find the sum of square digits using
recursion.
void ishappy() : check whether a number is happy or not by calling.
sum_sq_digits method
Also, define a main() function to create an object and call the
methods to check whether a number is happy number or not.

#ALGORITHM#
STEP 1- Class Happy created.
STEP 2- Number entered by the user.
STEP 3-Sum of the digits of the number found using recursion
technique.
STEP 4-Condition is checked for the number to be a happy number.
STEP 5-Appropriate message is displayed.
STEP 6-END.
62
import [Link];
class Happy
{
int n,s,d;
Happy()
{
n=0;
}
void get_num(int nm)
{
n=nm;
}
int sum_sq_digits(int x)
{

if(x>0)
{

d=x%10;
s=s+d*d;
x=x/10;
return sum_sq_digits(x);
}
else
{
return s;
63
}}
void isHappy()
{
int a;
while(n>9)
{
s=0;
n=sum_sq_digits(n);
}
if(n==1)
{
[Link]("HAPPY NUMBER");
}
else
{
[Link]("NOT A HAPPY NUMBER");
}}
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter a number");
int num=[Link]();
{
Happy ob=new Happy();
ob.get_num(num);
ob.sum_sq_digits(num);
[Link]();
}
64
}
}

⧫OUT4UT⧫

::VDT::

VARIABLE DATATYPE DESCRIPTION

N INT TO STORE THE NUMBER

S INT SUM
D INT REMOVING THE DIGITS

NUM INT TO STORE THE VALUE

65
⫷4ROGRAM-14⫸
Write a program to accept a matrix from the user and print its
lower and upper triangle .
Example:
Matrix:
0011
0111
0001
0000

Output:
Upper Triangle
0 011
011
00
0
Lower Triangle
1
01
0001
0000

#ALGORITHM#

Step1: creating class


Step 2:entering the size of the matrix
66
Step 3:Function to display upper and lower triangle
Step 4: Function to display upper and lower triangle
Step 5: printing the matrix
Step 6: end

Import [Link].*;

public class UpperAndLowerTriangle {


// Function to display upper and lower triangle
static void displayUpperAndLowerTriangle(int[][] matrix){
int order = [Link];
int i,j;
for(i=0; i<order; i++){
for(j=0; j<order;j++){
if((i+j) <order)
[Link](matrix[i][j] + "\t");
}
[Link]();
}
for(i=0; i<order; i++){
for(j=0; j<order;j++){
if((i+j) >=order)
[Link](matrix[i][j] + "\t");
}
[Link]();
}
67
}
// Function to read user input
public static void mainFunction to display upper and lower
triangle
(String[] args) {
Scanner sc=new Scanner([Link]);
int order;
[Link]("Enter the order of the matrix");
try{
order =[Link]();
}
catch(Exception e)
{
[Link]("An error occurred");
return;
}
int[][] matrix = new int[order][order];
[Link]("Enter matrix elements");
int i,j;
for(i=0; i<order; i++){
for(j=0; j<order; j++){
try{
matrix[i][j] = [Link]();
}
catch(Exception e){
[Link]("An error occurred");
return;
}
68
}
}
[Link]("Tha matrix is");
for(i=0; i<order; i++){
for(j=0; j<order; j++){
[Link](matrix[i][j] + "\t");
}
[Link]();
}
[Link]("The upper and lower triangle is");
displayUpperAndLowerTriangle(matrix);
}
}

69
⧫OUT4UT⧫

70
::VDT::

VARIABLE DATA-TYPE DESCRIPTION

N int Size of the matrix

M char Matrix

I int Loop variable

J int Loop variable

First char First character

Second char second character

Third char third character

71
⫷4ROGRAM-15⫸
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 with the sample data and some random data:

Example 1

INPUT: ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL


ANYMORE.

OUTPUT: NUMBER OF WORDS BEGINNING AND ENDING WITH A


VOWEL= 3

72
#ALGORITHM#
Step1: creating the class
Step 2:entering the word
Step 3:Finding the number of words beginning and ending
with a vowel.
Step 4: Place the words which begin and end with a vowel at
the beginning, followed by the remaining words as they occur
in the sentence.
Step 5: checking
Step 6: printing
Step 7: End.

import [Link].*;
class Vowel
{
boolean isVowel(String w) // Function to check if a word begins
and ends with a vowel or not
{
int l = [Link]();
char ch1 = [Link](0); // Storing the first character
char ch2 = [Link](l-1); // Storing the last character
if((ch1=='A' || ch1=='E' || ch1=='I' || ch1=='O' || ch1=='U') &&
73
(ch2=='A' || ch2=='E' || ch2=='I' || ch2=='O' || ch2=='U'))
{
return true;
}
else
{
return false;
}
}

public static void main(String args[])


{
Vowel ob = new Vowel();
Scanner sc = new Scanner([Link]);

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


String s = [Link]();
s = [Link]();
int l = [Link]();
char last = [Link](l-1); // Extracting the last character

/* Checking whether the sentence ends with '.' or '?' or not */


if(last != '.' && last != '?' && last != '!')
{
[Link]("Invalid Input. End a switch either'.', '?' or
'!' only");
}
else
74
{
StringTokenizer str = new StringTokenizer(s," .?!");
int x = [Link]();
int c = 0;
String w = "", a = "", b = "";

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


{
w = [Link](); // Extracting words and saving them in
w

if([Link](w))
{
c++; // Counting all words beginning and ending with a
vowel
a = a + w + " "; // Saving all words beginning and ending
with a vowel in variable 'a'
}
else
b = b + w + " "; // Saving all other words in variable 'b'
}
[Link]("OUTPUT : \nNUMBER OF WORDS
BEGINNING AND ENDING WITH A VOWEL = " + c);
[Link](a+b);

}
}

75
⧫OUT4UT⧫

::VDT::
VARIABLE DATA-TYPE DESCRIPTION

S string to store a sentence

L string finding the length of a sentence

char last string Extracting the last character

76
⫷4ROGRAM-1C⫸
Write a program to accept a sentence which may be terminated by
either ‘.’ ‘?’ or ‘!’ only. Any other character may be ignored. The
words may be separated by more than one blank space and are in
UPPER CASE.

Perform the following tasks:

(a) Accept the sentence and reduce all the extra blank space
between two words to
a single blank space.
(b) Accept a word from the user which is part of the sentence
along with its position number and delete the word and display
the sentence.

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

Example 1

INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.

WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6

77
#ALGORITHM#
Step1: creating th class
Step 2:accepting he sentence
Step 3:reducing all the extra blank space between two words
to a single blank space.
Step 4: Accept a word from the user which is part of the
sentence along with its position number and delete the word
and display the sentence.
Step 5: checking
Step 6: printing
Step 7: End.

import [Link].*;
class RemoveWord
{
public static void main (String args[])
{

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


String s = [Link]();
s = [Link]();
int l = [Link]();
78
char last = [Link](l-1); // Extracting the last character

/* Checking whether the sentence ends with '.' or '?' or not */


if(last != '.' && last != '?' && last != '!')
{
[Link]("Invalid Input. End a sentence with either
'.', '?' or '!' only");
}
else
{
StringTokenizer str = new StringTokenizer(s," .?!");
int c = [Link]();
String w="",ans = "";
[Link]("Enter the word to delete : ");
String del = [Link]();
[Link]("Enter the word position is the sentence :
");
int x = [Link]();

if(x<1 || x>c) // Checking whether integer inputted is


acceptable or not
{
[Link]("Sorry! The word position entered is out
of range");
}
else
{
for(int i=1; i<=c; i++)
79
{
w = [Link]();
/* Skipping if the word to delete and the position
matches */
if([Link](del)==true && i == x)
continue;
ans = ans + w + " ";
}
[Link]("Output : "+[Link]()+last);
}
}
}
}
::VDT::
VARIABLE DATA-TYPE DESCRIPTION

S string to store a sentence

L string finding the length of a sentence

char last string Extracting the last character

i int looping

80
⫷4ROGRAM-17⫸
Write a program to input a word from the user and remove the
duplicate characters present in it.

Example:

INPUT – abcabcabc
OUTPUT – abc

#ALGORITHM#
Step1: creating the class
Step 2:entering te woard
Step 3:checking the duplicate words
Step 4: removing the duplicate words
Step 5: checking
Step 6: printing
Step 7: End.

81
import [Link].*;
class RemoveDupChar
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter any word : ");
String s = [Link]();
int l = [Link]();
char ch;
String ans="";

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


{
ch = [Link](i);
if(ch!=' ')
ans = ans + ch;
s = [Link](ch,' '); //Replacing all occurrence of the current
character by a space
}

[Link]("Word after removing duplicate characters :


" + ans);
}
}
82
⧫OUT4UT⧫

::VDT::

VARIABLE DATA TYPE DESCRIPTION


S STRING STORING WOARD
I INT LOOPING

83
ANS STRING SPACE

⫷4ROGRAM-18⫸
The result of a quiz competition is to be prepared as follows:

The quiz has five questions with four multiple choices (A, B, C, D),
with each question carrying 1 mark for the correct answer. Design
a program to accept the number of participants N such that N
must be greater than 3 and less than 11, Accept a word from the
user which is part of the sentence along with its position number
and delete the word and display the sentence.
. Create a double dimensional array of size (Nx5) to store the
answers of each participant row-wise.

Calculate the marks for each participant by matching the correct


answer stored in a single dimensional array of size 5. Display the
scores for each participant and also the participant(s) having the
highest score.
Example: If the value of N = 4, then the array would be invalid
Note: Array entries are line fed (i.e. one entry per line)

#ALGORITHM#
Step1: crating the class

84
Step 2: accept the number of participants N such that N must
be greater than 3 and less than 11
Step 3:Accept a word from the user which is part of the
sentence along with its position number and delete the word
and display the sentence.
Step 4: Create a double dimensional array of size (Nx5) to
store the answers of each participant row-wise.
Step 5: Calculate the marks for each participant by matching
the correct
Step 6: Display the scores for each participant and also the
participant(s) having the highest score.
Step 7: End.

import [Link].*;
class QuizResult
{
char A[][],K[];
int S[],n;

void input()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter number of participants : ");
n = [Link]();
if(n<4 || n>10)
{
85
[Link]("INPUT SIZE OUT OF RANGE");
[Link](0);
}
A = new char[n][5]; // Array to store the answers of every
participants
K = new char[5]; // Array to store answer key
S = new int[n]; // Array to store score of every participant
[Link]("\n* Enter answer of each participant
row-wise in a single line *\n");
for(int i = 0; i<n; i++)
{
[Link]("Participant "+(i+1)+" : ");
for(int j=0; j<5; j++)
{
A[i][j] = [Link]().charAt(0);
}
}
[Link]("\nEnter Answer Key : ");
for(int i = 0; i<5; i++)
{
K[i] = [Link]().charAt(0);
}
}

void CalcScore() // Function to calculate score of every participant


{

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


86
{
S[i] = 0;
for(int j=0; j<5; j++)
{
if(A[i][j] == K[j]) // Checking if Answer of the participants
match with the key or not
{
S[i]++;
}
}
}
}

void printScore()
{
int max = 0;
[Link]("\nSCORES : ");
for(int i = 0; i<n; i++)
{
[Link]("\tParticipant "+(i+1)+" = "+S[i]);
if(S[i]>max)
{
max = S[i]; // Storing the Highest Score
}
}
[Link]();

[Link]("\tHighest Score : "+max);


87
[Link]("\tHighest Scorers : ");
for(int i = 0; i<n; i++) // Printing all those participant number
who got highest score
{
if(S[i] == max)
{
[Link]("\t\t\tParticipant "+(i+1));
}
}
}

public static void main(String args[])


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

88
OUT4UT

::VDT::
VARIABLE DATA TYPE DESCRIPTION
89
I INT ROW
J INT COLOMB

N INT TO STORE NUMBER

⫷4ROGRAM-19⫸
A company manufactures packing cartons in four sizes, i.e. cartons
to accommodate 6 boxes, 12 boxes, 24 boxes and 48 boxes. Design
a program to accept the number of boxes to be packed (N) by the
user (maximum up to 1000 boxes) and display the break-up of the
cartons used in descending order of capacity (i.e. preference
should be given to the highest capacity available, and if boxes left
are less than 6, an extra carton of capacity 6 should be used.)

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

Example 1

INPUT : N = 726

OUTPUT :

48 x 15 = 720
6x1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16

90
#ALGORITHM#
Step1: create the class
Step 2: accept the number of boxes to be packed (N) by the
user (maximum up to 1000 boxes)
Step 3:display the break-up of the cartons used in descending
order of capacity
Step 4: checking
Step 5: printing
Step 6: end

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

[Link]("Enter number of boxes to be packed : ");


int N = [Link]();
if(N<1 || N > 1000)
{
[Link]("INVALID INPUT");
}
91
else
{
int cart[] = {48, 24, 12, 6};
int copy = N;
int totalCart = 0,count = 0;
[Link]("OUTPUT :");
for(int i=0; i<4; i++)
{
count = N / cart[i];
if(count!=0)
{
[Link]("\t"+cart[i]+"\tx\t"+count+"\t=
"+cart[i]*count);
}
totalCart = totalCart + count;
N = N % cart[i];
}
if(N>0)
{
[Link]("\tRemaining Boxes "+N+" x 1 = "+N);
totalCart = totalCart + 1;
}
else
{
[Link]("\tRemaining Boxes\t\t= 0");
}
[Link]("\tTotal number of boxes = "+copy);
[Link]("\tTotal number of cartons = "+totalCart);
92
}
}
}

⧫OUT4UT⧫

::VDT::

VARIABLE DATA TYPE DESCRIPTION


N INT STORING THE NUMBER
COUNT INT COUNTING
TOTAL CART INT ADDING

93
⫷4ROGRAM-20⫸
Write a Program in Java to input a number and check whether it is
an Evil Number or not.

Evil Number : An Evil number is a positive whole number which


has even number of 1’s in its binary [Link] 1
INPUT : 15
BINARY EQUIVALENT : 1111
NO. OF 1’s : 4
OUTPUT : EVIL NUMBER

Step1: creating the class


Step 2:entering the number
Step 3: count no of 1's in binary
Step 4: convert a number to Binary

94
Step 5: checking
Step 6: printing
Step 7: End.

import [Link].*;
class EvilNumber
{
String toBinary(int n) // Function to convert a number to Binary
{
int r;
String s=""; //variable for storing the result

char dig[]={'0','1'}; //array storing the digits (as characters) in a


binary number system

while(n>0)
{
r=n%2; //finding remainder by dividing the number by 2
s=dig[r]+s; //adding the remainder to the result and
reversing at the same time
n=n/2;
}
return s;
}

int countOne(String s) // Function to count no of 1's in binary


number
{
95
int c = 0, l = [Link]();
char ch;
for(int i=0; i<l; i++)
{
ch=[Link](i);
if(ch=='1')
{
c++;
}
}
return c;
}
public static void main(String args[])
{
EvilNumber ob = new EvilNumber();
Scanner sc = new Scanner([Link]);

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


int n = [Link]();

String bin = [Link](n);


[Link]("Binary Equivalent = "+bin);
int x = [Link](bin);
[Link]("Number of Ones = "+x);

if(x%2==0)
[Link](n+" is an Evil Number.");
else
96
[Link](n+" is Not an Evil Number.");
}
}

⧫OUT4UT⧫

::VDT::
VARIABLE DATA TYPE DESCRIPTION
S STRING STORING THE RESULT

N INT FINDING REMAINDER


C INT COUNTING
97
CH CHARACTER CHECKING

BIBLIOGRAPHY
Class 12 COMPUTER BOOK.
GOOGLE.
WIKIPEDIA

98

You might also like