0% found this document useful (0 votes)
2 views

Computer Project (1)

This document is a computer science project by Abdul Majid for Class XII at Lucknow Public College, focusing on Java programming concepts. It includes acknowledgments, a preface, an index, and detailed explanations of various Java programs related to composite magic numbers, prime palindromes, and special numbers. The project also contains algorithms and code implementations for each concept discussed.

Uploaded by

am3807872
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)
2 views

Computer Project (1)

This document is a computer science project by Abdul Majid for Class XII at Lucknow Public College, focusing on Java programming concepts. It includes acknowledgments, a preface, an index, and detailed explanations of various Java programs related to composite magic numbers, prime palindromes, and special numbers. The project also contains algorithms and code implementations for each concept discussed.

Uploaded by

am3807872
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
You are on page 1/ 91

Isc Computer project XII 1

UID NO. : 7833167

Index no: 038

Session:2024-2025

Name: Abdul Majid

Class XII- Section - E

Subject: Computer Science

Subject Teacher: Mr. Mohit Kumar Goel

School: Lucknow Public College


Isc Computer project XII 2

ACKNOWLEDGEMENT
Organizing this file was not a child’s
play for me but this task was made easier through my
family members and friends without their cooperation this
file would not have been a success.
While making this project I have left no stone
unturned to make this project the successful one.It is hoped
that both teachers as well as my classmates will find this
project complete in itself. I want to thank my subject
teacher Mr.Mohit Kumar Goel who explained the
programs and topics with full gesture and whose willing
cooperation have been a great help in development of this
project.
My aim will be served if hopefully this
approaches towards brevity, compactness and lucidity
meets the requirement of teachers .I also look forward for
the same love and affection from the above all in the future
to achieve milestones of my life.
Isc Computer project XII 3

PREFACE

This project gives a vivid description of Java programs. An


attempt has been made to cover programs from various
topics such as single and double dimension array, string,
inheritance and programs based on functions, patterns etc.
All the programs are well tested on computer before
incorporating them in this file.
Any recommendation made by the reader to make
this file better would be highly acknowledged.

-Abdul Majid
Isc Computer project XII 4

Index
Number based - 5-15
String programs - 19-27
Stack /que - 30-33
Class based /Funtion calling – 36-60
Inheritance - 63-74
Data Structure - 77-91
Isc Computer project XII 5

A composite number is a positive integer which is composite as well as a


magic number.
Composite number: A composite number is a number which has more than
two factors. For example: 10 Factors are: 1,2,5,10
Magic number: A Magic number is a number in which the eventual sum of the
digit d is equal to 1. For example: 28 = 2+8=10= 1+0=1
Accept two positive integers m and n, where m is less than n as user input.
Display the number of composite magic integers that are in the range between
m and n (both inclusive) and output them along with frequency, in the format
specified below:
Example 1:
INPUT:
m = 10 n = 100
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE: 10, 28, 46, 55, 64, 82, 91, 100
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 8
Example 2:
INPUT:
m = 1200 n = 1300
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE: 1207, 1216, 1225, 1234, 1243, 1252, 1261,
1270, 1288 FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 9

Algorithm-:
Step 1: Program to print magic composite number in a given range.
Step 2: Input two variables m and n to specify the range .
Step 3: Input a counter c and initialize it with 0 .
Step 4: Now start from m taking numbers in the increasing order and check if they are
composite numbers. If yes goto Step 4 else goto Step 9 .
Step 5: Now check if the same number is magic or not by checking if its final sum of digits is
1. If yes goto Step 5 else goto Step 9 .
Step 6: Print the number and increase c by 1 .
Step 7: Repeat the steps 3, 4, 5 until all the numbers between m and n are checked.
Step 8: Print c as the frequency of composite magic numbers between m and n.
Step 9: End class.
---
|Variable | Type |Description

| `n` | `int` | The number to be checked (for composite or magic properties).


Isc Computer project XII 6

| `count` | `int` | Counter for divisors of a number (used in `isComposite`).


| `s` | `int` | Stores the sum of digits of a number (used in `sumDig`).
| `a` | `int` | Resultant sum of digits in `isMagic` to determine if it reduces to 1.
| `m` | `int` | Lower limit of the range entered by the user.
| `c` | `int` | Frequency counter for composite magic integers.
| `i` | `int` | Loop variable iterating over the range `[m, n]`.
| `ob` | `MagicComposite` | Object of the class to access instance methods.
| `in` | `Scanner` | Object for reading user input.

Let me know if you need further clarifications!


Code in java-:

import java.util.*;
class MagicComposite
{
boolean isComposite(int n) // Function to check for Composite number
{
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count>2)
return true;
else
return false;
}
int sumDig(int n) // Function to return sum of digits of a number
{
int s = 0;
while(n>0)
{
s = s + n%10;
n = n/10;
}
return s;
}
boolean isMagic(int n) // Function to check for Magic number
{
int a = sumDig(n);
while(a>9)
{
Isc Computer project XII 7

a = sumDig(a);
}
if(a == 1)
return true;
else
return false;
}
public static void main(String args[])
{
MagicComposite ob = new MagicComposite ();
Scanner in = new Scanner(System.in);
System.out.print("Enter the lower limit(m) : ");
int m=in.nextLine();
System.out.print("Enter the upper limit(n) : ");
int n=in.nextLine();
int c=0;
if (m<n)
{
System.out.println("The Composite Magic Integers are: ");
for(int i=m; i<=n; i++)
{
if(ob.isComposite(i)==true && ob.isMagic(i)==true)
{
if (c==0) // Printing the first number without any comma
System.out.print(i);
else
System.out.print(", "+i);
c++;
}
}
System.out.println();
System.out.println("The frequency of Composite Magic Integers is : "+c);
}
else
System.out.println("OUT OF RANGE");
}
}
Output:
Isc Computer project XII 8

Design a class PrimePalinGen to generate prime palindrome numbers.


[ A number is said to be prime palindrome if the number is a prime as
well as a palindrome number ]
[ Prime number: A number having only two factors i.e. 1 and itself ]
[ Palindrome number: A number which is same as its reverse ]
Example: 11(where 11 is a prime number and a palindrome number)
Some of the members of the class are given below:
Class name : PrimePalinGen
Data members/instance variables:
start : to store the start of range
end : to store the end of range

Methods/Member functions:
PrimePalinGen (int a, int b) : parameterized constructor to initialize
the data members start=a and end=b
int isPrime(int i) : returns 1 if the number is prime otherwise returns
0.
int isPalin(int i) : returns 1 if the number is a palindrome otherwise
returns 0.
void generate( ) : generates all prime palindrome numbers between start
and end by invoking the functions isPrime() and isPalin().

Specify the class PrimePalinGen giving details of the constructor(


),int isPrime(int), int isPalin(int) and void generate( ). Define a main(
) function to create an object and call thefunctions accordingly to
enable the task.
 Algorithm
 Define the class PrimePalinGen with attributes start and end to store the range.
 Use a parameterized constructor to initialize the range values.
Isc Computer project XII 9

 Implement the isPrime method:


 Return 0 if the number is less than or equal to 1.
 Iterate from 2 to n-1 and check divisibility.
 Return 1 if the number is prime, else 0.
 Implement the isPalin method:
 Reverse the digits of the number.
 Compare the reversed number with the original.
 Return 1 if they are the same, else 0.
 Implement the generate method:
 Iterate through the range [start, end).
 For each number, check if it is both a palindrome and prime using isPalin and isPrime.
 Print numbers satisfying both conditions.
 Create an object of PrimePalinGen with a specific range (e.g., 10 to 500).

 Call the generate method to print all prime palindrome numbers in the range.

Variable Data Type Description


Name
start int Represents the starting value of the range to
find prime palindrome numbers.
end int Represents the ending value of the range to find
prime palindrome numbers.
n int Input number to check if it is prime in the
isPrime method.
flag int Indicates whether a number is prime (1) or not
(0) in isPrime, or a palindrome in isPalin.
num int Input number to check if it is a palindrome in the
isPalin method.
temp int Temporary variable to hold the original value of
num during the palindrome check.
rev int Stores the reversed digits of num in the isPalin
method.
digit int Holds the last digit of num during the
palindrome check.
A PrimePalinGen Object of the PrimePalinGen class to call
methods and generate prime palindromes.
i int Loop variable used in the generate method to
iterate through the range [start, end).

Code in java-:
public class PrimePalinGen
{
int start;
int end;
PrimePalinGen (int a, int b)
{
start = a;
Isc Computer project XII 10

end = b;
}
int isPrime(int n)
{
int flag=1;
// Corner case
if (n <= 1)
flag=0;;
// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
flag=0;
return flag;
}
int isPalin(int num)
{
int temp=num, rev=0,digit=0, flag=0;
while(temp>0)
{
digit=temp%10;
rev=rev*10+digit;
temp= temp/10;
}
if (rev == num)
flag=1;
return flag;
}
void generate( )
{
int flag=1;
System.out.println(" Prime Palindome Nos are ");
for( int i =start; i<end;i++)
if(isPalin(i)==1)
if(isPrime(i)==1){
System.out.print(i+" ");
flag=0;
}
}
public static void main()
{
PrimePalinGen A = new PrimePalinGen(10,500);
A.generate();
}
}
Isc Computer project XII 11

Output:

Design a class Prime.


Data Members-:
n - to store the number

Member Functions-:
Prime(int) - constructor to initialize n
void check( ) - to check if the no is prime or not by calling a function
isPrime(int)
boolean isPrime(int) - returns true/false for prime using recursive
technique

Algorithm-:
 Program to check for prime.
 Input a variable n to store the number from the user.
 Now using recursive technique, find the number of factors of n. If the number of
factors is 2 then n is prime, otherwise not .
 Print an appropriate message with respect to the result obtained.
 End algorithm .
| Variable Name |Data Type |description

|n | int | Stores the number to be checked for primality.


|r | boolean| Stores the result of the `isPrime` method, indicating
|f | int | Represents the current factor being tested
| num | int | Holds the input number provided by the user.
| sc | Scanner| Used to read input from the user in the `main`
| obj |Prime | Object of the `Prime` class, used to call methods and store
the number to check.
Isc Computer project XII 12

Code in java-:
class Prime
{
int n;
Prime()
{
n=0;
}
Prime(int num) //defaultconstructor
{
n=num;
}
void check()
{
boolean r=isPrime(1); //check for prime
if (r==true)
System.out.println(n+” is prime”); //print
else
System.out.println(n+” is not prime”);
} //check
boolean isPrime(int f)
{
if (n==1)
return false;
if (n==f)
return true;
if (n%f==0 && f!=1)
return false;
return isPrime(f+1); //recursive technique
} //isPrime
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println(“enter a number”);
int num=sc.nextInt();
Prime obj=new Prime();
obj=new Prime(num);
obj.check();
} //end of main
} //end of class
Output:-
Isc Computer project XII 13

