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

Utkarma Verma - Computer Science Project

The document describes a Java program to check if a number is an Armstrong number. It includes: 1. A class "ArmNum" with data members to store the input number and methods like a constructor, a method "checkArm()" to check if a number is Armstrong, and a main method. 2. The "checkArm()" method calculates the sum of cubes of each digit and compares it with the original number. 3. The main method creates an object, calls the constructor to take input, and calls "checkArm()" to check if the number is Armstrong, printing the result.

Uploaded by

RISHABH YADAV
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)
169 views

Utkarma Verma - Computer Science Project

The document describes a Java program to check if a number is an Armstrong number. It includes: 1. A class "ArmNum" with data members to store the input number and methods like a constructor, a method "checkArm()" to check if a number is Armstrong, and a main method. 2. The "checkArm()" method calculates the sum of cubes of each digit and compares it with the original number. 3. The main method creates an object, calls the constructor to take input, and calls "checkArm()" to check if the number is Armstrong, printing the result.

Uploaded by

RISHABH YADAV
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/ 119

Assessment Sheet 

 
o Name - Utkarsh 
Verma 
 
o Class/Section - XI-A 
 
o Topic of Project - 
Computer Science 
   
o Teacher’s Signature-
ACKNOWLEDGEMENT 
 
I​ would like to express my special thanks of 
gratitude to my teacher ​Mr. Sarfaraz Sir ​as well 
as our senior principal ​Mrs. Jyoti Ma’am​ and 
junior principal ​Mrs. Shivani Ma’am,​ who gave me 
the golden opportunity to do this wonderful project 
on the topic Computer Science , which also helped 
me in doing a lot of Research and I came to know 
about so many new things I am really thankful to 
them. 
 
S​econdly I would also like to thank my parents and 
friends who helped me a lot in finalizing this 
project within the limited time frame. 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Program 1 
A class ArrayMax contains a square matrix which finds the largest
element in each row.

Some of the members of the class are given below:

Class name : ArrayMax

Data member/instance variable:

arr[ ][ ] : array to store integer elements

m : to store the order of the matrix

Member functions/methods:

ArrayMax( int mm) : parameterized constructor to initialize the data

member m=mm and to declare the array

void readarray() : to accept the array elements

void large( ) : finds and displays the largest element in each row

with an appropriate message

void display() : displays the array elements in matrix form import


java.util.Scanner;

class ArrayMax

int m ;// instance variable m of type int

int arr[][] ;// instance array of type int

ArrayMax( int mm )// parameterised constructor

{
m = mm ;

arr = new int[m][m] ;

void readarray()// function that takes input from the user

Scanner sc = new Scanner( System.in );// create scanner object for


taking input from keyboard

System.out.println( " Please enter all the numbers . They will be


arranged in a table of " + m + "*" + m + "size . " );

for( int i = 0 ; i < m ; i++ )// outer loop for taking input

for( int j = 0 ; j < m ; j++ )// inner loop

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

void large()// function that finds and displays each row's largest element

for( int i = 0 ; i < m ; i++ )// outer loop

int lgst = 0 ;

for( int j = 0 ; j < m ; j++ )// inner loop

{
if( lgst < arr[i][j] )

lgst = arr[i][j] ;

System.out.println( " Of row " + i + " largest element is " + lgst );

void display()// function that displays the array in matrix/table form

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

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

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

System.out.println();

System.out.println();

System.out.println();

public static void main ()

Scanner sc = new Scanner(System.in);

System.out.println( " Please enter the side of square table " );

ArrayMax a = new ArrayMax(sc.nextInt());


a.readarray();

System.out.println( " The elements you entered are ( in arranged tabular


form ) : " );

a.display();

a.large();

Variable Type Function

arr[][] Double Stores all the input numbers


dimensional int
array

m Int Stores dimensional of arr[][]

i Int Counter variables for loops

j Int

lgst Int Stores max num in each row

a ArrayMax Used by main function to execute


the task

  

 
Algorithm 
Input taken from user, stored in a double dimensional array by using a
for loop with one nested loop. nested fills rows, outer changes rows.
Separate function.

Displayed in tabular/matrix form after using input function using a loop


with nested loop. Inner loop prints row in one line, outer loop changes
row. Separate function.

Largest number in each row displayed after input is displayed by storing


the largest number temporarily in a variable (initial value 0) and
compared with each number (variable changed to larger value) and
variable printed after comparing with the final member of a row.

Main function acts as a menu and calls functions to complete the task
and acts as a menu by calling various methods.
Program 2 
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( )import java.util.Scanner;

import java.util.StringTokenizer ;

class WordWise

String str ;// class variables

Scanner sc = new Scanner(System.in);


void readSent()// function that takes input from the user

System.out.println( " Please enter a sentence " );

str = sc.nextLine();

str = str.trim() ;

int freq_vowel( String w )// function that takes parameter string( assumed
to be a word ) and returns frequency of vowels in it

int a = w.length() ;

w = w.toUpperCase() ;

int b = 0 ;

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

if ( w.charAt(i) == 'A' || w.charAt(i) == 'E' || w.charAt(i) == 'I' ||


w.charAt(i) == 'O' || w.charAt(i) == 'U' )

b++;

if( w.charAt(i) == ' ' && i != 0 )

i=a;

return b ;

void arrange()

{
StringTokenizer d = new StringTokenizer(str);

int a = str.length();

int b = 0 ;

int c = d.countTokens() ;

String str2 = "" ;

String str3 = str ;

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

b = str3.indexOf( ' ' ) ;

if( b == -1 )

str2 = str3 ;

else

str2 = str3.substring(0,b);

int e = freq_vowel( str2 ) ;

System.out.println( str2 + " has " + e + " vowels . " ) ;

if( b!= -1 )

str3 = (str3.substring(b)).trim() ;

}
public static void main()

WordWise a = new WordWise() ;

a.readSent();

a.arrange();

Variable Type Description

str String Stores the input

Stores length of str


a int

b int Stores frequency of vowels in a word

i int Counter variable

c int Stores number of words in a sentence

String Stores a word to be used


str2

e int Stores frequency of vowels in a word

Algorithm 
Input (a sentence) is taken from the user and stored in a variable of type
string

By taking an appropriate number of variables of various kinds and using


a for loop, an if else construct with one if and one else and another
(separate) if, print the vowel frequency (determined by another function)
along with the word.

To calculate a word’s vowel frequency, store it in a string, check if each


letter is a vowel and if yes add one to a variable (initial value 0) which
stores the vowel frequency

The main function simply call the other functions to finish the task
Program 3
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 ]

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

class PrimePalinGen

int start = 0 ;

int end = 0 ;

PrimePalinGen( int a , int b )

start = a ;

end = b ;

int isPrime( int i )

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

if( i%j == 0 )

return 0 ;

return 1 ;

int isPalin(int i )

int a = 0 ;
int temp = i ;

while ( temp != 0 )

a = temp%10 + a*10 ;

temp = temp/10 ;

if( i == a )

return 1 ;

else

return 0 ;

void generate()

System.out.println( " Prime palindrome numbers within " + start + " and "
+ end + " are : " );

for( int i = start ; i <= end ; i++ )

if( isPalin(i) == 1 && isPrime(i) == 1 )

System.out.println( i );

}
Variable Type Description