A special number is a number in which the sum of the factorial of each digit is
equal to the number itself. For example:- 145 = 1! + 4! + 5!
= 1 + 24 + 120
Design a class Special to check if a given number is a special number. Some of
the members of the class are given below:
Class name : Special
Data members
N : Integer
Sum
Member
functions
Special() : constructor to assign 0 to n
Special(int) : Parameterized constructor to assign a
value to ‘n’
void sum() : calculate and display the sum of the
digits factorial
of n using recursion
void isSpecial() : check and display if the number n is a
special number.

Specify the class Special giving details of the constructor, void sum() and void
isSpecial(). You need not write the main function.
 Algorithm
 Prompt the user to input a number and store it in number.
 Copy the value of number into num for later comparison.
 Set sum_Of_Fact to 0.
 While number is greater than 0:
Isc Computer project XII 14

 Extract the last digit of number using number % 10 and store it in last_digit.
 Initialize fact to 1.
 Calculate the factorial of last_digit using a for loop.
 Add the factorial value to sum_Of_Fact.
 Remove the last digit of number by dividing it by 10.
 Compare sum_Of_Fact with num:
 If they are equal, print that the number is a special number.
 Otherwise, print that it is not a special number.
 End Program.

Variable Data Description


Name Type
Variable int Stores the original number entered by the user
Name for comparison.
number int Stores a copy of the original number, used to
process digits.
last_digit int Holds the last digit of the number during each
iteration of the while loop.
sum_Of_Fact int Stores the cumulative sum of the factorials of
the digits of the number.
fact int Temporarily holds the factorial of the current
digit being processed.
i int Loop variable used to calculate the factorial of
the current digit.
sc Scanner Object to read input from the user.

Code in java-:
import java.util.Scanner;
public class SpecialNumber
{
public static void main(String args[])
{
int num, number, last_digit, sum_Of_Fact = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
//reads an integer from the user
number = sc.nextInt();
num = number;
//executes until the condition becomes false
while (number > 0)
{
//finds the alst digit from the given number
last_digit = number % 10;
//variable stores factorial
int fact=1;
//factorial logic
for(int i=1; i<=last_digit; i++)
Isc Computer project XII 15

{
//calculates factorial
fact=fact*i;
}
//calculates the sum of all factorials
sum_Of_Fact = sum_Of_Fact + fact;
//divides the number by 10 and removes the last digit from the number
number = number / 10;
}
//compares the sum with the given number
if(num==sum_Of_Fact)
{
System.out.println(num+ " is a special number.");
}
else
{
System.out.println(num+ " is not a special number.");
}
}
}
Output:

You are given a sequence of n integers, which are called pseudo arithmetic
sequences ( sequences that are in arithmetic progression).
Sequence of n integers : 2, 5, 6, 8, 9, 12 We observe that 2 + 12 = 5 + 9 = 6 +8 =
14
The sum of the above sequence can be calculated as 14 x 3 = 42
For sequence containing an odd number of elements the rule is to double the
middle element, for example 2, 5, 7, 9, 12
=2 +12 = 5 +9 = 7 +7 = 14
14 x 3 = 42 [ middle element = 7]
A class pseudoarithmetic determines whether a given sequence is pseudo-
arithmetic sequence. The details of the class are given below:-
Class name : Pseudoarithmetic
Data members
N : to store the size of the sequence
Isc Computer project XII 16

a[ ] : integer array to store the sequence of


numbers
ans, flag : to store the status
Sum : to store the sum of sequence of numbers
R : to store the sum of 2 numbers
Member :
functions
Pseudoarithmeti : default constructor
c( )
void accept(int : to assign nn to n and to create an integer
nn ) array. Fill in the
elements of the array.
boolean check( ) : return true if the sequence is a pseudo-
arithmetic sequence
otherwise return false.

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


accept(int) and Boolean check(). Also define the main function to create an
object and call methods accordingly to enable the
task.
Algorithm:-
 Prompt the user to enter the phone number (s1), name (s2), and the total number of calls (x).
 Read and store the inputs.
 Create an object ob of the Telcall class, passing s1, s2, and x to the constructor.
 Define the method compute:
 If calls are between 1-100, set Amt = 500.
 If calls are between 101-200, set Amt = 500 + (calls above 100) * 1.
 If calls are between 201-300, set Amt = 500 + (calls above 100) * 1.2.
 If calls exceed 300, set Amt = 500 + (calls above 100) * 1.5.
 Define the method dispdata:
 Print the phone number, name, total calls, and calculated amount in a formatted table.
 Call the compute method to calculate the bill amount.
 Call the dispdata method to display the customer data.

Variable Data Description


Name Type
Name String Stores the name of the customer.
N int Stores the total number of calls made by the
customer.
Phno int Stores the phone number of the customer.
Amt double Stores the calculated bill amount based on the
number of calls.
s1 int Temporary variable to store the phone number
input from the user.
Isc Computer project XII 17

s2 String Temporary variable to store the name input from


the user.
x int Temporary variable to store the number of calls
input from the user.
ob Telcall Object of the Telcall class used to invoke methods
and manage customer data.
sc Scanner Object of the Scanner class used to read input from
the user.

Code in java-:
import java.util.*;
public class Pseudoarithmetic
{
int n,sum,r;
boolean ans,flag;
int a[];
public Pseudoarithmetic()
{
ans=true;
flag=true;
}
public void accept(int nn)
{
int i=0;
Scanner sc=new Scanner(System.in);
n=nn;
a=new int[n];
System.out.println("Enter" +n + "elements");
for(i=0;i< n;i++)
{
a[i]=sc.nextInt();
}
}
public boolean check()
{
int i=0,j=0;
r=a[0]+a[n-1];
if(n%2==0)
{
for(i=0;i< n/2;i++)
{
if((a[i]+a[n-1-i])!=r)
{
flag=false;
}
}
}
Isc Computer project XII 18

else
{
for(j=0;j<= n/2;j++)
{
if((a[j]+ a[n-1-j])!=r)
{
ans=false;
}
}
}
if(flag ==true)
{
sum=n/2*r;
}
if(ans=true)
{
sum=(n/2+1)*r;
}
if(ans==false || flag==false)
{
return false;
}
else
{
return true;
}
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter size of sequence");
int nn=sc.nextInt();
Pseudoarithmetic ob1=new Pseudoarithmetic();
ob1.accept(nn);
System.out.println(ob1.check());
}
}
Output:
Isc Computer project XII 19

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 the 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
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
 Declare a string variable str to hold the sentence.

 Initialize str to an empty string.

 Create a Scanner object to take input from the user.


 Read a sentence from the user and store it in str.

 Initialize a counter c to zero.


 Loop through each character in the word w:
o Convert the character to uppercase.
o Check if the character is a vowel (A, E, I, O, U):
 If it is, increment the counter c.

 Return the count of vowels c.


 Create a new WordWise object obj.
 Append a space to the end of str and store it in a new string s.
 Initialize an empty string word to collect individual words.
 Loop through each character in s:
o If the character is a space:
 Calculate the vowel count of the word by calling freq_vowel(word).
 Print the word and its vowel count.
Isc Computer project XII 20

 Reset word to an empty string.


o Otherwise, add the character to word.

 Create an instance of WordWise.


 Call readsent to get input from the user.
 Call arrange to process and display each word with its vowel count.

 Variable Name Data Type Description


str String Stores the input sentence entered by the user.
in Scanner Used to read input from the user in the readsent method.
w String Represents a single word whose vowels are counted in the freq_vowel method.
c int Counts the number of vowels in the given word.
ch Char Represents the current character being checked for vowels in the freq_vowel method.
ch1 char Stores the uppercase version of the current character for case-insensitive comparison.
S String A copy of str with an extra space appended, used for processing words in the sentence.
word String Temporarily holds the current word being formed while iterating through the sentence.
Vcount int Stores the count of vowels in the current word.
obj WordWise Object of the WordWise class used to call methods.

Code in java-:
import java.util.Scanner;
public class WordWise
{
String str;
WordWise()
{
str="";
}
void readsent()
Scanner in = new Scanner(System.in);
str=in.nextLine();
}
int freq_vowel(String w)
{
int c = 0;
for(int i=0;i<w.length();i++)
{
char ch = w.charAt(i);
char ch1 = Character.toUpperCase(ch);
if(ch1=='A' || ch1=='E' || ch1=='I' || ch1=='O' || ch1=='U')
{
c++;
}
}
return c;
}
void arrange()
{
WordWise obj = new WordWise();
Isc Computer project XII 21

String s = str+" ";


String word="";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)==' ')
{
int Vcount = obj.freq_vowel(word);
System.out.println(word + " " + Vcount);
word="";
}
else
{
word=word+s.charAt(i);
}
}
}
public static void main(String args[])
{
WordWise obj = new WordWise();
obj.readsent();
obj.arrange();
}
}

Output:

Write a program to create a class TimeDiff with the following discription...


Class name : TimeDiff
Isc Computer project XII 22

Data Members:
h : to store hours
m : to store minutes
s : to store seconds

Member Methods:
TimeDiff () : default constructor
void Accept() : to Accept h,m,s from user
TimeDiff Calculate(TimeDiff) : to receive a Time and return the Time after the
current Time interval.
void Display() : to display the values of hours, minutes and seconds.
void main() : to accept a time and an interval and display the time after the
given interval by calling member methods.
 Algorithm
 Define the TimeDiff class with attributes h, m, and s to store hours, minutes, and seconds.
 Define a default constructor to initialize h, m, and s to 0.
 Step 2: Accept Method
 Prompt the user to enter time in hours, minutes, and seconds.
 Read and store the values in the respective variables (h, m, and s) using a Scanner object.
 Step 3: Calculate Method
 Define the Calculate method to add two TimeDiff objects:
 Add the corresponding hours, minutes, and seconds of the current object (this) and the parameter
object A.
 Convert excess seconds into minutes (B.m = B.m + B.s / 60; B.s = B.s % 60).
 Convert excess minutes into hours (B.h = B.h + B.m / 60; B.m = B.m % 60).
 Use a 12-hour format by taking the modulo of the total hours (B.h = B.h % 12).
 Return the resulting TimeDiff object B.
 Step 4: Display Method
 Define the Display method to print the time in hh:mm:ss format.
 Step 5: Main Method
 Create three objects (ob1, ob2, and ob3) of the TimeDiff class.
 Accept the first time (ob1) as the current time.
 Accept the second time (ob2) as the time interval.
 Call the Calculate method on ob2 with ob1 as an argument, and store the result in ob3.
 Display the resulting time using the Display method.

Variable Variable Variable Name


Name Name
h int Stores the hours of the time.
m int Stores the minutes of the time.
s int Stores the seconds of the time.
sc Scanner Used to read input from the user in the Accept
method.
Isc Computer project XII 23

A TimeDiff Represents an object of the TimeDiff class passed as


an argument to the Calculate method.
B TimeDiff Represents the resulting TimeDiff object after adding
the current object and A.
ob1 TimeDiff Represents the first time input (e.g., current time).
ob2 TimeDiff Represents the second time input (e.g., time
interval).
ob3 TimeDiff Represents the result of adding ob1 and ob2 using
the Calculate method.

Code in java-:
import java.util.*;
class TimeDiff
{
int h,m,s;
TimeDiff()
{
h=m=s=0;
}
void Accept()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Time in hours, minutes and seconds:");
h=sc.nextInt();
m=sc.nextInt();
s=sc.nextInt();
}
TimeDiff Calculate(TimeDiff A)
{
TimeDiff B=new TimeDiff();
B.h=this.h+A.h;
B.m=this.m+A.m;
B.s=this.s+A.s;
B.m=B.m+B.s/60;
B.s=B.s%60;
B.h=B.h+B.m/60;
B.m=B.m%60;
B.h=B.h%12;
return B;
}
void Display()
{
System.out.print(h+":"+m+":"+s);
Isc Computer project XII 24

}
void main()
{
TimeDiff ob1=new TimeDiff();
TimeDiff ob2=new TimeDiff();
TimeDiff ob3=new TimeDiff();
System.out.print("Enter Current Time in hours, minutes and seconds : ");
ob1.Accept();
System.out.print("Enter Time Interval in hours, minutes and seconds : ");
ob2.Accept();
ob3=ob2.Calculate(ob1);
ob3.Display();
}
}
Output:

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:
Class name : Rearrange Data member/instance variable: 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
Isc Computer project XII 25

functions accordingly to enable the task.


Algorithm:-
 Initialize variables wrd to store the input word and newwrd for the rearranged word.
 Use the readword() method to accept a word from the user.
 Convert the word to uppercase.
 Loop through each character:
 If it is a vowel (A, E, I, O, U), increment the vowel count.
 Otherwise, increment the consonant count.
 Loop through the word again:
 Collect all vowels into a string.
 Collect all consonants into another string.
 Concatenate the vowels and consonants into newwrd.
 Show the original word, vowel and consonant frequencies, and the rearranged word.
Variable Type Description
Name
wrd String Stores the original word input by the user.
newwrd String Stores the rearranged word (vowels first,
consonants later).
v int Counts the number of vowels in the word.
c int Counts the number of consonants in the word.
ch char Holds the current character being processed in
the word during iteration.
vowels String Temporary string to store all vowels from the
word during rearrangement.
consonants String Temporary string to store all consonants from
the word during rearrangement.

Code in java-:
import java.util.*;
class Rearrange
{
String wrd;
String newwrd;
public Rearrange()
{
wrd = new String();
newwrd = new String();
}
public void readword()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the word:");
wxd = sc.next();
}
public void freq_vow_con() {
wrd = wrd.toUpperCase();
int v = 0;
int c = 0;
Isc Computer project XII 26

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


char ch = wrd. char At(i);
if(Character.isLetter(ch)) {
switch(ch) {
case 'A':
v++;
case'E':
v++
case T:
v++;
case 'O':
v++
case 'U':
v++;
break;
default:
C++;
}
}
}
System.out.println("Frequency of vowels: "+v);
System.out.println("Frequency of consonants: "+c);
}
public void arrange() {
String v = new String();
String c = new String();
wrd = wrd.toUpperCase();
for(int i = 0; i < wrd. length(); i++) {
char ch = wrd.charAt(i);
if(Character.isLetter!ch)) {
switch(ch) {
case 'A':
case'E':
case T:
case 'O':
case 'U':
v += ch;
break;
default:
c+= ch;
}
}
}
newwrd = v + c;
}
public void display() {
System.out.println("Original word:" + wrd);
Isc Computer project XII 27

System.out.prfntln("Rearranged word:" + newwrd);


}
public static void main(String args[])
{
Rearrange obj = new Rearrange();
obj.readword();
obj.freq_vow_con();
obj.arrange();
obj.display();
}
}
Output:-

Input a paragraph containing 'n' number of sentences where (1<=n<=4). The


words are to be separated with single blank space and are in upper case. A
sentence may be terminated either with a full stop (.) or question mark (?).
Perform the following:
1. Enter the number of sentences, if it exceeds the limit show a message.
2. Find the number of words in the paragraph
3. Display the words in ascending order with frequency.
Example 1
INPUT: Enter number of sentences: 1
Enter sentences:
TO BE OR NOT TO BE.
OUTPUT:
Total number of words: 6
WORD FREQUENCY
OR 1
NOT 1
TO 2
BE 2
Isc Computer project XII 28

Algorithm-:
 Program to input >=4 number of sentences and print words and their frequency .
 Input number of sentences to be inputted by user .
 Input the sentences from user.
 Join all sentences inputted.
 Chop a word from the sentence and check its frequency and print it in the given
format also count the number of word .
 Delete the word whose frequency is checked .
 Repeat step 5 and 6.
 Print the total number of word.
 End algorithm.
| Variable Name | Data Type |Description

| `s` | `String` | Temporarily holds a word or string for comparison or swapping


| `str` | `String` | Stores the input paragraph entered by the user.
| `sarr` | `String[]` | Array to store individual words from the paragraph.
| `strarr` | `String[]` | Array to store unique words for frequency analysis.
| `st` | `StringTokenizer`| Tokenizes the input paragraph into words based on
delimiters like `, . ?`.
| `i` | `int` | Loop control variable for the outer loop.
| `j` | `int` | Loop control variable for the inner loop.
| `n` | `int` | Stores the number of sentences or is reused for other purposes
| `c` | `int` | Counts occurrences of a word in the paragraph.
| `index` | `int` | Tracks the current position in `sarr` while storing tokens.
| `fre` | `int[]` | Array to store the frequency of each unique word.
| `index1` | `int` | Tracks the position in `strarr` and `fre` during frequency cal.
| `in` | `Scanner` | Used to read input from the user.
Code in java-:
import java.io.*;
import java.util.*;
class SentencesOrder
{
String s,str,sarr[],strarr[];
StringTokenizer st;
int i,j,n,c,index=0,fre[],index1=0;
Scanner in = new Scanner(System.in());
public void take() throws IOException
{
System.out.println(“Enter the Number of sentences:”);
n=in.nextLine();
if(n< 1 || n >4)
{
Isc Computer project XII 29

System.out.println(“Wrong Input…”);
return;
}

System.out.println(“Enter the Paragraph:”);


str=in.nextLine();
st=new StringTokenizer(str,”,.? “);
n=st.countTokens();
System.out.println(“Number of Words in the paragraph=”+n);
sarr=new String[n];
strarr=new String[n];
fre=new int[n];
while(st.hasMoreTokens())
{
sarr[index++]=st.nextToken();
}
for(i=0;i< index-1;i++)
{
for(j=i+1;j< index;j++)
{
if(sarr[i].compareTo(sarr[j]) > 0)
{
s=sarr[i];
sarr[i]=sarr[j]; }
}
c=1;
s=sarr[0];
for(i=1;i< index;i++)
{
if(!s.equals(sarr[i]))
{
strarr[index1]=s;
fre[index1++]=c;
c=1;
s=sarr[i];
}
else
c++;
}
strarr[index1]=s;
fre[index1++]=c;
for(i=0;i< index1-1;i++)
{
for(j=i+1;j< index1;j++)
Isc Computer project XII 30

{
if(fre[i] > fre[j])
{
n=fre[i];
fre[i]=fre[j];
fre[j]=n;
s= strarr[i];
strarr[i]=strarr[j];
strarr[j]=s;
}
}
}
System.out.println(“WORD FREQUENCY”);
for(i=0;i< index1;i++)
System.out.println(strarr*i++” “+fre*i+);
}
}

Output:

Design a class Stack-:


Data Members-:
int arr[ ] – size 50
int size – store no of elements
int top

Member Functions-:
Stack(int s) – to initialize the size by s and top by -1
Isc Computer project XII 31

void pushvalues(int v) – to fill the stack if it is empty otherwise display


message – “overflow”
int popvalues() – to delete value from the stack and return it, if possible
otherwise display – “underflow” and return -999
void display()

 Algorithm-:
 Program to design a stack
 Input an int array of max size 50
 Design a switch case for the user’s choice of adding or deleting a value from stack
 If user’s choice is 1 then add a value given by the user in the stack. If no more values
can be added, print appropriate message
 If the user’s choice is 2 them delete the existing value in stack. If the stack is already
empty then print an appropriate message
 Display the stack after each choice
 End algorithm

 Code in java-:
import java.util.*;
class stack
{
int arr[],size,top;

stack (int s)
{
size =s;
arr=new int [size];
top=-1;
}//constructor
void pushvalues (int v)
{
if (top<size-1)
{
++top;
arr[top]=v;
}
else
System.out.println ("overflow");
} //pushvalues
int popvalues ()
{
Isc Computer project XII 32

if (top!=-1)
{
int x=arr[top];
top--;
return x;
}
else
{
System.out.println("underflow");
return -999;
}
} //popvalues
void main (int s)
{
Scanner sc=new Scanner (System.in);
stack obj=new stack(s);
while (true)
{
System.out.println("1.push values");
System.out.println("2.pop values");
System.out.println("3.exit");
int ch=sc.nextInt();
switch(ch)
{
case 1:System.out.println("enter value");
int v=sc.nextInt();
obj.pushvalues(v);
System.out.println("values in stack");
obj.display();
break;

case 2:int x=obj.popvalues();


System.out.println("value deleted "+x);
obj.display();
break;

case 3:System.out.println("end");
break;

default:System.out.println("invalid");
}

if (ch==3)
break;
Isc Computer project XII 33

}
} //end of main
void display()
{
for (int i=0;i<=top;i++)
{
System.out.println(arr[i]);
}
} //display
} //end of class

Output:

Design a class SQ
Data Members-:
int arr[ ] – max size 100
int size – store the capacity of arr
int front
int rear
Member Functions-:
SQ(int s) – to initialize the size and front and rear by -1
void addrear(int v) – to add value at rear if possible otherwise display
“Queue full at the rear end… OVERFLOW”
int deletefront() – to delete value from front if possible otherwise display
Isc Computer project XII 34

“Queue empty…UNDERFLOW”
void display() – display elements of the queue
 Algorithm-:
 Program to design a stack.
 Input an int array of max size 50
 Design a switch case for the user’s choice of adding or deleting a value from stack.
 If user’s choice is 1 then add a value given by the user in the stack. If no more values
can be added, print appropriate message.
 If the user’s choice is 2 them delete the existing value in stack. If the stack is already
empty then print an appropriate message.
 Display the stack after each choice .
 End algorithm .