start int Stores the range of numbers

end

i int Counter variables

a int Stores new reversed word

temp int Stores temporary work copy of a number

Algorithm 
A range of numbers ( start and end number ) are taken from the user as
input

A number is checked to be prime by dividing it with every natural number


smaller than it and if it divides by anything else than 1 or itself , it returns
false

A number is reversed by using a single loop . The original number is


copied in a second variable and a third variable is used to store the
reversed number . The second variable is divided by 10 . The remainder
is added to the third variable multiplied by 10 and is stored in the third
variable as it’s new value . then it is checked if the revered digit is equal
to the original digit( i.e. , if it is a palindrome )

The main function takes every number in a range and checks if it is


prime and palindrome . if it is , then it is printed in the list of prime
palindrome numbers
Program 4 
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

Some of the members of the class are given below:

Class name: Arm Numb

Data members/instance variables:

n: to store the number

1: to store the length of the number

Methods/Member functions:

Arm Numb (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 eg., 34 will return 32
+ 42 (as the length of the number is 2)

void isArmstrong(): checks whether the given number is an Armstrong


number by invoking the function sum_pow () and displays the result with
an appropriate message.

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


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

class ArmNum
{

int n ;// declares member methods for storing a number and it's length

int l ;

Arm Numb( int nn )// parameterised constructor

n = nn ;

while( nn != 0 )

l++ ;

nn = nn/10 ;

int sum_pow( int i )

int sum = 0 ;

int temp = i ;

for( int j = 1 ; j < l ; j ++ )

sum = sum + ( ( temp%10 ) * ( temp%10 ) );

temp = temp/10 ;

return sum ;

}
void isArmstrong()

if( n == sum_pow(n) )

System.out.println( n + " is an armstrong number " ) ;

else

System.out.println( n + " is not an armstrong number " ) ;

Variable Type Description

n int Stores a number

l int Stores number of digits in the number

sum int Stores the sum of square of digits

temp int Temporary work copy

j int Counter variable

 
Algorithm 
First input is taken from the user for the number to be checked

The number is checked by dividing the number by 10 , the cube of the


remainder is added to a variable used to store the sum of the cube of
digits . The quotient is again divided by 10 and the process continues till
the last digit is cubed and added .

The final sum is compared with the original number . if they are equal , a
message is displayed telling the user that the number is an armstrong
number . else the message says it is not an Armstrong number
Program 4
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

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

vow freq_vow_con(): finds the frequency of vowels and consonants in


the word and displays them with an appropriate message

void arrange(): rearranges the word by bringing the vowels at the


beginning followed by consonants

void display(): displays the original word along with the rearranged word

Specify the class Rearrange, giving the details of the constructor(), void
readword(), void freq _vow_con(), void arrange() and void display().
Define the main() function to create an object and call the functions
accordingly to enable the task.

import java.util.Scanner ;

class arrange
{

String wrd ;

StringBuffer newwrd ;

Scanner sc = new Scanner( System.in ) ;

arrange( )

wrd = "" ;

newwrd = new StringBuffer( "" );

void readword () // accepts word in upper case

System.out.println( " Please enter a word in upper case " ) ;

wrd = sc.next() ;

wrd = wrd.toUpperCase() ;

newwrd.setLength( wrd.length() ) ;

void freq_vow_con () // shows frequency of vowels and consonants

int vow = 0 ;

int con = 0 ;

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

{
if( wrd.charAt(i) == 'A' || wrd.charAt(i) == 'E' || wrd.charAt(i) == 'I' ||
wrd.charAt(i) == 'O' || wrd.charAt(i) == 'U' )

vow ++ ;

else

con ++ ;

System.out.println( " Number of consonants = " + con );

System.out.println( " Number of vowels = " + vow ) ;

void arrange () // bring vowels at beginning

int ind = 0 ;

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

if ( wrd.charAt( i ) == 'A' || wrd.charAt( i ) == 'E' || wrd.charAt( i ) == 'I' ||


wrd.charAt( i ) == 'O' || wrd.charAt( i ) == 'U' )

newwrd.setCharAt( ind , wrd.charAt( i ) );

ind ++ ;

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

{
if ( wrd.charAt( i ) == 'A' || wrd.charAt( i ) == 'E' || wrd.charAt( i ) == 'I' ||
wrd.charAt( i ) == 'O' || wrd.charAt( i ) == 'U' )

{}

else

newwrd.setCharAt( ind , wrd.charAt( i ) ) ;

ind ++ ;

void display () // displays original and new word

System.out.println( " Original word is " + wrd + " \n Rearranged word is "
+ newwrd ) ;

public static void main ()

arrange a = new rearrange() ;

a.readword() ;

a.freq_vow_con() ;

a.arrange() ;

a.display() ;

}
Variable Type Description

wrd String Stores input number

newwrd StringBuff Stores rearranged number


er

vow int Stores number of vowels in a number

con int Stores number of consonants in a number

i int Counter variable

ind int Stores next index of character

Algorithm

Rearrange

The program takes input from the user in the form of a word using a
separate function.

The frequency of vowels and consonants is calculated and displayed.

Then the program generates a new word that has the vowels of the
entered word in the beginning of the word by using two for loops. The
first loop checks the letters of the word and on detecting a vowel it is
placed in the beginning of a new word. The second loop does the same
but searches for consonants and places them in string after the vowels.

Then the new word is displayed alongside the input .


Program 5 
Design a class to overload a function volume() as follows :

(i) double volume (double R) — with radius (R) as an argument, returns


the volume of the sphere using the formula.

V = 4/3 × 22/7 × R​3

(ii) double volume (double H, double R) – with height(H) and radius(R)


as the arguments, returns the volume of a cylinder using the formula.

V = 22/7 × R​2​ × H

(iii) double volume (double L, double B, double H) – with length(L),


breadth(B) and Height(H) as the arguments, returns the volume of a
cuboid using the formula.

class ShapesVolume {

public static double volume (double R) {

double V = 4.0 / 3 * 22.0 / 7 * Math.pow(R, 3);

return V;

public static double volume(double H, double R) {

double V = 22.0 / 7 * R * R * H ;

return V;

public static double volume (double L, double B, double H) {

double V = L * B * H;

return V;
}

Variable Type Description

V double Stores volume of regular shape

R double Stores dimensions of regular shape

  

Algorithm 
The program overloads a function volume that finds the volume of a
regular 3d shape assuming the shape based to actual parameters

The program takes basic data about a shape such as its length, radius
etc. and uses mathematical formula to calculate and assign a variable
the volume of the shape and returns said variable
Program 6 
Design a class Railway Ticket with following description:

Instance variables/s data members :

String name : To store the name of the customer

String coach : To store the type of coach customer wants to travel

long mobno : To store customer’s mobile number

int amt : To store basic amount of ticket

int total amt : To store the amount to be paid after updating the original
amount

Member methods

void accept ( ) — To take input for name, coach, mobile number and
amount

void update ( )— To update the amount as per the coach selected


Type of Coaches Amount

First_ AC 700

Second_AC 500

Third _AC 250

Sleeper None

import java.io.*;

import java.util.Scanner;

class RailwayTicket {

String name, coach;

long mobno;

int amt, total amt;

void accept( ) throws IOException {

Scanner sc = new Scanner(System.in);

System.out.print("Enter Passenger’s Name: ");

name = sc.next( );
System.out.print("Enter Mobile Number:");

mobno = sc.nextLong( );

System.out.print("Enter Coach (FirstAC/SecondAC/ThirdAC/sleeper):");

coach = sc.next( );

System.out.print("Enter basic amount of ticket:");

amt = sc.nextInt( );

void update() {

if (coach.equals("FirstAC"))

total amt = amt + 700;

else

if (coach.equals("SecondAC"))

total amt = amt + 500;

else

if (coach.equals("ThirdAC"))

total amt = amt + 250;

else

total amt = amt;

void display() {

System.out.println("\n\n Name :" +name);

System.out.println("Coach :" +coach);

System.out.println("Total Amount:" +total amt);


System.out.println("Mobile No.:" +name);

public static void main (String args[ ]) throws IOException {

RailwayTicket t = new RailwayTicket();

t.accept();

t.update();

t.display();

Variable Type Description

name String Stores name of customer

coach String Stores class of coach

mobno long Stores mobile number of customer

amt int Stores base amount of ticket

total amt int Stores final amount of ticket

 
Algorithm 
The program takes input in form of coach, mobile number of customer
passenger’s name and basic amount of the ticket by involving functions
of scanner class in a separate function.

Then it updates the total amount of the ticket using a function that
determines the final price of the ticket based on the railway company’s
policy using an if else construct .

The program then uses a function that displays the passenger’s info .

 
 
 
 
 
 
 
Program 7  
Write a program to accept name and total marks of N number of
students in two single subscript array name[] and total marks[ ].

Calculate and print:

(i) The average of the total marks obtained by N Number of students.

[average = (sum of total marks of all the students)/N]

(ii) Deviation of each student’s total marks with the average.

[deviation = total marks of a student – average]

import java.io.*;

import java. util. Scanner;

class NameMarks {

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.print( "Enter number of students: ");

int N = sc.nextInt( );

String name[] = new String[N];

int total marks[] = new int[N];

double deviation[ ] = new double[N];

double sum = 0;

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

System.out.print( "Enter Name of the Student: ");

name[i] = sc.next( );

System.out.print("Enter Marks:");
total marks[i] = sc.nextInt();

sum = sum + total marks [i];

double average = sum / N;

System.out.println( "The average of the total marks of " +N+ " number of
students: " +average);

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

deviation[i] = total marks[i] - average;

System.out.println( "Deviation of " + name[i] + "s marks with the


average: " +deviation[i]);

}
Variable Type Description

N int Stores number of students

name[] String Stores names of students


array

total Int array Stores marks of each student


marks[]

sum int Stores total marks

deviations[ Int array Stores deviation of each student from


] average

i int Counter variable

Algorithm 
The program first takes input in the form of the number of students and
names of students alongside the marks secured by them. The input is
stored in arrays which are of the size of the number of students. Input is
taken by using a for loop and the sum (for calculating average) is
calculated alongside taking input.

The average is then calculated immediately after taking input and is


displayed .

Using a for loop all the student’s deviation from the average is calculated
and immediately displayed and stored .
Program 8  
Design a class Perfect to check if a given number is a perfect number or
not. [A number is said to be perfect if sum of the factors of the number
excluding itself is equal to the original number]

Some of the members of the class are given below:

Class name: Perfect

Data members/instance variables:

num: to store the number

Methods/Member functions:

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


num=nn

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


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

void check(): checks whether the given number is perfect by invoking the
function sum_of_factors() and displays the result with an appropriate
message

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


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

import java.io.*;

import java.util.Scanner;
class Perfect{

private int num;

private int f;

public Perfect(int num) {

this.num = num;

f = 1;

public int sumofFactors(int i) {

if(i==f){

return 0;

else if(i%f==0)

return c++ + sumofFactors(i);

else{

f++;

return sumofFactors(i);

public void check() {

if(num==sumofFactors(num))

System.out.println(num + " is a Perfect Number");

else

System.out.println(num + " is not a Perfect Number");


}

public static void main(String args[ ])throws IOException {

Scanner sc = new Scanner(System.in);

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

int n = sc.nextInt();

Perfect obj = new Perfect(n);

obj.check();

Variable Type Description

num int Stores input from user

f int A number to check for being a factor of num

n int Stores input from user

Algorithm 
The program checks for a perfect number by calculating the sum of
factors and comparing it with the initial number using a recursive method
done by a separate function.

Another method is used to invoke the first function and compare the
returned value with the first value.

The main method acts as a menu and calls the second function to do the
task .
Program 9
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 the 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.

import java.io.*;
import java.util. Scanner;

import java.util.StringTokenizer;

public class Capital{

private String sent;

private int freq;

public Capital() {

sent = new String();

freq = 0;

public void input() throws IOException {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the sentence: ");

sent = sc.nextLine();

boolean isCap(String w) {

char ch = w.charAt(0);

if(Character.isLetter(ch) && Character.isUpperCase(ch))

return true;

return false;

public void display() {

StringTokenizer st = new StringTokenizer(sent, "" );

int count = st.countTokens();


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

String word = st.nextToken();

if(isCap(word))

freq++;

System.out.println("Sentence: " + sent);

System.out.println("Frequency: " + freq);

public static void main(String args[ ])throws IOException {

Capital obj = new Capital();

obj.input();

obj.display();

Variable Type Description

sent String Stores input from the user

freq int Stores frequency of words that start with a


capital letter

i int Counter variables

ch char Stores first character of a word

count int Stores number of words in a sentence


Algorithm 
The program checks the frequency of capital letter beginning words by
using the StringTokenizer class.

First input is taken from the user in the form of a sentence using the
scanner method. separate function.

It is checked if a word begins with a capital letter by a function that takes


a string literal as input and returns Boolean value by checking the first
letter of the given string.

A separate function is used that uses the second function and calculates
the frequency of capital starting words and displays said frequency .
Program 10 
A class Merger concatenates two positive integers that are greater than
0 and produces a newly merged integer.

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.
import java.util. Scanner;

class Merger

long n1; long n2;

long magNum;

public Merger()

n1=1;

n2=1;

magNum=11;

public void readNum()

Scanner sc=new Scanner(System.in);

System.out.print("Enter first number:");

n1=(int)Math.abs(sc.nextLong());

System.out.print("Enter second number:");

n2=(int)Math.abs(sc.nextLong());

if(n1==0)

n1=1;

if(n2==0)

n2=1;

}
public void joinNum()

String num1 = Long.toString(n1);

String num2 = Long.toString(n2);

String merged=num1 + num2;

magNum=Long.parseLong(merged);

public void show()

System.out.println("First Number: "+n1);

System.out.println("Second Number: "+n2);

System.out.println("Merged Number: "+mergNum);

public static void main(String args[])

Merger obj=new Merger();

obj.readNum();

obj.joinNum();

obj.show();

}
Variable Type Description

n1 long Stores input from the user

n2 long

mergNum long Stores merged number

num1 String Stores parsed n1 and n2

num2

Algorithm 
The program first takes input from the user in the form of two integer
numbers which are immediately stored in the form of their absolute
values. Any value equal to 0 is immediately changed to 1.

Then two string variables are declared and initialized with the value of
one of the parsed integers using the Long.toString() function. the two
strings are then contacted to form a merged integer which is parsed and
stored in a variable of type long.

The two numbers along with the merged number are then displayed.
Program 11 
A class SeriesSum is designed to calculate the sum of the following
series:

Sum=x2(1)!+x4(3)!+x6(5)!+…xn(n−1)!

Some of the members of the class are given below:

Class name: SeriesSum

Data members/instance variables:

x: to store an integer number

n: to store the number of terms

sum: double variable to store the sum of the series

Member functions:

SeriesSum(int xx, int nn): constructor to assign x=xx and n=nn

double find fact(int m): to return the factorial of m using the recursive
technique.

double find power(int x, int y): to return x raised to the power of y using
the recursive technique.

void calculate(): to calculate the sum of the series by invoking the


recursive functions respectively

void display(): to display the sum of the series

(a) Specify the class SeriesSum, giving details of the constructor(int, int),
double find fact(int),

double find power(int, int), void calculate() and void display(). Define the
main() function to create an object and call the functions accordingly to
enable the task. [8]
import java.util.Scanner;

class SeriesSum

int x, n;

double sum;

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

SeriesSum(int xx, int nn)

x=xx;

n=nn;

sum=0.0;

double findfact(int a)

return (a<2)? 1:a*findfact(a-1);

double findpower(int a, int b)

return (b==0)? 1:a*findpower(a,b-1);

void calculate()
{

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

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

void display()

System.out.println("sum="+ sum);

public static void main()

System.out.println( " Please enter the constant then the number of terms
" );

SeriesSum obj = new SeriesSum(sc.nextInt() , sc.nextInt());

obj.calculate();

obj.display();

Variable Type Description

x int Stores input from user

sum double Stores sum of series


i int Counter variable

Algorithm 
The program takes input from the user in form of a constant and the total
number of terms in the series and the input is taken first.

Then using a for loop the sum of the series is calculated. A function is
used to find the power to which the constant is to be raised and another
function the factorial of the divisor is calculated.

Then the sum is displayed .


Program 12 
A class Palin has been defined to check whether a positive number is a
Palindrome number or not.

The number ‘N’ is palindrome if the original number and its reverse are
the same.

Some of the members of the class are given below:

Class name: Palin

Data members/instance variables:

num: integer to store the number

revnum: integer to store the reverse of the number

Methods/Member functions:

Palin(): constructor to initialize data members with legal initial values

void accept(): to accept the number

int reverse(int y): reverses the parameterized argument ‘y’ and stores it
in revenue using a recursive technique
void check(): checks whether the number is a Palindrome by invoking
the function reverse() and display the result with an appropriate
message

Specify the class Palin giving the details of the constructor (), void
accept(), int reverse(int) and void check(). Define the main() function to
create an object and call the functions accordingly to enable the task.

import java.io.*;

class Palin {

static int num;

int revnum;

Palin() {

num = 0;

revnum = 0;

void accept() throws IOException {

BufferedReader y = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter the Number:");

String a = y. readLine();

num = Integer.parseInt(a);

int reverse(int i) {

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


{

if( i%j == 0 )

return 0 ;

return 1 ;

void check( int i ){

int a = 0 ;

int temp = i ;

while ( temp != 0 )

a = temp%10 + a*10 ;

temp = temp/10 ;

if( i == a )

System.out.println("\n Number is palindrome");

else

System.out.println("\n Number is not palindrome");

public static void main(String args[]) throws IOException {

Palin p = new Palin();

p.accept();

p.check( num );
}

Variable Type Description

num int Stores input from user

revnum int Stores reversed number

y BufferedRea Takes input from keyboard


der

a String Stores initial input from BufferedReader

i int Counter variable

temp int Temporary work copy of num

a int Stores intermediate values while


computing reverse of num

Algorithm 
The program takes a number as input.
The program uses a for loop to check weather a number is palindrome
or not

Program 13  
A class Adder has been defined to add any two accepted times.

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

Class name: Adder

Data member/instance variable:

a[ ]: integer array to hold two elements (hours and minutes)

Member functions/methods:

Adder (): constructor to assign 0 to the array elements

void read time (): to enter the elements of the array

void addtime (Adder X, Adder Y): adds the time of the two parameterized
objects X and Y and stores the sum in the current calling object

void disptime(): displays the array elements with an appropriate


message (i.e., hours= and minutes=)

Specify the class Adder giving details of the constructor( ), void read
time( ), void addtime(Adder, Adder) and void disptime(). Define the
main() function to create objects and call the functions accordingly to
enable the task.
Answer:

import java.util.Scanner;

class Adder {

int a[];

Adder() {

a = new int[2];

void read time() {

Scanner sc = new Scanner( System.in ) ;

System.out.println("Enter hour:");

a[0] = sc.nextInt();

System.out.println("Enter minute :");

a[1] = sc.nextInt();

void addtime(Adder X, Adder Y) {

int hour1 = X.a[0];

int min1 = X.a[1];

int hour2 = Y.a[0];

int min2 = Y.a[1];

int hourSum = hour1 + hour2;

int minSum = min1 + min2;

a[0] = hourSum + (minSum/60);

a[1] = minSum%60;
}

void disptime() {

System.out.println("Their sum is-");

System.out.println("hours =" + a[0] +" minutes =" + a[1]);

public static void main(String args[ ]){

Adder obj1 = new Adder();

Adder obj2 = new Adder();

Adder sumObj = new Adder();

obj1.read time();

obj2.read time();

sumObj.addtime(obj1, obj2);

sumObj.disptime();

Variable Type Description

a[] int array Stores hour and minute

hour1 int Stores time from both objects

hour2

min1

min2
Algorithm 

Adder 
The program takes input in the form of time, hours and minutes.

The sum is calculated using a formula related to the 60 min hour format.

The main class creates two objects of Adder type and uses the add time
function of the object it’s part of that takes objects of type Adder as
actual parameters .
Program 14 
It contains a square matrix which finds the largest element in each row.

Some of the members of the class are given below:

Class name : ArrayMax

Data member/instance variable:

arr[ ][ ] : array to store integer elements

m : to store the order of the matrix

Member functions/methods:

ArrayMax( int mm) : parameterized constructor to initialize the data

member m=mm and to declare the array

void readarray() : to accept the array elements

void large( ) : finds and displays the largest element in each row

with an appropriate message

void display() : displays the array elements in matrix form import


java.util.Scanner;

class ArrayMax

int m ;// instance variable m of type int

int arr[][] ;// instance array of type int

ArrayMax( int mm )// parameterised constructor


{

m = mm ;

arr = new int[m][m] ;

void readarray()// function that takes input from the user

Scanner sc = new Scanner( System.in );// create scanner object for


taking input from keyboard

System.out.println( " Please enter all the numbers . They will be


arranged in a table of " + m + "*" + m + "size . " );

for( int i = 0 ; i < m ; i++ )// outer loop for taking input

for( int j = 0 ; j < m ; j++ )// inner loop

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

void large()// function that finds and displays each row's largest element

for( int i = 0 ; i < m ; i++ )// outer loop

int lgst = 0 ;

for( int j = 0 ; j < m ; j++ )// inner loop


{

if( lgst < arr[i][j] )

lgst = arr[i][j] ;

System.out.println( " Of row " + i + " largest element is " + lgst );

void display()// function that displays the array in matrix/table form

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

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

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

System.out.println();

System.out.println();

System.out.println();

public static void main ()

Scanner sc = new Scanner(System.in);

System.out.println( " Please enter the side of square table " );


ArrayMax a = new ArrayMax(sc.nextInt());

a.readarray();

System.out.println( " The elements you entered are ( in arranged tabular


form ) : " );

a.display();

a.large();

Variable Type Function

arr[][] Double Stores all the input numbers


dimensional int
array

m Int Stores dimension of arr[][]

i Int Counter variables for loops

j Int

lgst Int Stores max num in each row

a ArrayMax Used by main function to execute


the task
Algorithm 
Input taken from user, stored in a double dimensional array by using a
for loop with one nested loop. nested fills rows, outer changes rows.
Separate function.

Displayed in tabular/matrix form after using input function using a loop


with nested loop. Inner loop prints row in one line, outer loop changes
row. Separate function.

Largest number in each row displayed after input is displayed by storing


the largest number temporarily in a variable (initial value 0) and
compared with each number (variable changed to larger value) and
variable printed after comparing with the final member of a row.

Main function acts as a menu and calls functions to complete the task
and acts as a menu by calling various methods.
Program 15 
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( )import java.util.Scanner;

import java.util.StringTokenizer ;

class WordWise

String str ;// class variables


Scanner sc = new Scanner(System.in);

void readSent()// function that takes input from the user

System.out.println( " Please enter a sentence " );

str = sc.nextLine();

str = str.trim() ;

int freq_vowel( String w )// function that takes parameter string( assumed
to be a word ) and returns frequency of vowels in it

int a = w.length() ;

w = w.toUpperCase() ;

int b = 0 ;

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

if ( w.charAt(i) == 'A' || w.charAt(i) == 'E' || w.charAt(i) == 'I' ||


w.charAt(i) == 'O' || w.charAt(i) == 'U' )

b++;

if( w.charAt(i) == ' ' && i != 0 )

i=a;

return b ;

void arrange()
{

StringTokenizer d = new StringTokenizer(str);

int a = str.length();

int b = 0 ;

int c = d.countTokens() ;

String str2 = "" ;

String str3 = str ;

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

b = str3.indexOf( ' ' ) ;

if( b == -1 )

str2 = str3 ;

else

str2 = str3.substring(0,b);

int e = freq_vowel( str2 ) ;

System.out.println( str2 + " has " + e + " vowels . " ) ;

if( b!= -1 )

str3 = (str3.substring(b)).trim() ;

}
}

public static void main()

WordWise a = new WordWise() ;

a.readSent();

a.arrange();

Variable Type Description

str String Stores the input

Stores length of str


a int

b int Stores frequency of vowels in a word

i int Counter variable


c int Stores number of words in a sentence

String Stores a word to be used


str2

e int Stores frequency of vowels in a word

Algorithm 
Input (a sentence) is taken from the user and stored in a variable of type
string

By taking an appropriate number of variables of various kinds and using


a for loop, an if else construct with one if and one else and another
(separate) if, print the vowel frequency (determined by another function)
along with the word.

To calculate a word’s vowel frequency, store it in a string, check if each


letter is a vowel and if yes add one to a variable (initial value 0) which
stores the vowel frequency

The main function simply call the other functions to finish the task

 
 
 
 
Program 16 
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 ]

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

class PrimePalinGen

int start = 0 ;

int end = 0 ;

PrimePalinGen( int a , int b )

start = a ;

end = b ;

int isPrime( int i )

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

if( i%j == 0 )

return 0 ;

return 1 ;

int isPalin(int i )

int a = 0 ;

int temp = i ;
while ( temp != 0 )

a = temp%10 + a*10 ;

temp = temp/10 ;

if( i == a )

return 1 ;

else

return 0 ;

void generate()

System.out.println( " Prime palindrome numbers within " + start + " and "
+ end + " are : " );

for( int i = start ; i <= end ; i++ )

if( isPalin(i) == 1 && isPrime(i) == 1 )

System.out.println( i );

}
Variable Type Description

start int Stores the range of numbers

end

i int Counter variables

a int Stores new reversed word

temp int Stores temporary work copy of a number

 
 

Algorithm 
A range of numbers ( start and end number ) are taken from the user as
input

A number is checked to be prime by dividing it with every natural number


smaller than it and if it divides by anything else than 1 or itself , it returns
false

A number is reversed by using a single loop . The original number is


copied in a second variable and a third variable is used to store the
reversed number . The second variable is divided by 10 . The remainder
is added to the third variable multiplied by 10 and is stored in the third
variable as it’s new value . then it is checked if the revered digit is equal
to the original digit( i.e. , if it is a palindrome )

The main function takes every number in a range and checks if it is


prime and palindrome . if it is , then it is printed in the list of prime
palindrome numbers

 
 
 
 
 
Program 17 
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

Some of the members of the class are given below:

Class name: Arm Numb

Data members/instance variables:

n: to store the number

1: to store the length of the number

Methods/Member functions:

Arm Numb (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 eg., 34 will return 32
+ 42 (as the length of the number is 2)

void isArmstrong(): checks whether the given number is an Armstrong


number by invoking the function sum_pow () and displays the result with
an appropriate message.

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


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

class ArmNum

int n ;// declares member methods for storing a number and it's length

int l ;
Arm Numb( int nn )// parameterised constructor

n = nn ;

while( nn != 0 )

l++ ;

nn = nn/10 ;

int sum_pow( int i )

int sum = 0 ;

int temp = i ;

for( int j = 1 ; j < l ; j ++ )

sum = sum + ( ( temp%10 ) * ( temp%10 ) );

temp = temp/10 ;

return sum ;

void isArmstrong()

if( n == sum_pow(n) )
System.out.println( n + " is an armstrong number " ) ;

else

System.out.println( n + " is not an armstrong number " ) ;

Variable Type Description

n int Stores a number

l int Stores number of digits in the number

sum int Stores the sum of square of digits

temp int Temporary work copy

j int Counter variable

Algorithm 
First input is taken from the user for the number to be checked

The number is checked by dividing the number by 10 , the cube of the


remainder is added to a variable used to store the sum of the cube of
digits . The quotient is again divided by 10 and the process continues till
the last digit is cubed and added .

The final sum is compared with the original number . if they are equal , a
message is displayed telling the user that the number is an armstrong
number . else the message says it is not an Armstrong number
Program 18 
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

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

vow freq_vow_con(): finds the frequency of vowels and consonants in


the word and displays them with an appropriate message

void arrange(): rearranges the word by bringing the vowels at the


beginning followed by consonants

void display(): displays the original word along with the rearranged word

Specify the class Rearrange, giving the details of the constructor(), void
readword(), void freq _vow_con(), void arrange() and void display().
Define the main() function to create an object and call the functions
accordingly to enable the task.

import java.util.Scanner ;

class arrange

{
String wrd ;

StringBuffer newwrd ;

Scanner sc = new Scanner( System.in ) ;

arrange( )

wrd = "" ;

newwrd = new StringBuffer( "" );

void readword () // accepts word in upper case

System.out.println( " Please enter a word in upper case " ) ;

wrd = sc.next() ;

wrd = wrd.toUpperCase() ;

newwrd.setLength( wrd.length() ) ;

void freq_vow_con () // shows frequency of vowels and consonants

int vow = 0 ;

int con = 0 ;

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

if( wrd.charAt(i) == 'A' || wrd.charAt(i) == 'E' || wrd.charAt(i) == 'I' ||


wrd.charAt(i) == 'O' || wrd.charAt(i) == 'U' )
vow ++ ;

else

con ++ ;

System.out.println( " Number of consonants = " + con );

System.out.println( " Number of vowels = " + vow ) ;

void arrange () // bring vowels at beginning

int ind = 0 ;

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

if ( wrd.charAt( i ) == 'A' || wrd.charAt( i ) == 'E' || wrd.charAt( i ) == 'I' ||


wrd.charAt( i ) == 'O' || wrd.charAt( i ) == 'U' )

newwrd.setCharAt( ind , wrd.charAt( i ) );

ind ++ ;

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

if ( wrd.charAt( i ) == 'A' || wrd.charAt( i ) == 'E' || wrd.charAt( i ) == 'I' ||


wrd.charAt( i ) == 'O' || wrd.charAt( i ) == 'U' )

{}
else

newwrd.setCharAt( ind , wrd.charAt( i ) ) ;

ind ++ ;

void display () // displays original and new word

System.out.println( " Original word is " + wrd + " \n Rearranged word is "
+ newwrd ) ;

public static void main ()

arrange a = new rearrange() ;

a.readword() ;

a.freq_vow_con() ;

a.arrange() ;

a.display() ;

}
Variable Type Description

wrd String Stores input number

newwrd StringBuff Stores rearranged number


er

vow int Stores number of vowels in a number

con int Stores number of consonants in a number

i int Counter variable

ind int Stores next index of character

Algorithm 

Rearrange 
The program takes input from the user in the form of a word using a
separate function.

The frequency of vowels and consonants is calculated and displayed.

Then the program generates a new word that has the vowels of the
entered word in the beginning of the word by using two for loops. The
first loop checks the letters of the word and on detecting a vowel it is
placed in the beginning of a new word. The second loop does the same
but searches for consonants and places them in string after the vowels.

Then the new word is displayed alongside the input .


Program 19 
Design a class to overload a function volume() as follows :

(i) double volume (double R) — with radius (R) as an argument, returns


the volume of the sphere using the formula.

V = 4/3 × 22/7 × R​3

(ii) double volume (double H, double R) – with height(H) and radius(R)


as the arguments, returns the volume of a cylinder using the formula.

V = 22/7 × R​2​ × H

(iii) double volume (double L, double B, double H) – with length(L),


breadth(B) and Height(H) as the arguments, returns the volume of a
cuboid using the formula.

class ShapesVolume {

public static double volume (double R) {

double V = 4.0 / 3 * 22.0 / 7 * Math.pow(R, 3);

return V;

public static double volume(double H, double R) {

double V = 22.0 / 7 * R * R * H ;

return V;

public static double volume (double L, double B, double H) {


double V = L * B * H;

return V;

Variable Type Description

V double Stores volume of regular shape

R double Stores dimensions of regular shape

Algorithm 
The program overloads a function volume that finds the volume of a
regular 3d shape assuming the shape based to actual parameters

The program takes basic data about a shape such as its length, radius
etc. and uses mathematical formula to calculate and assign a variable
the volume of the shape and returns said variable
Program 20 
Design a class Railway Ticket with following description:

Instance variables/s data members :

String name : To store the name of the customer

String coach : To store the type of coach customer wants to travel

long mobno : To store customer’s mobile number

int amt : To store basic amount of ticket

int total amt : To store the amount to be paid after updating the original
amount

Member methods

void accept ( ) — To take input for name, coach, mobile number and
amount

void update ( )— To update the amount as per the coach selected


Type of Coaches Amount

First_ AC 700

Second_AC 500

Third _AC 250

Sleeper None

import java.io.*;

import java.util.Scanner;

class RailwayTicket {

String name, coach;

long mobno;

int amt, total amt;

void accept( ) throws IOException {

Scanner sc = new Scanner(System.in);

System.out.print("Enter Passenger’s Name: ");


name = sc.next( );

System.out.print("Enter Mobile Number:");

mobno = sc.nextLong( );

System.out.print("Enter Coach (FirstAC/SecondAC/ThirdAC/sleeper):");

coach = sc.next( );

System.out.print("Enter basic amount of ticket:");

amt = sc.nextInt( );

void update() {

if (coach.equals("FirstAC"))

total amt = amt + 700;

else

if (coach.equals("SecondAC"))

total amt = amt + 500;

else

if (coach.equals("ThirdAC"))

total amt = amt + 250;

else

total amt = amt;

void display() {

System.out.println("\n\n Name :" +name);

System.out.println("Coach :" +coach);


System.out.println("Total Amount:" +total amt);

System.out.println("Mobile No.:" +name);

public static void main (String args[ ]) throws IOException {

RailwayTicket t = new RailwayTicket();

t.accept();

t.update();

t.display();

Variable Type Description

name String Stores name of customer

coach String Stores class of coach

mobno long Stores mobile number of customer

amt int Stores base amount of ticket

total amt int Stores final amount of ticket


Algorithm 
The program takes input in form of coach, mobile number of customer
passenger’s name and basic amount of the ticket by involving functions
of scanner class in a separate function.

Then it updates the total amount of the ticket using a function that
determines the final price of the ticket based on the railway company’s
policy using an if else construct .

The program then uses a function that displays the passenger’s info .
Program 21 
Write a program to accept name and total marks of N number of
students in two single subscript array name[] and total marks[ ].

Calculate and print:

(i) The average of the total marks obtained by N Number of students.

[average = (sum of total marks of all the students)/N]

(ii) Deviation of each student’s total marks with the average.

[deviation = total marks of a student – average]

import java.io.*;

import java. util. Scanner;

class NameMarks {

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.print( "Enter number of students: ");

int N = sc.nextInt( );

String name[] = new String[N];

int total marks[] = new int[N];

double deviation[ ] = new double[N];

double sum = 0;
for (int i = 0; i < N; i++) {

System.out.print( "Enter Name of the Student: ");

name[i] = sc.next( );

System.out.print("Enter Marks:");

total marks[i] = sc.nextInt();

sum = sum + total marks [i];

double average = sum / N;

System.out.println( "The average of the total marks of " +N+ " number of
students: " +average);

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

deviation[i] = total marks[i] - average;

System.out.println( "Deviation of " + name[i] + "s marks with the


average: " +deviation[i]);

}
Variable Type Description

N int Stores number of students

name[] String Stores names of students


array

total Int array Stores marks of each student


marks[]

sum int Stores total marks

deviations[ Int array Stores deviation of each student from


] average

i int Counter variable

 
 

Algorithm 
The program first takes input in the form of the number of students and
names of students alongside the marks secured by them. The input is
stored in arrays which are of the size of the number of students. Input is
taken by using a for loop and the sum (for calculating average) is
calculated alongside taking input.

The average is then calculated immediately after taking input and is


displayed .

Using a for loop all the student’s deviation from the average is calculated
and immediately displayed and stored .

 
 
 
 
 
 
Program 22 
Design a class Perfect to check if a given number is a perfect number or
not. [A number is said to be perfect if sum of the factors of the number
excluding itself is equal to the original number]

Some of the members of the class are given below:

Class name: Perfect

Data members/instance variables:

num: to store the number

Methods/Member functions:

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


num=nn

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


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

void check(): checks whether the given number is perfect by invoking the
function sum_of_factors() and displays the result with an appropriate
message

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


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

import java.io.*;

import java.util.Scanner;
class Perfect{

private int num;

private int f;

public Perfect(int num) {

this.num = num;

f = 1;

public int sumofFactors(int i) {

if(i==f){

return 0;

else if(i%f==0)

return c++ + sumofFactors(i);

else{

f++;

return sumofFactors(i);

public void check() {

if(num==sumofFactors(num))

System.out.println(num + " is a Perfect Number");

else

System.out.println(num + " is not a Perfect Number");


}

public static void main(String args[ ])throws IOException {

Scanner sc = new Scanner(System.in);

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

int n = sc.nextInt();

Perfect obj = new Perfect(n);

obj.check();

Variable Type Description

num int Stores input from user

f int A number to check for being a factor of num

n int Stores input from user

  

 
Algorithm 
The program checks for a perfect number by calculating the sum of
factors and comparing it with the initial number using a recursive method
done by a separate function.

Another method is used to invoke the first function and compare the
returned value with the first value.

The main method acts as a menu and calls the second function to do the
task .

 
 
 
 
 
 
 
Program 23 
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 the 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.

import java.io.*;
import java.util. Scanner;

import java.util.StringTokenizer;

public class Capital{

private String sent;

private int freq;

public Capital() {

sent = new String();

freq = 0;

public void input() throws IOException {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the sentence: ");

sent = sc.nextLine();

boolean isCap(String w) {

char ch = w.charAt(0);

if(Character.isLetter(ch) && Character.isUpperCase(ch))

return true;

return false;

public void display() {

StringTokenizer st = new StringTokenizer(sent, "" );

int count = st.countTokens();


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

String word = st.nextToken();

if(isCap(word))

freq++;

System.out.println("Sentence: " + sent);

System.out.println("Frequency: " + freq);

public static void main(String args[ ])throws IOException {

Capital obj = new Capital();

obj.input();

obj.display();

Variable Type Description

sent String Stores input from the user

freq int Stores frequency of words that start with a


capital letter

i int Counter variables

ch char Stores first character of a word

count int Stores number of words in a sentence


Algorithm 
The program checks the frequency of capital letter beginning words by
using the StringTokenizer class.

First input is taken from the user in the form of a sentence using the
scanner method. separate function.

It is checked if a word begins with a capital letter by a function that takes


a string literal as input and returns Boolean value by checking the first
letter of the given string.

A separate function is used that uses the second function and calculates
the frequency of capital starting words and displays said frequency .

 
 
 
 
 
Program 24 
A class Merger concatenates two positive integers that are greater than
0 and produces a newly merged integer.

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.
import java.util. Scanner;

class Merger

long n1; long n2;

long magNum;

public Merger()

n1=1;

n2=1;

magNum=11;

public void readNum()

Scanner sc=new Scanner(System.in);

System.out.print("Enter first number:");

n1=(int)Math.abs(sc.nextLong());

System.out.print("Enter second number:");

n2=(int)Math.abs(sc.nextLong());

if(n1==0)

n1=1;

if(n2==0)

n2=1;

}
public void joinNum()

String num1 = Long.toString(n1);

String num2 = Long.toString(n2);

String merged=num1 + num2;

magNum=Long.parseLong(merged);

public void show()

System.out.println("First Number: "+n1);

System.out.println("Second Number: "+n2);

System.out.println("Merged Number: "+mergNum);

public static void main(String args[])

Merger obj=new Merger();

obj.readNum();

obj.joinNum();

obj.show();

}
Variable Type Description

n1 long Stores input from the user

n2 long

mergNum long Stores merged number

num1 String Stores parsed n1 and n2

num2

Algorithm 
The program first takes input from the user in the form of two integer
numbers which are immediately stored in the form of their absolute
values. Any value equal to 0 is immediately changed to 1.

Then two string variables are declared and initialized with the value of
one of the parsed integers using the Long.toString() function. the two
strings are then contacted to form a merged integer which is parsed and
stored in a variable of type long.

The two numbers along with the merged number are then displayed.
Program 25 
A class SeriesSum is designed to calculate the sum of the following
series:

Sum=x2(1)!+x4(3)!+x6(5)!+…xn(n−1)!

Some of the members of the class are given below:

Class name: SeriesSum

Data members/instance variables:

x: to store an integer number

n: to store the number of terms

sum: double variable to store the sum of the series

Member functions:

SeriesSum(int xx, int nn): constructor to assign x=xx and n=nn

double find fact(int m): to return the factorial of m using the recursive
technique.

double find power(int x, int y): to return x raised to the power of y using
the recursive technique.

void calculate(): to calculate the sum of the series by invoking the


recursive functions respectively

void display(): to display the sum of the series

(a) Specify the class SeriesSum, giving details of the constructor(int, int),
double find fact(int),

double find power(int, int), void calculate() and void display(). Define the
main() function to create an object and call the functions accordingly to
enable the task. [8]
import java.util.Scanner;

class SeriesSum

int x, n;

double sum;

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

SeriesSum(int xx, int nn)

x=xx;

n=nn;

sum=0.0;

double findfact(int a)

return (a<2)? 1:a*findfact(a-1);

double findpower(int a, int b)

return (b==0)? 1:a*findpower(a,b-1);

void calculate()
{

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

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

void display()

System.out.println("sum="+ sum);

public static void main()

System.out.println( " Please enter the constant then the number of terms
" );

SeriesSum obj = new SeriesSum(sc.nextInt() , sc.nextInt());

obj.calculate();

obj.display();

Variable Type Description

x int Stores input from user

sum double Stores sum of series


i int Counter variable

Algorithm 
The program takes input from the user in form of a constant and the total
number of terms in the series and the input is taken first.

Then using a for loop the sum of the series is calculated. A function is
used to find the power to which the constant is to be raised and another
function the factorial of the divisor is calculated.

Then the sum is displayed .


Program 26 
A class Palin has been defined to check whether a positive number is a
Palindrome number or not.

The number ‘N’ is palindrome if the original number and its reverse are
the same.

Some of the members of the class are given below:

Class name: Palin

Data members/instance variables:

num: integer to store the number

revnum: integer to store the reverse of the number

Methods/Member functions:

Palin(): constructor to initialize data members with legal initial values

void accept(): to accept the number

int reverse(int y): reverses the parameterized argument ‘y’ and stores it
in revenue using a recursive technique
void check(): checks whether the number is a Palindrome by invoking
the function reverse() and display the result with an appropriate
message

Specify the class Palin giving the details of the constructor (), void
accept(), int reverse(int) and void check(). Define the main() function to
create an object and call the functions accordingly to enable the task.

import java.io.*;

class Palin {

static int num;

int revnum;

Palin() {

num = 0;

revnum = 0;

void accept() throws IOException {

BufferedReader y = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter the Number:");

String a = y. readLine();

num = Integer.parseInt(a);

int reverse(int i) {

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


{

if( i%j == 0 )

return 0 ;

return 1 ;

void check( int i ){

int a = 0 ;

int temp = i ;

while ( temp != 0 )

a = temp%10 + a*10 ;

temp = temp/10 ;

if( i == a )

System.out.println("\n Number is palindrome");

else

System.out.println("\n Number is not palindrome");

public static void main(String args[]) throws IOException {

Palin p = new Palin();

p.accept();

p.check( num );
}

Variable Type Description

num int Stores input from user

revnum int Stores reversed number

y BufferedRea Takes input from keyboard


der

a String Stores initial input from BufferedReader

i int Counter variable

temp int Temporary work copy of num

a int Stores intermediate values while


computing reverse of num

Algorithm 
The program takes a number as input.

The program uses a for loop to check weather a number is palindrome


or not
​ Program 27 
A class Adder has been defined to add any two accepted times.

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

Class name: Adder

Data member/instance variable:

a[ ]: integer array to hold two elements (hours and minutes)

Member functions/methods:

Adder (): constructor to assign 0 to the array elements

void read time (): to enter the elements of the array

void addtime (Adder X, Adder Y): adds the time of the two parameterized
objects X and Y and stores the sum in the current calling object

void disptime(): displays the array elements with an appropriate


message (i.e., hours= and minutes=)

Specify the class Adder giving details of the constructor( ), void read
time( ), void addtime(Adder, Adder) and void disptime(). Define the
main() function to create objects and call the functions accordingly to
enable the task.

import java.util.Scanner;

class Adder {
int a[];

Adder() {

a = new int[2];

void read time() {

Scanner sc = new Scanner( System.in ) ;

System.out.println("Enter hour:");

a[0] = sc.nextInt();

System.out.println("Enter minute :");

a[1] = sc.nextInt();

void addtime(Adder X, Adder Y) {

int hour1 = X.a[0];

int min1 = X.a[1];

int hour2 = Y.a[0];

int min2 = Y.a[1];

int hourSum = hour1 + hour2;

int minSum = min1 + min2;

a[0] = hourSum + (minSum/60);

a[1] = minSum%60;

void disptime() {

System.out.println("Their sum is-");


System.out.println("hours =" + a[0] +" minutes =" + a[1]);

public static void main(String args[ ]){

Adder obj1 = new Adder();

Adder obj2 = new Adder();

Adder sumObj = new Adder();

obj1.read time();

obj2.read time();

sumObj.addtime(obj1, obj2);

sumObj.disptime();

Variable Type Description

a[] int array Stores hour and minute

hour1 int Stores time from both objects

hour2

min1

min2
Algorithm 

Adder 
The program takes input in the form of time, hours and minutes.

The sum is calculated using a formula related to the 60 min hour format.

The main class creates two objects of Adder type and uses the add time
function of the object it’s part of that takes objects of type Adder as
actual parameters .
BIBLIOGRAPHY 

o https://​www.google.com​/ 

o Computer Science with JAVA 


- Sumitra Arora 

You might also like