 Code in java-:
import java.util.*;
class SQ
{
int arr[];
int size,front,rear;
SQ(int s)
{
size=s;
front=-1;
rear=-1;
arr=new int [size];
void addrear(int v)
{
if (rear<size-1) {
if (front==-1)
front=0;
arr[++rear]=v;
}
else
System.out.println("Queue full at the rear end...OVERFLOW");
}
int deletefront()
{
if (front<=rear && front>-1){
int x=arr[front];
front++;
return x;
}
else{
Isc Computer project XII 35

System.out.println("Stack empty...UNDERFLOW");
return -999;
}
}
void display()
{
if (front<=rear && front>-1)
{
for (int i=front;i<=rear;i++)
{
System.out.println(arr[i]+" ");
}
}
else
System.out.println("No values to be printed...");
}
void main (int s)
{
Scanner sc=new Scanner (System.in);
SQ obj=new SQ(s);
while (true)
{

System.out.println("1.add values");
System.out.println("2.delete values");
System.out.println("3.exit");
int ch=sc.nextInt();
switch(ch)
{

case 1:System.out.println("enter value");


int v=sc.nextInt();
obj.addrear(v);
System.out.println("values in queue");
obj.display();
break;

case 2:int x=obj.deletefront();


System.out.println("value deleted "+x);
obj.display();
break;

case 3:System.out.println("end");
break;
Isc Computer project XII 36

default:System.out.println("invalid");
}
if (ch==3)
break;
}
}
}
}

Output:-

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


Some of the members of the class are given below:
72 371 5
12 6 426
5 126 94
BECOMES
27 173 5
21 6 624
5 321 49

Class name : MatRev


Data members/instance variables:
arr[ ][ ] : to store integer elements
m : to store the number of rows
Isc Computer project XII 37

n : to store the number of columns

Member functions/methods:
MatRev(int mm, int nn) : parameterised 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 matrix form

Define the class MatRev giving details of the constructor( ), void fillarray( ),
int reverse(int), 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: Class Initialization
 Define the MatRev class with attributes arr, m, and n for the matrix and its dimensions.
 Initialize these attributes using a parameterized constructor.
 Step 2: Fill the Matrix
 Implement fillarray:
 Use nested loops to input elements into the matrix.
 Step 3: Reverse a Number
 Implement reverse:
 Extract digits of the number, build the reversed number, and return it.
 Step 4: Reverse Matrix
 Implement revMat:
 Loop through each element of the input matrix, reverse it using reverse, and store it in the current object.
 Step 5: Display Matrix
 Implement show:
 Print matrix elements row by row with tab spacing.
 Step 6: Main Method
 Read the matrix dimensions from the user.
 Create two MatRev objects:
 matrix1 to store the original matrix.
 matrix2 to store the reversed matrix.
 Call fillarray for matrix1 and use revMat to populate matrix2.
 Display the reversed matrix using matrix2.show().
Variable Variable Variable Name
Name Name
arr int[][] 2D array to store the elements of the matrix.
m int Stores the number of rows in the matrix.
n int Stores the number of columns in the matrix.
scanner Scanner Used to read input values from the user.
x int Represents the number being reversed in the
reverse method.
Isc Computer project XII 38

reversedNum int Stores the reversed number computed in the


reverse method.
digit int Holds the last digit of the number during
reversal computation in the reverse method.
rows int Stores the number of rows input by the user for
the matrix dimensions.
columns int Stores the number of columns input by the user
for the matrix dimensions.
matrix1 MatRev Object of MatRev class used to hold the original
matrix entered by the user.
matrix2 MatRev Object of MatRev class used to store the matrix
with reversed numbers from matrix1

Code in java-:
import java.util.Scanner;
class MatRev {
private int[][] arr;
private int m;
private int n;
// Parameterized constructor to initialize the data members m and n
MatRev(int mm, int nn) {
m = mm;
n = nn;
arr = new int[m][n];
}

// Function to enter elements in the array


void fillarray() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = scanner.nextInt();
}
}
}

// Function to reverse a number


int reverse(int x) {
int reversedNum = 0;
while (x != 0) {
int digit = x % 10;
reversedNum = reversedNum * 10 + digit;
x /= 10;
Isc Computer project XII 39

}
return reversedNum;
}

// Function to reverse each element of the array of the parameterized object


// and store it in the array of the current object
void revMat(MatRev P) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = reverse(P.arr[i][j]);
}
}
}

// Function to display the array elements in matrix form


void show() {
System.out.println("Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + "\\\\t");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter dimensions of the matrix


System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter number of columns: ");
int columns = scanner.nextInt();

// Create two objects of MatRev class


MatRev matrix1 = new MatRev(rows, columns);
MatRev matrix2 = new MatRev(rows, columns);

// Read elements for matrix1


System.out.println("Enter elements for matrix 1:");
matrix1.fillarray();
// Reverse elements of matrix1 and store in matrix2
matrix2.revMat(matrix1);
matrix2.show();
}}
Isc Computer project XII 40

Output:

A class OctDeci has been defined to convert an octal number to its equivalent
decimal number as.
e.g. oct = 6548 then dec = 6 x 82 + 5x81 + 4x80 = 42810
The details of the class are given below :
Class name: OctDeci
Data members/instance variables
oct : integer to store a octal number
dec : integer to store a decimal number
Member function/methods
OctDeci(int x) : Constructor to assign oct=x and
dec=0.
int deci_oct(int num) : Calculate and return decimal
equivalent of ‘num’.
void display() : Display the original number ‘oct’ and
its decimal equivalent.

Specify the class OctDeci giving details of the constructor and functions int
deci_oct(int) and void display(). Define a main() function to create an object
and call the functions accordingly to enable the task.
Algorithm:-
 Read a decimal number n from the user.
 Initialize an array to store octal digits.
 Perform successive division by 8, storing the remainders in the array.
 Stop when the number becomes 0.
 Print the octal digits from the array in reverse order.
Isc Computer project XII 41

Variable Type Description


Name
n int Stores the decimal number to be converted to
octal.
octalNum int[] Array to store individual octal digits of the number
during conversion.
i int Counter to track the current position in the
octalNum array.
j int Used to iterate through the octalNum array in
reverse order for display.

Code in java-:
import java.util.*;
class OctDeci
{
OctDeci()
{
int oct;
int deci;
}
// Function to convert decimal to octal
static void dec_oct(int n)
{
// array to store octal number
int[] octalNum = new int[100];

// counter for octal number array


int i = 0;
while (n != 0) {
// storing remainder in octal array
octalNum[i] = n % 8;
n = n / 8;
i++;
}
void display()
{
// Printing octal number array in reverse order
for (int j = i - 1; j >= 0; j--)
System.out.print("OCTAL NUMBER IS - " +octalNum[j]);
}
}

// Driver Code
public static void main(String[] args)
{
Isc Computer project XII 42

Scanner sc=new Scanner (System.in);


System.out.println("Enter a number");
int n = sc.nextInt();

// Function Call
decToOctal(n);
}
}Output:

Sum= 1 + x/1!+x3/2!+x5/3!+……..+x2n-1/n!
A class seriessum has been defined to calculate the sum of the above series.
Some of the members of the class are given below:
Class name : seriessum
Data
members
X
N : int
Sum : double
Member
functios
sumseries() : constructor
int
factorial(int calculates and returns the factorial of n( n!)
n) : where n!=1 x 2 x
3 x 4 x….x n.
double term(int p, int Calculates and returns the value of p/q! by
q) : making use of
factorial(int).
void accept() : Inputs the value of member data x,n
void
displaysum() : displays the value of member data sum.
double calculates the sum of the given seriesusing
calsum() : the appropriate
Isc Computer project XII 43

data and other member functions.

Specify the class sumseries giving details of the constructor, int factorial(int),
double term(int,int), void displaysum(). You may assume that other member
functions are written
for you.
Algorithm:-
 Input: Initialize base x and number of terms n for the series.
 Calculate Factorials: Create a method to compute factorial for given integers.
 Compute Series: Loop through even values up to n. For each term:
 Compute x^i (power of x raised to i).
 Divide it by the factorial of (i - 1).
 Add the result to the sum.
 Output: Display the calculated sum of the series.

Variable Type Description


Name
x int Base value used in the series.
n int Number of terms up to which the series is
calculated.
sum double Accumulates the sum of the series.
term double Stores the value of the current term during the
series computation.
fact double Used to store the factorial of a number in the
factorial method.

Code in java-:
import java.util.*;

class SeriesOne

int x,n,sum;

SeriesOne(int xx, int nn)

x=xx;

n=nn;

double factorialt(int m)

{
Isc Computer project XII 44

int fact=1;

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

fact=fact*i;

return fact;

double findpower(int x, int y)

double res;

res= Math.pow(x,y);

return res;

void calculate()

double term=0;

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

term= findpower(x,i) / findfact( i-1);

sum+=term;

void display()

System.out.println("Sum of the series:"+sum);

}
Isc Computer project XII 45

public static void main(String[] args)

SeriesOne so = new SeriesOne(3,4);

so.cal();

so.display();

Output:

Design a class ArmNum to check if a given number is an Armstrong number or


not. [A number is said to be Armstrong if sum of its digits raised to the power
of length of the number is equal to the number] Example : 371 = 33 + 73 + 13
1634 = 14 + 64 + 34 + 44 54748 = 55 + 45 + 75 + 45 + 85 Thus 371, 1634 and
54748 are all examples of Armstrong numbers.
Some of the members of the class are given below:
Class name : ArmNum Data members/instance variables: n : to store the
number l : to store the length of the number
Methods/Member functions:
ArmNum (int nn) : parameterized constructor to initialize 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 32 + 42
(as the length of the
number is 2)
void isArmstrong( ) : checks whether the given number is an Armstrong
Isc Computer project XII 46

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:-
 Read the number from the user.
 Calculate the number of digits (l) in the number.
 Compute the sum of each digit raised to the power l using recursion.
 Compare the computed sum with the original number.
 Print whether the number is an Armstrong number or not.

Variable Type Description


Name
n int Stores the user input number to be
checked.
l int Stores the number of digits in the input
number.

digit int Represents the current digit being


processed in the recursive function.

number int Stores the number entered by the user


in the main method.

Code in java-:
import java.util.Scanner;
class ArmNum {
int n;
int l;
// Parameterized constructor to initialize the data member n
ArmNum(int nn) {
n = nn;
l = String.valueOf(nn).length();
}

// Function to calculate the sum of each digit raised to the power of the length of the number
int sum_pow(int i) {
if (i == 0) {
return 0;
} else {
int digit = i % 10;
return (int) (Math.pow(digit, l) + sum_pow(i / 10));
}
Isc Computer project XII 47

// Function to check whether the given number is an Armstrong number


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


// Create a Scanner object for user input
Scanner scanner = new Scanner([System.in](<http://system.in/>)); // Prompt the user to
enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Create an object of ArmNum class


ArmNum obj = new ArmNum(number);

// Call the isArmstrong method to check if the number is an Armstrong number


obj.isArmstrong();
}
}
Output:-

A class SwapSort has been defined to perform string related operations on a


word input. Some of the members of the class are as follows: Class name :
SwapSort Data members/instance variables: wrd : to store a word len : integer
Isc Computer project XII 48

to store length of the word swapwrd : to store the swapped word sortwrd : to
store the sorted word Member functions/methods: SwapSort( ) : default
constructor to initialize data members
with legal initial values
void readword( ) : to accept a word in UPPER CASE void swapchar( ) : to
interchange/swap the first and last characters of the word in ‘wrd’ and stores
the new word in ‘swapwrd’
void sortword( ) : sorts the characters of the original word in alphabetical
order and stores it in ‘sortwrd’ void display( ) : displays the original word,
swapped word and the sorted word
Specify the class SwapSort, giving the details of the constructor( ), void
readword( ), void swapchar( ), void sortword( ) and void display( ). Define the
main( ) function to create an object and call the functions accordingly to
enable the task.
Algorithm:-
 Declare and initialize variables to store the original word, swapped word, and sorted word.
 Accept a word in uppercase from the user.
 Swap the first and last characters of the input word if its length is greater than 1.
 Store the result in swapwrd.
 Convert the original word into a character array.
 Sort the array alphabetically and store the result in sortwrd.
 Print the original word, swapped word, and sorted word.
Variable Type Description
Name
wrd String Stores the original word entered by the
user.
len int Stores the length of the word.

swapwrd String Stores the word after swapping the first


and last characters.

sortwrd String Stores the word after sorting its


characters alphabetically.

chars char[] Temporary array to store characters of


the word for processing.

Code in java-:
import java.util.Scanner;
class SwapSort {
String wrd;
int len;
String swapwrd;
String sortwrd;
Isc Computer project XII 49

// Default constructor to initialize data members


SwapSort() {
wrd = "";
len = 0;
swapwrd = "";
sortwrd = "";
}

// Function to accept a word in UPPER CASE


void readword() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word in UPPER CASE: ");
wrd = scanner.next();
len = wrd.length();
}

// Function to interchange/swap the first and last characters


// of the word in 'wrd' and store the new word in 'swapwrd'
void swapchar() {
if (len >= 2) {
char[] chars = wrd.toCharArray();
char temp = chars[0];
chars[0] = chars[len - 1];
chars[len - 1] = temp;
swapwrd = new String(chars);
} else {
swapwrd = wrd;
}
}

// Function to sort the characters of the original word


// in alphabetical order and store it in 'sortwrd'
void sortword() {
char[] chars = wrd.toCharArray();
Arrays.sort(chars);
sortwrd = new String(chars);
}

// Function to display the original word, swapped word, and the sorted word
void display() {
System.out.println("Original Word: " + wrd);
System.out.println("Swapped Word: " + swapwrd);
System.out.println("Sorted Word: " + sortwrd);
}
public static void main(String[] args) {
// Create an object
SwapSort obj = new SwapSort();
Isc Computer project XII 50

// Call member functions accordingly


obj.readword();
obj.swapchar();
obj.sortword();
obj.display();
}
}
Output:

A class Capital has been defined to check whether a sentence has words
beginning with a capital letter or not. Some of the members of the class are
given below:
Class name : Capital
Data member/instance variable:
sent : to store a sentence freq : stores the frequency of words beginning with
a capital letter
Member functions/methods:
Capital( ) : default constructor void input( ) : to accept the sentence boolean
isCap(String w) : checks and returns true if word begins with a capital letter,
otherwise returns false void display( ) : displays the sentence along with the
frequency of the words beginning with a capital letter Specify the class Capital,
giving the details of the constructor( ), void input( ), boolean isCap(String) and
void display( ). Define the main( ) function to create an object and call the
functions accordingly to enable the task.
Algorithm:-
 Accept a sentence from the user.
 Break the sentence into words using whitespace as a delimiter.
 For each word, check if the first character is uppercase using the isCap function.
 Increment freq for each word that starts with an uppercase letter.
 Display the input sentence and the count of words starting with a capital letter.
Variable Type Description
Name
Isc Computer project XII 51

sent String Stores the input sentence entered by the


user.
freq int Stores the count of words starting with a
capital letter.

words String[] Array storing the words of the sentence


after splitting.

Code in java-:
import java.util.Scanner;
class Capital {
String sent;
int freq;
// Default constructor
Capital() {
sent = "";
freq = 0;
}

// Function to accept the sentence


void input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
sent = scanner.nextLine();
}

// Function to check if a word begins with a capital letter


boolean isCap(String w) {
if (w.length() > 0) {
return Character.isUpperCase(w.charAt(0));
}
return false;
}

// Function to display the sentence along with the frequency


// of the words beginning with a capital letter
void display() {
String[] words = sent.split("\\\\\\\\s+");
freq = 0;
for (String word : words) {
if (isCap(word)) {
freq++;
}
}
System.out.println("Sentence: " + sent);
Isc Computer project XII 52

System.out.println("Frequency of words beginning with a capital letter: " + freq);


}
public static void main(String[] args)
{
// Create an object of Capital class
Capital obj = new Capital();
// Call input method to accept the sentence
obj.input();
// Call display method to display the sentence and frequency
obj.display();
}}
Output:

A class Merger concatenates two positive integers that are greater than 0 and
produces a newly merged integer. Example: If the first number is 23 and the
second is 764, then the concatenated number will be 23764. Some of the
members of the class are given below:
Class name: Merger
Data members/instance variables: n1: long integer to store the first number
n2: long integer to store the second number mergNum: long integer to store
the merged number.
Member functions: Merger(): constructor to initialize the data members void
readNum(): to accept the values of the data members n1 and n2
voidjoinNum(): to concatenate the numbers n1 and n2 and store it in
mergNum void show(): to display the original numbers and the merged
number with appropriate messages Specify the class Merger giving the details
of the constructor, void readNum(), void joinNum() and void show().
Define the main() function to create an object and call the functions
accordingly to enable the task.
Algorithm:-
 Create a class Merger with three data members: n1, n2, and mergNum.
 Define a constructor to initialize these variables to zero.
 Create a method readNum that accepts two numbers as input and assigns them to n1 and n2.
Isc Computer project XII 53

 Create a method joinNum that:


 Converts n1 and n2 into strings.
 Concatenates these strings.
 Parses the concatenated string back into a long and stores it in mergNum.
 Create a method show to print:
 The original numbers (n1 and n2).
 The concatenated number (mergNum).
 Create an object of the Merger class.
 Read two numbers from the user.
 Call the readNum, joinNum, and show methods in sequence to execute the program.
Name Data Purpose
Type
n1 long Stores the first input number.

n2 long Stores the second input number.

mergNum long Stores the concatenated result of


n1 and n2.

strNum1 String Temporary variable to hold the


string representation of n1 during
concatenation.
strNum2 String Temporary variable to hold the
string representation of n2 during
concatenation.
mergedString String Temporary variable to hold the
concatenated string of strNum1 and
strNum2.
scanner Scanner Used to take user input in the main
method.

Code in java-:
public class Merger {
long n1;
long n2;
long mergNum;
// Constructor to initialize the data members
public Merger() {
n1 = 0;
n2 = 0;
mergNum = 0;
}

// Method to accept the values of the data members n1 and n2


public void readNum(long num1, long num2) {
n1 = num1;
Isc Computer project XII 54

n2 = num2;
}

// Method to concatenate the numbers n1 and n2 and store it in mergNum


public void joinNum() {
String strNum1 = Long.toString(n1);
String strNum2 = Long.toString(n2);
String mergedString = strNum1 + strNum2;
mergNum = Long.parseLong(mergedString);
}

// Method to display the original numbers and the merged number with appropriate messages
public void show() {
System.out.println("Original numbers: " + n1 + " and " + n2);
System.out.println("Merged number: " + mergNum);
}

public static void main(String[] args) {


// Example usage
long num1 = 23;
long num2 = 764;

Merger mergerObj = new Merger();


mergerObj.readNum(num1, num2);
mergerObj.joinNum();
mergerObj.show();
}}
Output:

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 members/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): parameterized constructor to assign str=ds
void countFreq(): to count the number of words and the number of
consonants and store them in wordCount and cons respectively void display():
Isc Computer project XII 55

to display the original string, along with the number of words and the number
of consonants Specify the class TheString giving the details of the constructors,
void countFreq() and void display(). Define the main() function to create an
object and call the functions accordingly to enable the task.
Algorithm:-
 Define a class TheString with three data members: str, len, wordCount, and cons.
 Provide two constructors:
 Default constructor to initialize all variables to default values.
 Parameterized constructor to initialize str and calculate its length (len).
 Define a method countFreq to:
 Split the string into words using space as the delimiter and count the words.
 Iterate through each character in the string:
 Check if the character is a letter and not a vowel using the isVowel helper method.
 Increment the consonant count (cons) for each consonant.
 isVowel: Checks if a given character is a vowel (a, e, i, o, u, case-insensitive).
 Define a method display to print:
 The original string (str).
 The number of words (wordCount).
 The number of consonants (cons).
 Create an object of the TheString class using the parameterized constructor.
 Call the countFreq and display methods to calculate and print the results.

Variable Data Purpose


Name Type
str String Stores the input string.

len int Stores the length of the input string.

wordCount int Stores the number of words in the


input string.

cons int Stores the number of consonants in the


input string.
words String[] Array of words obtained by splitting
the input string.
ch char Temporary variable to hold each
character of the string during iteration.
inputString String Example input string provided in the
main method for demonstration.

Code in java-:
public class TheString
{
String str;
int len;
int wordCount;
int cons;
// Default constructor
Isc Computer project XII 56

public TheString() {
str = "";
len = 0;
wordCount = 0;
cons = 0;
}

// Parameterized constructor
public TheString(String ds) {
str = ds;
len = str.length();
wordCount = 0;
cons = 0;
}
// Method to count the number of words and consonants
public void countFreq() {
// Reset counts
wordCount = 0;
cons = 0;

// Split the string into words by space


String[] words = str.split(" ");

// Count words
wordCount = words.length;

// Count consonants
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch) && !isVowel(ch)) {
cons++;
}
}
}

// Helper method to check if a character is a vowel


private boolean isVowel(char ch) {
ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

// Method to display the original string, number of words, and number of consonants
public void display() {
System.out.println("Original String: " + str);
System.out.println("Number of Words: " + wordCount);
System.out.println("Number of Consonants: " + cons);
}
Isc Computer project XII 57

public static void main(String[] args) {


// Example usage
String inputString = "Hello world! This is a test.";
TheString strObj = new TheString(inputString);
strObj.countFreq();
strObj.display();
}
}
Output:

A class Telcall calculates the monthly telephone bill of a consumer. Some of


the members of the class are given below:

Class Name : Telcall


Data Members
Phno : phone number
Name : name of consumer
N : number of calls made
Amt : bill amount

Memberfunctions
Parameterised constructor to assign
Telcall( ) : values to data
Members
to calculate the phone bill amount based
void compute() : on the slabs given
below.
to display the details in the specified
void dispdata() : format.
Isc Computer project XII 58

Number of calls Rate


1-100 Rs. 500/- rental charge only

101-200 Re. 1.00/- per call + rental charge

201-300 Rs.1.20/- per call + rental charge

Above 300 Rs.1.50/- per call + rental charge

The calculation needs to be done as per the slabs.

Specify the class Telcall, giving the details of the constructor, void compute()
and void dispdata().

In the main function, create an object of type Telcall and display the phone
bill in the following

format:

Phone
number Name Total calls Amount

XXXXXXX
XX XXXXX XXXXX XXXXX

Algorithm:-
 Prompt the user to enter the phone number (s1), name (s2), and the total number of calls (x).
 Read and store the inputs.
 Create an object ob of the Telcall class, passing s1, s2, and x to the constructor.
 Define the method compute:
 If calls are between 1-100, set Amt = 500.
 If calls are between 101-200, set Amt = 500 + (calls above 100) * 1.
 If calls are between 201-300, set Amt = 500 + (calls above 100) * 1.2.
 If calls exceed 300, set Amt = 500 + (calls above 100) * 1.5.
 Define the method dispdata:
 Print the phone number, name, total calls, and calculated amount in a formatted table.
 Execute Program:
 Call the compute method to calculate the bill amount.
 Call the dispdata method to display the customer data.

Variable Data Description


Name Type
Name String Stores the name of the customer.
Isc Computer project XII 59

N int Stores the total number of calls made by the


customer.
Phno int Stores the phone number of the customer.
Amt double Stores the calculated bill amount based on the
number of calls.
s1 int Temporary variable to store the phone number
input from the user.
s2 String Temporary variable to store the name input from
the user.
x int Temporary variable to store the number of calls
input from the user.
ob Telcall Object of the Telcall class used to invoke methods
and manage customer data.
sc Scanner Object of the Scanner class used to read input from
the user

Code in java-:
import java.util.*;
class Telcall {
String Name;
int N, Phno;
double Amt;

Telcall(int s1, String s2, int x) {


Phno = s1;
Name = s2;
N = x;
Amt = 0;
}

void compute() {
if (N >= 1 && N <= 100)
Amt = 500;
else if (N >= 101 && N <= 200)
Amt = 500 + ((N - 100) * 1);
else if (N >= 201 && N <= 300)
Amt = 500 + ((N - 100) * 1.2);
else if (N > 300)
Amt = 500 + ((N - 100) * 1.5);
}

void dispdata() {
System.out.printf("%-15s %-15s %-15s %-10s%n", "Phone No.", "Name", "Total
Calls", "Amount");
System.out.printf("%-15d %-15s %-15d %.2f%n", Phno, Name, N, Amt);
}
}
Isc Computer project XII 60

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Phone Number:");
int s1 = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.println("Enter Name:");
String s2 = sc.nextLine();
System.out.println("Enter No. of calls:");
int x = sc.nextInt();

Telcall ob = new Telcall(s1, s2, x);


ob.compute();
ob.dispdata();
sc.close();
} }
Output:

The co-ordinates of a point P on a two-dimensional plane can be represented


by P(x,y) with x as the x co-ordinate and y as the y co-ordinate. The co-
ordinates of midpoint of two points P1(x1,y1) and P2(x2,y2) can be calculated
as P(x,y) where:x=x1+x2/2, y=y1+y2/2

Design a class Point with the following details:

Class name : Point

Data members

X : stores the x co-ordinate

Y : stores the y co-ordinate

Memberfunctio
Isc Computer project XII 61

Point() : constructor to initialize x=0 and y=0

void readPoint() : accepts the co-ordinates x and y of a point

Point midpoint(Point A, calculates and returns the midpoint of the


Point B): two points A and B.

void
displaypoint() : displays the co-ordinates of a point

Specify the class Point giving details of the constructor( ), member functions
void readPoint(), Point midpoint(Point, Point) and void displaypoint() along
with the main function to create an object and call the functions accordingly
to calculate the midpoint between any two given points.

Algorithm:-
 Define the Point class:
 Attributes: x (double), y (double)
 Methods:
 readPoint(): Reads x and y coordinates from the user.
 displayPoint(): Prints the point's coordinates.
 midpoint(Point A, Point B): Computes the midpoint between two points A and B.
 Create three Point objects: p, q, and r.
 Call p.readPoint() to read coordinates for point p.
 Call q.readPoint() to read coordinates for point q.
 Compute the midpoint r using r = Point.midpoint(p, q).
 Call p.displayPoint() to print point p.
 Call q.displayPoint() to print point q.
 Call r.displayPoint() to print point r (the midpoint of p and q).
 Inside midpoint method:
 Compute C.x = (A.x + B.x) / 2
 Compute C.y = (A.y + B.y) / 2
 Return C (new point representing the midpoint).

Variable Type Description


x double Stores the x-coordinate of a point.

y double Stores the y-coordinate of a point.

sc Scanner A Scanner object for reading user input.

p Point Represents the first point.

q Point Represents the second point.


Isc Computer project XII 62

r Point Represents the midpoint of points p and


q.
A Point First parameter to the midpoint method
(represents Point 1).
B Point Second parameter to the midpoint
method (represents Point 2).
C Point Stores the computed midpoint in the
midpoint method.

Code in java-:
import java.util.Scanner;
public class Point
{
double x,y;
Scanner sc = new Scanner(System.in);
public Point() {
x=0.0;
y=0.0;
}
public void readpoint()
{
System.out.println("enter x");
x=sc.nextDouble();
System.out.println("enter y");
y=sc.nextDouble();
}
public void displaypoint()
{
System.out.println(x);
System.out.println(y);
}
public Point midpoint(Point A,Point B)
{
Point C=new Point();
C.x=(A.x+B.x)/2;
C.y =(A.y+B.y)/2;
return C;
}
public static void main()
{
Point p=new Point();
Point q=new Point();
Point r=new Point();
p.readpoint();
q.readpoint();
r=r.midpoint(p,q);
Isc Computer project XII 63

p.displaypoint();
q.displaypoint();
r.displaypoint();
}
}
Output:

A superclass Record contains names and marks of the students in two


different single dimensional arrays. Define a subclass Highest to display the
names of the students obtaining the highest mark
The details of the members of both classes are given below:
Class name: Record

Data member/instance variable:


n[] : array to store names
m[]: array to store marks
size: to store the number of students
Member functions/methods:
Record(int cap): parameterized constructor to initialize the data member
size = cap
void readarray() : to enter elements in both the arrays
void display() : displays the array elements
Class name: Highest
Data member/instance variable:
ind: to store the index
Member functions/methods:
Highest(…): parameterized constructor to initialize the data members of
both the classes
void find(): finds the index of the student obtaining the highest mark and
Isc Computer project XII 64

assign it to ‘ind’
void display(): displays the array elements along with the names and marks
of the students who have obtained the highest mark
Assume that the superclass Record has been defined. Using the concept of
inheritance, specify the class Highest giving the details of the
constructor(…), void find() and void display().
Algorithm:-
 n[]: Array to store student names.
 m[]: Array to store student marks.
 size: Integer to store the number of students.
 readarray(): Reads names and marks for the students from the user.
 display(): Displays the names and marks of all students.
 ind: Stores the index of the student with the highest mark.
 find(): Finds the student with the highest mark by comparing each student's marks and updating the ind
value.
 display(): Calls the display() method from Record to print all student data and then prints the
student with the highest mark.
 Create an instance of the Highest class with a specified capacity (number of students).
 Call readarray() to read the names and marks of the students.
 Call find() to find the student with the highest mark.


Call display() to show the list of students and the student with the highest marks.
Variable Type Description
n String[] Array to store the names of students.

m int[] Array to store the marks of students.

size int Stores the number of students (capacity of the


arrays n and m).

ind int Stores the index of the student with the highest
mark.
sc Scanner A Scanner object to read input from the user.
p Highest Represents an instance of the Highest class.
cap int Represents the capacity (number of students)
passed to the Highest constructor.
maxMark int Used to store the highest mark during the find()
method.
A Record Reference to an object of the Record class
(superclass of Highest).

Code in java-:
class Highest extends Record
{
private int ind; // to store the index of student with highest mark
// Parameterized constructor
public Highest(int cap) {
Isc Computer project XII 65

super(cap); // Call superclass constructor


ind = 0; // Initialize ind to 0
}
// Method to find the index of student with highest mark
public void find()
{
int maxMark = m[0]; // Assume first student has highest mark
for (int i = 1; i < size; i++) {
if (m[i] > maxMark) {
maxMark = m[i];
ind = i;
}
}
}
// Method to display array elements and highest scorer
public void display() {
super.display(); // Display all students' data
System.out.println("\nStudent with Highest Mark:");
System.out.println("Name: " + n[ind]);
System.out.println("Mark: " + m[ind]);
}
public static void main(String[] args) {
Highest h = new Highest(5); // Create object with capacity 5
h.readarray(); // Read student data
h.find(); // Find highest scorer
h.display(); // Display results
}}
Output:-
Isc Computer project XII 66

A super class EmpSal has been defined to store the details of an employee.
Define a subclass Overtime to compute the total salary of the employee, after
adding the overtime amount based on following criteria:
1. if hours are more than 40, then Rs.5000 are added to salary as an overtime
amount.
2. if hours are between 30 and 40 (both inclusive), then Rs.3000 are addedd to
salary as an overtime amount.
3. if hours are less than 30, then salary remain unchanged.
The details of the members of both the classes are given below
Class Name -EmpSal
Data members/instance variables:
Empnum - to store the name of employee salary
Empcode - integer to store the employee code
Salary - to store the salary of the eployee in decimal
Methods/member functions:
EmpSal(….) : parameterised constructor to assign values to data members.
void show() : to display the details of employee
Class name : Overtime
Data members/instance variables.:
hours : integer to store overtime in hours
totsal : to store total salary in decimal
Methods/Member functions:
Overtime(…) : parameterised constructor to assign values to data members
of both the classes.
void calSal() : calculates the total salary by adding the overtime amount to
salary as per criteria given above.
void show() : to display the employee details along with the total
salary(salary + overtime amount)
Assume that the the super class EmpSal has been defined. Using the concept
of inheritance. Specify the class Overtime giving the details of the
constructor(…), void calSal() and void show()
Algorithm:-
 hours: Stores the number of overtime hours worked by the employee.
 totsal: Stores the total salary after considering overtime.
 The parameterized constructor initializes the Overtime object by calling the superclass (EmpSal)
constructor with employee details (empnu, empcod, and salar), then it initializes hours with the
overtime hours and sets totsal to the base salary initially.
Isc Computer project XII 67

 calSal(): Calculates the total salary by adding an overtime amount based on the number of overtime
hours worked:
 If overtime hours are more than 40, Rs. 5000 is added to the base salary.
 If overtime hours are between 30 and 40, Rs. 3000 is added.
 If overtime hours are fewer than 30, the salary remains unchanged.
 show(): Displays the employee's details, including the overtime hours and total salary.
 Creates an Overtime object with employee details and overtime hours.
 Calls calSal() to calculate the total salary.
 Displays the employee's details by calling the show() method.
Variable Type Description
empno String Employee number (identifier).

empcode int Employee unique code.

salary double Base salary of the employee.

hours int Number of overtime hours worked by the


employee.
totsal double Total salary, including overtime, of the employee.

emp Overtime Object of the Overtime class used to store


employee details.
sc Scanner A Scanner object (not explicitly used in this
version but can be used for user input).

Code in java-:
// Subclass Overtime extends the superclass EmpSal
class Overtime extends EmpSal
{
// Data members of the subclass Overtime
int hours; // To store overtime in hours
double totsal; // To store the total salary
// Parameterized constructor to assign values to both classes' data members
Overtime(String empnu, int empcod, double salar, int hour)
{
super(empnu, empcod, salar); // Calling the constructor of the superclass
hours = hour;
totsal = salary; // Initializing totsal with the base salary
}
// Method to calculate total salary by adding the overtime amount
void calSal()
{
if (hours > 40)
{
totsal = salary + 5000; // Rs. 5000 added for hours > 40
}
else if (hours >= 30 && hours <= 40)
{
Isc Computer project XII 68

totsal = salary + 3000; // Rs. 3000 added for hours between 30 and 40 (inclusive)
}
else {
totsal = salary; // No change if hours < 30
}
}
void show()
{
super.show(); // Calling the show method of the superclass to display base details
System.out.println("Overtime Hours: " + hours);
System.out.println("Total Salary (including overtime): " + totsal);
}
// Example of how the classes can be used
public static void main(String[] args) {
// Creating an object of the Overtime class
Overtime emp = new Overtime("John Doe", 101, 30000, 45);
// Calculating the total salary with overtime
emp.calSal();

// Displaying the employee details


emp.show();
}}

Output:-
Isc Computer project XII 69

A superclass Record contains names and marks of the students in two


different single dimensional arrays. Define a subclass Highest to display the
names of the students obtaining the highest mark
The details of the members of both classes are given below:
Class name: Record
Data member/instance variable:
n[] : array to store names
m[]: array to store marks
size: to store the number of students
Member functions/methods:
Record(int cap): parameterized constructor to initialize the data member
size = cap
void readarray() : to enter elements in both the arrays
void display() : displays the array elements
Class name: Highest
Data member/instance variable:
ind: to store the index
Member functions/methods:
Highest(…): parameterized constructor to initialize the data members of both
the classes
void find(): finds the index of the student obtaining the highest mark and
assign it to ‘ind’
void display(): displays the array elements along with the names and marks of
the students who have obtained the highest mark
Assume that the superclass Record has been defined. Using the concept of
inheritance, specify the class Highest giving the details of the constructor(…),
void find() and void display().
Algorithm:-
 Define arrays for student names and marks.
 Implement methods to read and display data.
 Extend the Record class in the Highest class:
 Add an attribute ind to store the index of the student with the highest marks.
 Implement the find() method to calculate the index of the highest scorer.
 In the main() Method:
 Create an object of Highest with a specific capacity.
 Call readarray() to input student data.
 Call find() to calculate the index of the highest scorer.
 Call display() to show all student records and the highest scorer's details.

 End.
Isc Computer project XII 70

Variable Type Description


n String[] Array to store the names of students.

m int[] Array to store the marks of students.

size int Total number of students (capacity of arrays n and


m).
ind int Index of the student with the highest mark.

maxMark int Variable to track the highest mark during the


search.
h Highest Object of the Highest class used to store student
data.

Code in java-:
class Highest extends Record
{
private int ind; // to store the index of student with highest mark
// Parameterized constructor
public Highest(int cap) {
super(cap); // Call superclass constructor
ind = 0; // Initialize ind to 0
}
// Method to find the index of student with highest mark
public void find()
{
int maxMark = m[0]; // Assume first student has highest mark
for (int i = 1; i < size; i++) {
if (m[i] > maxMark) {
maxMark = m[i];
ind = i;
}
}
}
// Method to display array elements and highest scorer
public void display() {
super.display(); // Display all students' data
System.out.println("\nStudent with Highest Mark:");
System.out.println("Name: " + n[ind]);
System.out.println("Mark: " + m[ind]);
}
public static void main(String[] args) {
Highest h = new Highest(5); // Create object with capacity 5
h.readarray(); // Read student data
h.find(); // Find highest scorer
h.display(); // Display results
}
Isc Computer project XII 71

A class Employee contains employee details and another class Salary calculates the
employee’s net salary. The details of the two classes are given below:
Class name : Employee
Data members
empNo : stores the employee number.
empName : stores the employee name
empDesig : stores the employee’s designation.

Member functions:

Employee() : default constructor.


parameterized constructor to assign values
Employee(…) : to data
members.
void display() : display the employee details.

Class name : Salary


Data members
Basic : float variable to store the basic pay.
Member functions
parameterized constructor to assign values
Salary(…) : to data
members.
void calculate() : calculates the employee’s net salary according to the
following rules:
DA = 10% of basic
HRA = 15% of basic
Salary = basic + DA +H RA
PF= 8 % of Salary
Net Salary = Salary –PF
Display the employee details and the Net salary.
Assume that the class Employee has been defined . Using the concept of inheritance
specify the class Salary giving details of the constructor and the member
function void calculate(). The main function need not be
written. [ 5]
Algorithm:-
 Start.
 Create the Employee class:
 Define attributes: empno, empname, and empdesig.
 Implement:
 Default constructor to initialize default values.
 Parameterized constructor to initialize attributes with input values.
 display() method to print employee details.
Isc Computer project XII 72

 Create the Salary class as a subclass of Employee:


 Define an additional attribute: basic.
 Implement:
 Parameterized constructor to call the Employee constructor and initialize basic.
 calculate() method to compute:
 DA = 10% of basic.
 HRA = 15% of basic.
 Gross = basic + DA + HRA.
 PF = 8% of gross.
 Net Pay = Gross - PF.
 Display all details, including payment breakdown.
 In the main() method:
 Take user input for employee details (empname, empno, empdesig, and basic).
 Create a Salary object using the input values.
 Call the calculate() method.
 Display the employee's details and salary breakdown.
 End
Variable Type Description
empno int Stores the employee number.

empname String Stores the employee name.

empdesig String Stores the employee designation.

basic float Stores the basic salary of the employee.

da double Stores the Dearness Allowance (10% of basic salary).

hra double Stores the House Rent Allowance (15% of basic salary).

gross double Stores the gross pay (sum of basic, DA, and HRA).
pf double Stores the Provident Fund (8% of gross pay).
netpay double Stores the net pay (gross pay minus PF).
sc Scanner Used to take user input for employee details and salary.

call Salary Object of the Salary class used to calculate salary data.

Code in java-:
import java.util.*;
class Employee
{
int empno;String empname,empdesig;
Employee()
{
empno=9763;
empname=null;
empdesig=null;
Isc Computer project XII 73

}
Employee(int a,String b,String c)
{
empno=a;
empname=b;
empdesig=c;
}
void display()
{
System.out.println("Employee name:"+empname);
System.out.println("Employee number:"+empno);
System.out.println("Employee designation:"+empdesig);
}
}
class Salary extends Employee
{
float basic;
Salary(float b,int n,String name,String d)
{
super(n,name,d);
basic=b;
}
void calculate()
{
double da=0.1*basic,hra=0.15*basic,gross=basic+da+hra,pf=0.08*gross,netpay=gross-pf;
System.out.println("\nEmployee Details");
System.out.println("----------------");
super.display();
System.out.println("\nPayment Details");
System.out.println("----------------");
System.out.println("Basic="+basic+"\nDA="+da+"\nHRA="+hra+"\nGross
Pay="+gross+"\nNet Pay="+netpay);
}
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter employee name:");
String name=sc.nextLine ();
System.out.print("Enter employee number:");
int n=sc.nextInt();
System.out.print("Enter employee designation:");
String d=sc.next();
System.out.print("Enter basic pay:");
float b=sc.nextFloat ();
Salary call=new Salary(b,n,name,d);
call.calculate();
Isc Computer project XII 74

}
Output:

Design a program using inheritance to calculate and display the total marks of a
student and determine whether the student passed or failed.
Requirements:
Class: Student (Superclass):
Data members: name (String), roll (int).
Methods:
Constructor to initialize name and roll.
display() to print student details.
Class: Result (Subclass):
Data members: marks (int array of 3 subjects).
Methods:
Constructor to initialize marks.
calculate() to compute the total marks and determine pass/fail (passing marks are 33 in
each subject).
Override display() to print student details along with marks, total, and result.
Passing Criteria:
A student passes if they score 33 or more marks in all three subjects.
Algorithm:-
 Start.
 Create the Student class:
 Define attributes name and roll.
 Implement:
 Constructor to initialize attributes.
 display() to print student details.
 Create the Result class:
 Define additional attributes marks[], total, and result.
 Implement:
 Constructor to initialize attributes and call Student constructor.
 calculate() to compute total marks and check passing criteria.
 Override display() to include marks, total, and result.
 In the main() method:
 Take user input for student details (name, roll, marks).
 Create an object of the Result class.
Isc Computer project XII 75

 Call calculate() to compute results.


 Call display() to print all details.
 End.

Variable Type Description


name String Stores the name of the student.

roll int Stores the roll number of the student.

marks int[] Array to store marks in 3 subjects.

total int Stores the total marks of the student.

result String Stores "Pass" or "Fail" based on the student's result.


sc Scanner Used for input operations in the main method.

Code in java-:
import java.util.Scanner;

// Superclass: Student
class Student {
protected String name; // Student's name
protected int roll; // Student's roll number

// Constructor to initialize name and roll number


public Student(String name, int roll) {
this.name = name;
this.roll = roll;
}

// Method to display student details


public void display() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + roll);
}
}

// Subclass: Result
class Result extends Student {
private int[] marks; // Array to store marks in 3 subjects
private int total; // Total marks
private String result; // Result: Pass/Fail

// Constructor to initialize student details and marks


public Result(String name, int roll, int[] marks) {
super(name, roll); // Call superclass constructor
this.marks = marks;
Isc Computer project XII 76

// Method to calculate total marks and determine pass/fail


public void calculate() {
total = 0;
boolean pass = true;
for (int mark : marks) {
total += mark;
if (mark < 33) { // Check if any subject mark is less than 33
pass = false;
}
}
result = pass ? "Pass" : "Fail"; // Set result based on pass criteria
}

// Override display method to include marks, total, and result


@Override
public void display() {
super.display(); // Call the superclass display method
System.out.println("Marks in 3 Subjects: ");
for (int i = 0; i < marks.length; i++) {
System.out.println("Subject " + (i + 1) + ": " + marks[i]);
}
System.out.println("Total Marks: " + total);
System.out.println("Result: " + result);
}

// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input student details


System.out.print("Enter Student Name: ");
String name = sc.nextLine();
System.out.print("Enter Roll Number: ");
int roll = sc.nextInt();

// Input marks for 3 subjects


int[] marks = new int[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter marks for Subject " + (i + 1) + ": ");
marks[i] = sc.nextInt();
}

// Create Result object and process data


Result student = new Result(name, roll, marks);
student.calculate(); // Calculate total and result
Isc Computer project XII 77

student.display(); // Display student details and result


}
}

Output:-

Implement array as a circular queue.

Algorithm-:
1. START
2. store int st[],size,top
3. store
4. st=null;
5. size=0;
6. top=-1;in stack()
7. store size=s;
8. st=new int[size];
9. top=-1;in stack(int s)
10. take void push(int val)
11. check if(top==size-1)
12. if step 6 is true print queue is full
13. if step 6 is not true store st[++top]=val
14. take void pop()
15. check if(top==-1)
16. if step 10 is true print Empty queue
17. if step 10 is not true print st[top]+"is deleted"
18. store st[top]=0;
19. st[top--]=0;
20. top--;
Isc Computer project XII 78

21. take void display()


22. check if( top!=-1)
23. take a loop for(int i=top;i>=0;i--)
24. print st[i]
25. END
Code in java-:
class cirqueue
{
int que[],size,front,rear;
cirqueue()
{
que=null;
size=0;
front=-1;
rear=-1;
}
cirqueue(int s)
{
size=s;
que=new int[size];
front=-1;
rear=-1;
}
void insert(int val)
{
if((rear+1)%size==front)
System.out.println("queue is full");
else
{
rear=(rear+1)%size;
que[rear]=val;
if(front==-1)
front=0;
}
}
void delete()
{
if(front==-1)
System.out.println("Queue is empty");
else
{
System.out.println(que[front]+"is deleted");
que[front]=0;
if(front==rear)front=rear=-1;
else front=(front+1)%rear;
}
}
void display()
{
if (front!=-1)
{
int i=front;
while(i!=rear)
{
System.out.println(que[i]);
i=(i+1)%size;
}
System.out.println(que[i]);
}
Isc Computer project XII 79

else
System.out.println("Empty Queue");
}
} Output:

Implement stack as an array

Class sumsuingclass

DATA MEMBERS:

St[],size,top(integers)
MEMBER METHODS:
sumsuingclass (): non-parameterize constructor
sumsuingclass (int s): parameterize constructor
Void push(int val):to insert value
Void pop():to delete value
Void display():to display value
Isc Computer project XII 80

Algorithm:-
 START
 store int st[],size,top
 store
 st=null;
 size=0;
 top=-1;in stack()
 store size=s;
 st=new int[size];
 top=-1;in stack(int s)
 take void push(int val)
 check if(top==size-1)
 if step 6 is true print Stack is full
 if step 6 is not true store st[++top]=val
 take void pop()
 check if(top==-1)
 if step 10 is true print Empty stack
 if step 10 is not true print st[top]+"is deleted"
 store st[top]=0;
 st[top--]=0;
 top--;
 take void display()
 check if( top!=-1)
 take a loop for(int i=top;i>=0;i--)
 print st[i]
 END
Variable Data Description
Name Type
st int[] Array to store the elements of the stack.

size int The maximum capacity of the stack.

top int Index pointing to the top element of the stack.

val int Temporary variable used in push() method to hold a


value to be added to the stack.
i int Loop variable used in display() method to iterate
through stack elements.

Code in java-:
class sumsuingclass
{
int st[],size,top;
sumsuingclass ()
{
st=null;
size=0;
top=-1;
Isc Computer project XII 81

}
sumsuingclass (int s)
{
size=s;
st=new int[size];
top=-1;
}
void push(int val)
{
if(top==size-1)
{
System.out.println("Stack is full");
}
else
{
st[++top]=val;
}
}
void pop()
{
if(top==-1)
System.out.println("Empty stack");
else
{
System.out.println(st[top]+"is deleted");
{
st[top]=0;
st[top--]=0;
top--;
}
}
}
void display()
{
if(top!=-1)
{
for(int i=top;i>=0;i--)
System.out.println(st[i]);
}
}
}

Output:
Isc Computer project XII 82

Implement a queue as an array


DATA MEMBERS:
St[],size,top(integers)
MEMBER METHODS:
queue (): non-parameterize constructor
queue (int s): parameterize constructor
Void push(int val):to insert value
Void pop():to delete value
Void display():to display value
Code in java-:
 START
 store int st[],size,top
 store
 st=null;
 size=0;
 top=-1;in stack()
 store size=s;
 st=new int[size];
 top=-1;in stack(int s)
 take void push(int val)
 check if(top==size-1)
 if step 6 is true print queue is full
 if step 6 is not true store st[++top]=val
 take void pop()
Isc Computer project XII 83

 check if(top==-1)
 if step 10 is true print Empty queue
 if step 10 is not true print st[top]+"is deleted"
 store st[top]=0;
 st[top--]=0;
 top--;
 take void display()
 check if( top!=-1)
 take a loop for(int i=top;i>=0;i--)
 print st[i]
 END
Variable Data Description
Name Type
que int[] Array to store the elements of the queue.

size int The maximum capacity of the queue.

front int Index pointing to the front element of the queue.

rear int Index pointing to the last element of the queue.

val int Temporary variable used in push() and pop() methods to


hold a value.
q Queue Object of the Queue class, used in the main() method to
demonstrate the program.
args String[] Array of command-line arguments, part of the main()
method signature.

Code in java-:
class Queue
{int que[],size,front,rear;
Queue()
{que=null;
size=0;
front=-1;
rear=-1;
}Queue(int s)
{ size=s;
que=new int[size];
front=-1;
rear=-1;
}void push(int val)
{rear=size-1;
if(isFull())
System.out.println("Queue is full");
else
{if(front==-1)
front=0;
que[++rear]=val;
Isc Computer project XII 84

}
}
int pop()
{
int val=-100;
if(isEmpty())
System.out.println("Queue is empty");
else
{
val=que[front];
que[front]=0;
if(front==rear)
front=rear=-1;
else
front++;
}
return val;
}
void display()
{
if(isEmpty())
{for(int i=front;i<=rear;i++)
{System.out.println(que[i]);
}}
else
System.out.println("Empty Queue");
}boolean isFull()
{if(rear==size-1)
return true;
else
return false;
}
boolean isEmpty()
{ if(front==-1)
return true;
else
return false;
}}
Output:
Isc Computer project XII 85

Write a Java program to implement a stack to perform the following


operations:

1. Push: Add an element to the stack.


2. Pop: Remove and display the top element from the stack.
3. Display: Display all elements in the stack.

Use an array to implement the stack. Handle cases such as stack overflow
and stack underflow.

Algorithm:-
 Start.
 Create a Stack class:
 Define attributes: stack[], top, and size.
 Implement methods:
 push(element): Add an element to the stack or handle overflow.
 pop(): Remove and display the top element or handle underflow.
 display(): Print all elements in the stack.
 In the main() method:
 Accept the stack size from the user.
 Use a while loop to display a menu for stack operations.
 Perform the operation based on the user's choice.
 Handle invalid inputs gracefully.
 Exit when the user selects the exit option.
 End.

Variable Type Description


Isc Computer project XII 86

stack int[] Array to store stack elements.

top int Index of the top element in the stack.

size int Maximum size of the stack.

element int Stores the value to be pushed onto the


stack.
choice int Stores the user's menu choice for stack
operations.
sc Scanner Object for input from the user.

Code in java:
import java.util.Scanner;

class Stack {
private int[] stack; // Array to store stack elements
private int top; // Pointer to the top of the stack
private int size; // Maximum size of the stack

// Constructor to initialize the stack


public Stack(int size) {
this.size = size;
stack = new int[size];
top = -1; // Stack is initially empty
}

// Method to push an element onto the stack


public void push(int element) {
if (top == size - 1) { // Check for stack overflow
System.out.println("Stack Overflow! Cannot push " + element);
} else {
stack[++top] = element; // Increment top and insert the element
System.out.println(element + " pushed onto the stack.");
}
}

// Method to pop an element from the stack


public void pop() {
if (top == -1) { // Check for stack underflow
System.out.println("Stack Underflow! No element to pop.");
} else {
System.out.println(stack[top] + " popped from the stack.");
top--; // Decrement top
}
}

// Method to display all elements in the stack


Isc Computer project XII 87

public void display() {


if (top == -1) { // Check if stack is empty
System.out.println("Stack is empty.");
} else {
System.out.println("Stack elements:");
for (int i = top; i >= 0; i--) {
System.out.println(stack[i]);
}
}
}

// Main method to test the stack implementation


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

System.out.print("Enter the size of the stack: ");


int size = sc.nextInt();
Stack stack = new Stack(size);

while (true) {
// Menu options
System.out.println("\nMenu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter element to push: ");
int element = sc.nextInt();
stack.push(element);
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
case 4:
System.out.println("Exiting program.");
System.exit(0);
default:
System.out.println("Invalid choice! Please try again.");
}
Isc Computer project XII 88

}
}
}

Write a Java program to implement a singly linked list with the following
operations:

1. Insert: Add a new node at the end of the list.


2. Delete: Remove the first node from the list.
3. Display: Print all the elements in the list.

Algorithm:-
 Start.
 Define a Node class with attributes data and next.
 Define a SinglyLinkedList class with:
 head to reference the first node.
 insert(int data) to add a new node at the end.
 delete() to remove the first node.
 display() to print all elements.
 In the main() method:
 Create an instance of SinglyLinkedList.
 Use a menu-driven approach to call the methods based on user input.
 Handle invalid inputs gracefully.
 Exit when the user selects the exit option.
 End.

Variable Type Description


data int Stores the value of a node in the list.
next Node Reference to the next node in the list.

head Node Reference to the first node in the list.

temp Node Temporary reference for traversal in the list.

choice int Stores the user’s menu choice for list


operations.
sc Scanner Object for user input
Isc Computer project XII 89

Code in java:-
import java.util.Scanner;

class Node {
int data; // Data to store in the node
Node next; // Reference to the next node

// Constructor to initialize the node


public Node(int data) {
this.data = data;
this.next = null;
}
}

class SinglyLinkedList {
private Node head; // Reference to the head of the list

// Constructor to initialize an empty list


public SinglyLinkedList() {
head = null;
}

// Method to insert a new node at the end of the list


public void insert(int data) {
Node newNode = new Node(data); // Create a new node
if (head == null) { // If the list is empty
head = newNode;
} else {
Node temp = head;
while (temp.next != null) { // Traverse to the end of the list
temp = temp.next;
}
temp.next = newNode; // Link the new node at the end
}
System.out.println(data + " inserted into the list.");
}

// Method to delete the first node from the list


public void delete() {
if (head == null) { // If the list is empty
System.out.println("List is empty. Nothing to delete.");
} else {
System.out.println("Deleted: " + head.data);
head = head.next; // Move head to the next node
}
}
Isc Computer project XII 90

// Method to display all elements in the list


public void display() {
if (head == null) { // If the list is empty
System.out.println("List is empty.");
} else {
System.out.println("List elements:");
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
}
}

// Main method to test the linked list implementation


public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
Scanner sc = new Scanner(System.in);

while (true) {
// Menu options
System.out.println("\nMenu:");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter the element to insert: ");
int element = sc.nextInt();
list.insert(element);
break;
case 2:
list.delete();
break;
case 3:
list.display();
break;
case 4:
System.out.println("Exiting program.");
System.exit(0);
default:
Isc Computer project XII 91

System.out.println("Invalid choice! Please try again.");


}
}
}
}

You might also like