0% found this document useful (0 votes)
14 views67 pages

Project 1-1

The document provides a detailed description of several programming tasks, including algorithms and Java programs for finding saddle points in a matrix, adding polynomials, rearranging vowels and consonants in a sentence, and replacing words in a sentence. Each task includes a step-by-step algorithm, Java code implementation, and variable/method description tables. The document serves as a comprehensive guide for implementing these programming challenges.

Uploaded by

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

Project 1-1

The document provides a detailed description of several programming tasks, including algorithms and Java programs for finding saddle points in a matrix, adding polynomials, rearranging vowels and consonants in a sentence, and replacing words in a sentence. Each task includes a step-by-step algorithm, Java code implementation, and variable/method description tables. The document serves as a comprehensive guide for implementing these programming challenges.

Uploaded by

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

Q1. Write a program to input values in a matrix. Find out the saddle points.

(Position wise highest of row = Position wise lowest of column).

ALGORITHM

1. Begin.
2. Declare memory variables(n,fl,jcp,rp).
3. Display "Enter size of matrix".
4. Take input of size in n.
5. Declare a matrix a of size n.
6. Initialize fl to zero.
7. Display "Enter numbers".
8. Initialize i to 0.
9. To run a loop continue steps 9 to 14 if i is less than n otherwise go to step 15.
10. Initialize j to 0.
11. To run a loop continue steps 12 to 13 if j is less than n otherwise go to step 14.
12. Take input of a number and store it in the ith row and jth column of the matrix.
13. Increase the value of j by 1.
14. Increase the value of i by 1.
15. Display "Original matrix".
16. To run a loop continue steps 17 to 21 if i is less than n otherwise go to step 22.
17. Initialize j to 0.
18. To run a loop continue steps 19 to 20 if j is less than n otherwise go to step 21.
19. Display the element present in ith row and jth coloumn of the matrix.
20. Increase the value of j by 1.
21. Increase the value of i by 1.
22. Initialize i by zero.
23. To run a loop continue steps 23 to 33 if i is less than n otherwise go to step 34.
24. Initialize j by 0 ,cp,rp by 0, min by the element in 0th row and ith column and rpos
by i.
25. To run a loop continue steps 26 to 27 if j is less than n otherwise go to step 28.
26. If the element in jth row and ith column is less than min, initialize min by that
element and rp by j.
27. Increase the value of j by 1.
28. Initialize max by the element 'rp'th row and 0th column.
29. To run a loop continue steps 30 to 31 if k less than n otherwise go to step 32.
30. If the element in rth row and kth column is greater than max or the element is
equal to max and fl is equal to 1, initialize max by that element and cp by k.
31. Increase the value of k by 1.
32. If max is equal to min display the element along with its row and column position
and store 1 in fl.
33. Increase the value of i by 1.
34. If fl is equal to zero display "No saddle points".
35. End.
PROGRAM

import java.util.*;
class Project1{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);//Object of Scanner class creation
System.out.println("Enter size of matrix");
int n=sc.nextInt();//Inputs the size of the matrix
int a[][]=new int[n][n];//Array declaration
int fl=0;//Flag variable initialisation
System.out.println("Enter "+(n*n)+" numbers");
for(int i=0;i<n;i++)//Array initialisation
for(int j=0;j<n;j++)
a[i][j]=sc.nextInt();
//Display original matrix
System.out.println("Original matrix\n");
for(int i=0;i<n;i++){//Original matrix printing
for(int j=0;j<n;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
for(int i=0;i<n;i++){//Saddle point checking
int cp=0;int rp=0;
int min=a[0][i],rpos=i;
for(int j=1;j<n;j++)
if(a[j][i]<min ){
min=a[j][i];
rp=j;
}
int max=a[rp][0];
for(int k=1;k<n;k++)//Saddle point checking
if(a[rp][k]>max ||(a[rp][k]==max && fl==1)){
max=a[rp][k];
cp=k;
}
if(max==min){//Saddle point checking and printing
System.out.println("R = "+rp+", C = "+cp+" ,Value = "+max);
fl=1;
}
}
if(fl==0)System.out.println("No saddle points");
}//End of main
}//End of program
VARIABLE DESCRIPTION TABLE

Variable Datatype Scope Purpose


name
n int Store size of matrix
fl int Flag variable
cp int main() Store column
position of saddle
point
rp int Store row position
of saddle point

METHOD DESCRIPTION TABLE

Return type Signature Purpose


void main(String[] args) To find saddle points of
the matrix

OUTPUT
Q2. Write a program to input 2 polynomials in 2 1D arrays. Then add them.

ALGORITHM

1. Begin.
2. Declare memory variables(d1,d2,i,max,coeff1,coeff2).
3. Display "Enter the degree of the first polynomial".
4. Input the degree in d1.
5. Declare array(p1[]) of size d1+1;
6. Display "Enter coefficients for the first polynomial(from lowest to highest):".
7. Initialize i with 0.
8. To run a loop continue steps 9 to 11 if i is less than or equal to d1 otherwise go to
step 12.
9. Display "Coefficient of x^",i and ": ".
10. Input decimal value in p1[i].
11. Increase the value of i by 1 and go to step 8 to continue the loop.
12. Display "Enter the degree of the second polynomial".
13. Input the degree in d2.
14. Declare array(p2[]) of size d2+1;
15. Display "Enter coefficients for the second polynomial(from lowest degree to
highest):".
16. Initialize i with 0.
17. To run a loop continue steps 18 to 20 if i is less than or equal to d2 otherwise go
to step 21.
18. Display "Coefficient of x^",i and ": ".
19. Input decimal value in p2[i].
20. Increase the value of i by 1 and go to step 17 to continue the loop.
21. Calculate maximum between d1 and d2 and store in max.
22. Declare array(pf[]) of size max+1;
23. Initialize i with 0.
24. To run a loop continue steps 25 to 28 if i is less than or equal to max otherwise
go to step 29.
25. If value of i is less than or equal to d1 store p1[i] in coeff1 otherwise store zero in
coeff1.
26. If value of i is less than or equal to d2 store p2[i] in coeff2 otherwise store zero in
coeff2.
27. Add coeff1 and coeff2 and store the resultant value in pf[i];
28. Increase the value of i by 1 and go to step 24 to continue the loop.
29. Display "Resultant Polynomial:".
30. Initialize i with max.
31. To run a loop continue steps 32 to 33 if i is greater than or equal to zero
otherwise go to step 34.
32. If pf[i] is not equal to 0.
i) If i is equal to zero display pf[i],"x^" otherwise display pf[i],"x^",i and " + ".
33. Reduce the value of i by 1 and go to step 31 to continue the loop.
34. End.

PROGRAM

import java.util.*;
class Pro2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);//Object of scanner class creation
System.out.print("Enter the degree of the first polynomial: ");
int d1 = sc.nextInt();//Input of the degree of the first polynomial
double p1[] = new double[d1+1];//Array declaration
System.out.println("Enter coefficients for the first polynomial (from lowest
degree to highest):");
for (int i = 0;i<=d1;i++) //Array intialization
{
System.out.print("Coefficient of x^" + i + ": ");//Printing in polynomial format
p1[i] = sc.nextDouble();
}
System.out.print("Enter the degree of the second polynomial: ");
int d2 = sc.nextInt();//Input of the degree of the first polynomial
double p2[] = new double[d2+1];//Array declaration
System.out.println("Enter coefficients for the second polynomial (from lowest
degree to highest):");
for (int i = 0;i<=d2;i++) //Array initialization
{
System.out.print("Coefficient of x^" + i + ": ");//Printing in polynomial format
p2[i] = sc.nextDouble();
}
int max = Math.max(d1,d2);//Determining larger value
double pf[] = new double[max+1];//Array declaration
double coeff1,coeff2;
for (int i = 0;i<=max;i++) //Sum calculation
{
if(i<=d1)
coeff1 = p1[i];
else
coeff1 = 0;
if(i<=d2)
coeff2 = p2[i];
else
coeff2 = 0;
pf[i] = coeff1 + coeff2;
}
System.out.println("Resultant Polynomial:");
for (int i = max;i>=0;i--) //Printing of resultant polynomial
{
if (pf[i]!=0)
{
if(i==0)
System.out.print(pf[i] + "x^"+ i);
else
System.out.print(pf[i] + "x^"+ i + " + ");
}
}
}//End of main
}//End of class
VARIABLE DESCRIPTION TABLE

Variable Datatype Scope Purpose


name
d1 int Degree of the first polynomial
d2 int Degree of the second polynomial
i int Loop variable
max int main() Stores max between d1 and d2
coeff1 int Stores coefficient from first polynomial
coeff2 int Stores coefficient from second polynomial

METHOD DESCRIPTION TABLE

Return type Signature Purpose


void main(String[] args) To find sum of two
polynomials.

OUTPUT
Q3. Write a program to input a sentence. Bring all the vowels of each word in
front and consonants at the back of each word. Print a new sentence.

ALGORITHM

1. Begin.
2. Declare memory variables(s,w,v,vow,c,i,j).
3. Display "Enter a sentence".
4. Input a sentence in s.
5. Add a space after s.
6. Initialize w,v and c with "".
7. Store "AEIOUaeiou" in vow.
8. Initialize i with 0.
9. To run a loop continue step 10 if i is less than the length of s otherwise go to step
11.
10. If the character at i position of s is not equal to space then add the character to w
and store the result in w
otherwise
i) Initialize j with 0.
ii) To run a loop continue step a if j is less than the length of w otherwise go to
step iii.
a) If the character at j position of w is present in vow then add the character to v
and store the result in v
otherwise add the character to c and store the result in c.
iii) Concatenate v,c and " " and display in a single line.
iv) Store "" in v,c and w.
11. Display "" and move the cursor to the next line.
12. End.

PROGRAM

import java.util.*;
class Vowel
{
public void main(String[] args)
{
Scanner sc= new Scanner (System.in);
System.out.println("Enter a sentence");
String s= sc.nextLine();//Inputs sentence from user
s=s+" ";
String w="",v="",c="";
String vow="AEIOUaeiou";
for(int i=0;i<s.length();i++)//Word extraction
{
if (s.charAt(i)!=' ')
{
w=w+s.charAt(i);
}
else
{
for(int j=0;j<w.length();j++)//Vowel checking
{
if(vow.indexOf(w.charAt(j))>-1)
{
v=v+w.charAt(j);
}
else
{
c=c+w.charAt(j);
}
}
System.out.print(v+c+" ");
v="";
c="";
w="";
}}
System.out.println();
}//End of main
}//End of class

VARIABLE DESCRIPTION TABLE


Variable name Datatype Scope Purpose
s String original sting
w String to extract words
v String to store vowel part
c String to store consonant
part
vow String main() to store all vowels
i int outer loop control
j int inner loop control
METHOD DESCRIPTION TABLE
Return Type Signature Purpose
void main(String[] args) to encode original
sentence

OUTPUT
Q4. Write a program to input a sentence. Input a word to replace and input
second word by which it will be replaced. Perform replacement in the two
following processes:
Input : This is a pen
Output : i) This was a pen.
ii) Thwas was a pen.

ALGORITHM

1. Begin.
2. Declare variables(s,sword,rword,x,t)
3. Display "Enter a sentence".
4. Store the sentence in s.
5. Display "Enter word to replace".
6. Store the word in sword.
7. Display "Enter new word".
8. Store the word in rword.
9. Initialize i with zero.
10. To run a loop continue steps 11 to 13 if i is less than length of the sentence
otherwise go to step 14.
11. Extract a character and store it in ch.
12. If ch is not equal to space(' '), add ch to t
otherwise
i. If t is equal to sword, store rword in t.
ii. Concatenate t with x.
iii. Store "" in t.
13. Increase i by 1 and go back to step 10.
14. Display the new sentence x.
15. Initialize c with 0.
16. To run an infinite loop continue step 17.
17. Store the position in s where sword has been found.
18. If l is equal to -1 go to step 21.
19. Extract the part of s from 0 to (l-1) and concatenate it to rword. Extract part of s
from (l + length of sword).
and concatenate the whole and store in s.
20. Store length of rword +l in c.
21. Display s.
22. End.
PROGRAM

import java.util.Scanner;
class Pro5{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();//Inputs string from user
System.out.println("Enter word to replace");
String sword=sc.next();//Inputs the word which has to be replaced
System.out.println("Enter new word");
String rword=sc.next();//Inputs the word which will replace it
String x="",t="";
s=s+" ";
for(int i=0;i<s.length();i++){//Word extraction
char ch=s.charAt(i);
if(ch!=' ')
t=t+ch;
else{
if(t.equals(sword))//checks if the word is equal to the word which has to be replaced
t=rword;
x=x+t+" ";
t="";
}
}
System.out.println(x);
int c=0;
while(true)//New sentence formation
{
int l=s.indexOf(sword,c);
if(l==-1)
break;
s=s.substring(0,l)+rword+s.substring(l+sword.length());
c=l+rword.length();
}
System.out.println(s);
}//End of main
}End of class
VARIABLE DESCRIPTION TABLE

Variable Data type Scope Purpose


name
s String To store the sentence
sword String To store search word
rword String To store word to replace
with
x String To store new sentence
i int main() Store index of search
word in the sentence
ch char Extract characters from
the sentence

METHOD DESCRIPTIONTABLE

Return Type Signature Purpose


void main(String[] args) To enter a sentence and
print it by replacing a word
with another word

OUTPUT
Q5. Write a program to design a class with the following methods:
i) void dudeneyNumber(int n) [512 => 5 + 1 + 2 = 8, and 512 = 8^3]
[Generalization: (sum of digits)t^3 == original number]
ii)void armstrong(int a, int b) [Get all Armstrong numbers from a to b]
iii)boolean fibonacci(int n) [Check if n is Fibonacci term or not ]

ALGORITHM

Algorithm for void dudeneyNumber(int n)


1. Begin.
2. Declare memory variables(copy,s,r).
3. Store the value of n in copy.
4. Initialize s with 0.
5. To run a loop continue steps 6 to 9 if n is greater than 0 otherwise go to step 10.
6. Divide copy by 10 and store the remainder in r.
7. Add r to s and store the result in s.
8. Divide copy by 10 and store the quotient in copy.
9. Go to step 5.
10. If the cube of s is equal to n display n and "is a Dudeney Number"
other display n and "is not a Dudeney Number".
11. End of method.
Algorithm for void Armstrong(int a,int b)
1. Begin.
2. Display "Armstrong number between",a,"and",b,"are:".
3. Initialize i with the minimum value between a and b.
4. To run a loop continue steps 5 to 16 if is less than the maximum value between a
and b
otherwise go to step 17.
5. Initialize n and copy with i and c and s with 0.
6. To run a loop continue steps 7 to 9 if copy is greater than 0 otherwise go to step
10
7. Increase the value of c by 1.
8. Divide copy by 10 and store the quotient in copy.
9. Go to step 6 to continue the loop.
10. To run a loop continue steps 11 to 14 if n is greater than 0 otherwise go to step
15
11. Divide n by 10 and store the remainder in r.
12. Raise r to the power of c, add the result to s and store the entire result in s.
13. Divide n by 10 and store the quotient in n.
14. Go to step 10 to continue the loop.
15. If s is equal to then display i and " " in a single line.
16. Increase the value of i by 1 and go to step 4 to continue the loop.
17. End of method.
Algorithm for Boolean fibonacci(int n)
1. Begin
2. Declare memory variables(int a,b,temp).
3. Initialize a with 0 and b with 1.
4. To run a loop continue steps 5 to 8 if a is less than n otherwise go to step 9.
5. Store a in temp.
6. Store b in a.
7. Store the sum of temp and b in b.
8. Go to step 4 to continue the loop.
9. If a is equal to n return True otherwise return False.{End of method}

PROGRAM

class Pro5
{
void dudeneyNumber(int n)//Checks if n is a dudeney number or not
{
int copy = n;//Copy variable
int s = 0;
while(copy>0)//Sum of digits calculation
{
int r = copy%10;
s = s + r;
copy = copy/10;
}
if((s*s*s)==n)//Checks if the cube of each digit is equal to the number or not
System.out.println(n + " is a Dudeney Number");
else
System.out.println(n + " is not a Dudeney Number");
}
void armstrong(int a, int b)//Prints all the Armstrong no.s between a and b
{
System.out.println("Armstrong numbers between " + a + " and " + b + " are:");
for(int i = Math.min(a,b);i<=Math.max(a,b);i++)//Armstrong no. printing
{
int n = i, copy = i, c = 0, s = 0;
while(copy>0)//No. of digits calculation
{
c++;
copy = copy/10;
}
while(n>0)//Raising each digit to the power of the no. of digits
{
int r = n%10;
s = s + (int)Math.pow(r,c);
n = n/10;
}
if(s==i)//checks if the sum is equal to the original number
System.out.print(i + " ");
}
}
Boolean fibonacci(int n)//Checks if n is a Fibonacci number or not
{
int a = 0,b = 1;
while(a<n)//Fibonacci checking
{
int temp = a;
a = b;
b = temp + b;
}
return (a==n);//Returns the result to method call
}
}//End of class.
VARIABLE DESCRIPTION TABLE

Variable name Datatype Scope Purpose


copy int dudeneyNumber () Copy variable
n int dudeneyNumber() Original number
s int dudeneyNumber () Sum of digits
r int dudeneyNumber() Temporary variable
for digit extraction
a int fibonacci () Starting range for
Armstrong numbers
b int fibonacci () Ending range for
Armstrong numbers
i int fibonacci () Loop variable for
Armstrong numbers
n int fibonacci() To store current
value of i
copy int fibonacci() Copy variable
c int fibonacci () Count of digits in
the current number
r int fibonacci () Temporary variable
for digit extraction
s int fibonacci() Sum calculation
a int fibonacci() Fibonacci series
calculation
b int fibonacci() Fibonacci series
calculation
n int fibonacci() Original number
temp int fibonacci() Temporary variable

METHOD DESCRIPTION TABLE

Return Type Signature Purpose


void dudeneyNumber (int n) Checks if the given number is a
Dudeney number or not

void armstrong(int a,int b) Prints Armstrong numbers in the


range [a, b].

boolean fibonacci (int n) Checks if the given number is a


Fibonacci number and returns true if
it is, false otherwise.

OUTPUT
6. Design a class Number
with the following: Data
members: int n, rev, p;
Constructors: Default, Number(int) – To
initialize the data members. Methods:
i)void reverse() – Will reverse the number n by
recursion.
ii) void check() – Will check n is palindrome or
not.
Create object in main() Method and perform
palindrome checking.

ALGORITHM

A) Begin.
B) Declare data members(n,rev,p).
C) Algorithm for Default constructor
1. Begin
2. Initialize n,rev and p with 0.
3. End of Default constructor.
D) Algorithm for Parameterized constructor
1. Begin.
2. Initialize n with no.
3. End of Parameterized constructor.
E) Algorithm for void reverse()
1. Begin.
2. If n is equal to 0 then return to method call
otherwise
i) Divide n by 10 and add the remainder to rev multiplied by 10 and store the result
in rev.
ii) Divide n by 10 and store the quotient in n.
iii) Recursively call reverse() method.
3. End of method.
F) Algorithm for void check()
1. Begin.
2. Declare memory variable(copy)
3. Store the value of n in copy.
4. Call reverse() method.
5. If copy is equal to rev then display "Palindrome number"
otherwise display "Not Palindrome number".
6. End of method.
G) Algorithm for void main()
1. Begin.
2. Create an object ob1 of class Number.
3. Display "Enter number to be checked".
4. Input integer type value in no.
5. Create an object ob2 of class Number with no as parameter.
6. Call check() method on object ob2.
7. End of method.
H) End of program.

PROGRAM

import java.util.*;
class Number
{
int n, rev, p;
Number()//Default constructor
{
n = 0; rev = 0; p = 0;
}
Number(int no)//Parameterized constructor
{
n = no;
}
void reverse()//Reverses the number
{
if(n==0)
return;
else
{
rev = (rev * 10) + (n%10);
n/=10;
reverse();//Recursive call
}
}
void check()//Palindrome number checking
{
p = n;
reverse();//Reverse() method call
if(p==rev)
System.out.println(“Palindrome number”);
else
System.out.println(“Not Palindrome number”);
}
void main()
{
Scanner sc=new Scanner(System.in);
Number ob1 = new Number();//Object creation
System.out.println(“Enter number to be checked”);
int no = sc.nextInt();
Number ob2 = new Number(no);//Number input
ob2.check();//Calling of check() method
}//End of main
}//End of class

VARIABLE DESCRIPTION TABLE

Variable name Datatype Scope Purpose


n int Data member to
Class store entered
number
rev int Data member to
store reverse of the
entered number
p int Data member used
as a copy variable
no int main() Inputs number from
user

METHOD DESCRIPTION TABLE

Return type Signature Purpose


void reverse() Reverses the entered
number recursively
void check() Checks if the entered
number is a palindrome
number or not.
void main() Creates object and calls
the necessary methods.

OUTPUT
7. Write a program to design the
following
class Number2: Data members: int n, p,
c, s;
Constructors: 3 constructor (2 parameterized[1 parameter and 2
parameter] and 1 default)
Methods:
void calculate1() – Will calculate the sum of the cube of digits of the
number (recursively).
void check1() – Will check the number is Armstrong or not.
void count() – Will count no. of digits of p by recursion.
void check2() – Will print all automorphic numbers present in
range 10-100 recursively.
void main(): Print a menu i) Armstrong ii) Automorphic
Input the number, create an object and call proper
method to check Armstrong and for Automorphic create object with 2 values

ALGORITHM

A) Begin.
B) Declare data members(n,p,c,s)
C) Algorithm for Default constructor
1. Begin.
2. Initialize n,p,c and s with 0.
3. End
D) Algorithm or Parameterized constructor
1. Begin.
2. Initialize n and p with the passed parameter and c and s with 0.
3. End of parameterized constructor
E) Algorithm for void calculate1()
1. Begin
2. Declare memory variable(d).
3. If n is greater than 0
i) Divide n by 10 and store the remainder in d.
ii) Divide n by 10 and store the quotient in n.
iii) Calculate the cube of d, add it to s and store the result in s.
iv) Recursively call calculate1() method.
4. End of method.
F) Algorithm for void check1()
1. Begin.
2. Initialize p with n.
3. Call calculate1() method.
4. If s is equal to p then display "Armstrong no."
otherwise display "Not an Armstrong no.".
5. End of method.
G) Algorithm for count()
1. Begin.
2. If p is equal to 0 then return to method call
otherwise
i) Increase c by 1.
ii) Divide p by 10 and store the quotient in p.
iii) Recursively call count() method.
3. End of method.
H) Algorithm for check2()
1. Begin.
2. Declare memory variables(q,r,x).
3. If s is greater than 100 then return to method call
otherwise
i) Initialize c with 0 and p with s.
ii) Call count() method.
iii) Initialize q with c.
iv) Calculate the square of s and store the result in p.
v) Initialize c with 0.
vi) Call count() method.
vii) Initialize r with c.
viii) Declare a variable x of integer type value.
ix) If the modulus division of r by 2 gives result 0
then divide the square of s by 10 raised to the power of r-q and store the
remainder in x
otherwise divide the square of s by 10 raised to the power of r-q+1 and store the
remainder in x.
x) If x is equal to s then display s and a blank space.
xi) Increase the value of s by 1 and store the result in s.
xii) Recursively call check2() method.
4. End of method.
I) Algorithm for void main()
1. Begin.
2. Declare memory variables(op,no).
3. Display "1. Armstrong" and "2. Automorphic" in two separate lines.
4. Display "Enter an option".
5. Input an integer type value in op.
6. Create an object obj of class Number2.
7. If op is equal 1 then
i) Display "Enter a number".
ii) Input an integer type value in no.
iii) Store no in n variable of object obj of class Number2.
iv) Call check1() method.
else if op is equal to 2 then
i) Initialize s with 1.
ii) Call check2() method
otherwise display "Wrong input".
8. End of method.
J) End of program.
PROGRAM

import java.util.*;
class Number2
{
int n,p,c,s;
Number2()//Default constructor
{
n=p=c=s=0;
}
Number2(int n)//Parameterized constructor
{
this.n=n;
p=n;
c=s=0;
}
void calculate1()//Calculates cube of digits of no.s recursively
{
if(n>0)//Digit extraction and calculation
{
int d=n%10;
n=n/10;
s=s+(d*d*d);
calculate1();
}
}
void check1()
{
p=n;
calculate1();
if(s==p)
System.out.println("Armstrong no.");
else
System.out.println("Not an Armstrong no.");
}
void count()
{
if(p==0)
return;
else
{
c=c+1;
p=p/10;
count();
}
}
void check2()
{
if(s>100)
return;
else
{
c=0;
p=s;
count();
int q=c;
p=s*s;
c=0;
count();
int r=c;
int x;
if(r%2==0)
x=(s*s)%(int)Math.pow(10,r-q);
else
x=(s*s)%(int)Math.pow(10,r-q+1);
if(x==s)
{
System.out.print(s + " ");
}
s=s+1;
check2();
}
}
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("1.Armstrong\n2.Automorphic");
System.out.println("Enter an option");
int op=sc.nextInt();
Number2 obj=new Number2();
if(op==1)
{
System.out.println("Enter a number");
int no=sc.nextInt();
obj.n=no;
check1();
}
else if(op==2)
{
s=10;
check2();
}
else
System.out.println("Wrong input");
}
}
VARIABLE DESCRIPTION TABLE

Name Data Type Scope Purpose


n int class Store a number
p int class Store copy of the
number
c int class Counter to count
no. of digits
s int class Run a loop from
one to hundred
using recursion
op int main() Store choice
entered by user
no int main() Enter a number
from the user

METHOD DESCRIPTION TABLE

Return type Signature Purpose


void calculate1() It will calculate sum of the
cube of the digits of the
number recursively.
void check1() It will check if the number
is an Armstrong number or
not.
void count() It will calculate the number
of digits of p by recursion
void check2() It will all the Automorphic
numbers between 10 to
100 recursively
void main() It will create a menu to
check if a number is an
Armstrong number or not
or to print all the
Automorphic numbers in
the range 10-100
according to the entered
option
OUTPUT
8. Design a class Sentence with the following: Data members:
String a, b, wd[];
Constructor (Parameterized): Will store value of ‘a’, calculate no.
of words, and will create array wd[].
Methods:
void extract() – Extract words of a in wd[].
void change1() – Will change each word in piglatin form in the
wd[] and will frame a sentence by the piglatin words, and print it.
[example : owl -> owl, sky -> skyay, student -> udentstay ]
void change2() – Will change each word of sentence present in ‘a’
as follows – all the vowels will be at front and consonants at back
by modify() method. Create new sentence by these modified
words in b and print it.
String modify(String) – Will arrange vowels and consonants
as follows:
apple -> aelpp (of course recursively)
Create main() method and do necessary changes.

ALGORITHM

A) Begin.
B) Declare data members(a,b) which will contain words
C) Declare array (wd[])
D) Algorithm for parameterized constructor
1. Begin
2. Declare memory variable(c,i).
3. Initialize a with s.
4. Add a blank space to a.
5. Initialize c and i with 0.
6. To run a loop continue steps 6 to 7 if is less than the length of a otherwise go to
step 8.
7. If the character at i position of the sentence a is a blank space then increase the
value of c by 1.
8. Increase the value of i by 1 and go to step 5 to continue the loop.
9. Create an array wd[] of size c.
10. End of parameterized constructor.
E) Algorithm for void extract()
1. Begin.
2. Declare memory variables(word,x,i).
3. Initialize word with "",x with 0 and i with 0.
4. To run a loop continue steps 5 to 6 if the value of i is less than the length of a
otherwise go to step 7.
5. If the character at i position of a is not equal to a blank space then concatenate
the character to word and store in word
otherwise
i) Store word in the x position of wd[].
ii) Initialize word with "".
iii) Increase the value of x by 1.
6. Increase the value of by 1 and go to step 4 to continue the loop.
7. End of method.
F) Algorithm for void change()
1. Begin.
2. Declare memory variables(v,x,i,t,p,j).
3. Initialize v with "AEIOUaeiou",x with "" and i with 0.
4. To run a loop continue steps 5 to 12 if i less than the length of wd otherwise go to
step 13.
5. Store the word at i position of wd in t.
6. Initialize p and i with 0.
7. To run a loop continue steps 8 to 10 if j is less than the length of t otherwise go to
step 11.
8. Find the position of the character which appears at j position of t in the variable v
and store the result in p.
9. If p is not equal to -1 then move the control out of the loop.
10. Increase the value of j by 1 and go back to step 7 to continue the loop.
11. If p is equal to -1 then concatenate x,t and "ay" and store the result in x
otherwise if j is equal to 0 then concatenate x,t and a blank space in x
otherwise concatenate x, all the letters extracted from j position of t till the end, all
the letters extracted from
0 position of t till j and "ay" and store in x.
12. Increase the value of i by 1 and go back to step 4 to continue the loop.
13. Display "Pig Latin Form:" and x.
14. End of method.
G) Algorithm for void change2()
1. Begin.
2. Declare memory variable(i).
3. Initialize b with "" and i with 0.
4. To run a loop continue steps 5 to 6 if i is less than the length of wd otherwise go to
step 7.
5. Call modify() method with the word at i position of wd as parameter, concatenate it
with b and a blank space and
store the result in b.
6. Increase the value of i by 1 and go to step 4 to continue the loop.
7. Display "Modified sentence =" and b.
8. End of method.
H) Algorithm for String modify(String s)
1. Begin.
2. Declare memory variables(v,i,t,t1).
3. Store "AEIOUaeiou" in v.
4. Initialize i with 0.
5. To run a loop continue steps 6 to 7 if i is less than the length of s otherwise go to
step 8.
6. If the position of the character,at i position of s, of v is not equal to -1 then
i) Extract all the letters from i position of s till the i+1 position of s and store in t.
ii) Concatenate all the letters extracted from 0 position of s till the i position of s
with all the letters extracted
from i+1 position of till the end and store in t1.
iii) Return t concatenated with the recursive call of modify with t1 as parameter.
7. Increase the value of i by 1 and go back to step 5 to continue the loop.
8. Return s.
9. End of method.
I) Algorithm for void main()
1. Begin.
2. Display "Enter a sentence".
3. Input a sentence in s.
4. Create an object ob of class Sentence with s as parameter.
5. Call extract(), change1() and change2() methods of class ob.
6. End of method.
J) End of program.

PROGRAM

import java.util.*;
class Sentence
{
String a,b,wd[];
// Constructor to initialize the sentence and count the number of words
Sentence(String s)
{
a = s;
a = a + " ";
int c = 0;
for(int i = 0;i<a.length();i++)
{
if(a.charAt(i)==' ')
c++;
}
wd = new String[c];
}
// Method to extract words from the sentence and store them in an array
void extract()
{
String word = "";
int x = 0;
for(int i = 0;i<a.length();i++)
{
if(a.charAt(i)!=' ')
word = word + a.charAt(i);
else
{
wd[x++] = word;
word = "";
}
}
}
// Method to convert the sentence to Pig Latin
void change1()
{
String v = "AEIOUaeiou", x = "";
for (int i = 0; i < wd.length; i++)
{
String t = wd[i];
int p=0;int j=0;
for (; j < t.length(); j++)
{
p = v.indexOf(t.charAt(j));
if (p != -1)
break;
}
if (p == -1 )
{
x = x + t+"ay ";
}
else if(j==0)
{
x=x+t+" ";
}
else
{
x = x + t.substring(j) + t.substring(0, j) + "ay ";
}
}
System.out.println("Pig Latin Form: " + x);
}
void change2()
{
b = "";
for(int i = 0;i<wd.length;i++)
{
b = b + modify(wd[i]) + " ";
}
System.out.println("Modified sentence = " + b);
}
String modify(String s)
{
String v="AEIOUaeiou";
for(int i=0;i<s.length();i++)
{
if(v.indexOf(s.charAt(i))!=-1)
{
String t=s.substring(i,i+1);
String t1=s.substring(0,i)+s.substring(i+1);
return (t+modify(t1));
}
}
return s;
}
// Main method to accept input and perform transformations
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sc.nextLine();
Sentence ob=new Sentence(s);
ob.extract();
ob.change1();
ob.change2();
}
}

VARIABLE DESCRIPTION TABLE

Variable name Datatype Scope Purpose


a String Sentence class Original input
sentence
b String Sentence class Modified form of the
sentence
wd String[] Sentence class Array to store words
extracted from 'a'
c int Sentence(String s) To count the
number of words
word String To extract words
x int extract() Index control

v String To store all the


vowels
i int Loop variable
j int change1() Loop variable
p int Stores index
x String Calculates piglatin
form
v String To store all the
vowels
i int Loop variable
t String modify() Temporary variable
t1 String Temporary variable
METHOD DESCRIPTION TABLE

Return type Signature Purpose


void extract() Splits the sentence 'a' into
words and stores them in
the 'wd' array.
void change1() Converts each word in 'wd'
to Pig Latin and prints the
modified sentence.
void change2() Modifies each word in 'wd'
and prints the modified
sentence.
String modify(String s) Moves the vowels at first
and consonants at last.
Returns the modified word.
void main() Creates an instance of the
'Sentence' class, prints the
original sentence, Pig Latin
form, and modified form.

OUTPUT
9. Write a program to create the following class:
Data members: String a, b; int ch; (option 1 or 2)
Constructors: To initialize value of a to store a
sentence and b by “”. Methods:
void encode() – To change the sentence using the following process:
vowels will be replaced by v followed by vowel number. Example: a
-> v1
Consonants will be increase by 3 positions. Resultant consonant
need to be present within a – z (case sensitive).
void display() – Will display both a and b.
void decode() – Will convert encoded text to original form.
Create main() method, input a sentence and enter choice. Will create
object and will call encode and decode methods as necessary.
Example: GOat -> JV4v1w (for encoding) and vice versa.

ALGORITHM

A). Begin
B). Declare data members(a,b,ch).
C) Algorithm for parameterized constructor
1. Begin
2. Initialize a with s, b with "", and ch with 0
3. End of parameterized constructor.
D) Algorithm for void encode()
1. Begin.
2. Declare memory variables(n,i,j,f,vowel).
3. Store the length of a in n.
4. Declare array(arr[]) which will contain characters of size n.
5. Initialize i,j and f with 0.
6. Store "AEIOUaeiou" in vowel.
7. Initialize array(code[]) with "V1","V2","V3","V4","V5".
8. To run a loop continue steps 9 to 10 if i less than n otherwise go to step 11.
9. Store the character at i position of a in the i position of arr.
10. Increase the value of i by 1 and go to step 8 to continue the loop.
11. Initialize i with 0.
12. To run a loop continue steps 13 to 19 if I less than n otherwise go to step 20.
13. Initialize f with 0.
14. Initialize j with 0.
15. To run a loop continue steps 16 to 17 if j is less than 10 otherwise go to step 18.
16. If the character at i position of arr is equal to character at j position of vowel then
i) Concatenate the word at j position of code with b and store the result in b.
ii) Store 1 in f.
iii) Take the control out of the loop.
17. Increase the value of j by 1 and go to step 15 to continue the loop.
18. If f is equal to 0 and the character at i position of arr is a letter then
i) If the character at i position of arr is either- greater than 'A' and less than 'X'- or
greater than 'a' and less than 'x' then
a) Increase the ASCII of the character at i position of arr by 3 and store in the
same position
b) Concatenate the character at i position of arr with b and store the result in b.
ii)otherwise
a) Decrease the ASCII of the character at i position of arr by 23 and store in the
same position.
b) Concatenate b with the character at i position of arr and store in b.
otherwise if f is equal to 0 then
Concatenate b with the character at i position of arr and store in b.
19. Increase the value of i by 1 and go to step 12 to continue the loop.
20. End of method.
E) Algorithm for void decode()
1. Begin.
2. Initialise an array vowel1[] with 'A','E','I','O','U'.
3. Initialise an array vowel2[] with 'a','e','i','o','u'.
4. Initialize n with the length of a.
5. Initialize i and j with zero.
6. Declare array(arr[]), which will contain characters, of size n.
7. To run a loop continue steps 8 to 9 if i is less than n otherwise go to step 10.
8. Store character which is in i position of a in i position of arr[].
9. Increase the value of i by 1 and go to step 7 to continue the loop.
10. To run a loop continue steps 11 to 13 if i is less than n otherwise go to step 14.
11. If the character at i position of arr is greater than 'A' and less than 'Z' then
i) If i is not equal to n-1 and the character at i position of arr is equal to 'V' and the
character at i+1 position of arr is a digit then
a) Remove 0 from the digit at i+1 position of arr and store in pos1.
b) Concatenate b with the character at pos1-1 position of vowel1.
c) Increase i by 2 and store in i.
d) Ignore the rest of the statements and go to the next iteration of the loop.
ii) otherwise
a) If the character at i position of arr is less than or equal to 'C' then increase the
ASCII of the character at i position of arr by 23 and store in that same position and
concatenate that character to b and store in b
b) otherwise subtract 3 from the ASCII of the character at i position of arr and
store in that same position and concatenate that character to b and store in b.
c) Increase the value of i by 1.
12. Otherwise if the character at i position of arr is greater than 'a' and less than 'z'
then
i) If i is not equal to n-1 and the character at i position of arr is equal to 'v' and the
character at i+1 position of arr is a digit then
a) Remove 0 from the digit at i+1 position of arr and store in pos2.
b) Concatenate b with the character at pos2-1 position of vowel2.
c) Increase i by 2 and store in i.
d) Ignore the rest of the statements and go to the next iteration of the loop.
ii) otherwise
a) If the character at i position of arr is less than or equal to 'C' then increase the
ASCII of the character at i position of arr by 23 and store in that same position and
concatenate that character to b and store in b
b) otherwise subtract 3 from the ASCII of the character at i position of arr and
store in that same position and concatenate that character to b and store in b.
c) Increase the value of i by 1.
13. Otherwise concatenate b with the character at i position of arr and store in b and
increase the value of i by 1.
14. End of method.
F) Algorithm for void display()
1. Begin.
2. If ch is equal to 1 call encode() method and display b
3. Otherwise if ch is equal to 2 call decode() method and display b.
4. Otherwise display "Invalid choice".
5. End of method.
G) Algorithm for void main()
1. Begin.
2. Declare memory variable(s).
3. Display "Enter a sentence".
4. Input a sentence in s.
5. Create an object s1 of Pro9 class with s as parameter.
6. Display "Enter choice 1. Encode 2. Decode".
7. Input an integer value in ch variable of s1 object of class Pro9.
8. Call display() method of s1 object.
9. End of method.
H). End of program

PROGRAM

import java.util.*;
class Pro9
{
String a, b; // Variables to store the input sentence and the encoded/decoded sentence
int ch; // Variable to store the user's choice
// Constructor to initialize the sentence and choice
Pro9(String s)
{
a=s;
b="";
ch=0;
}
// Method to encode the sentence
void encode()
{
int n = a.length();
char arr[]=new char[n];
int i,j,f=0;
String vowel="AEIOUaeiou";
String code[]={"V1","V2","V3","V4","V5","v1","v2","v3","v4","v5"};
for(i=0;i<n;i++)
arr[i] = a.charAt(i);
// Encode the sentence
for(i=0;i<n;i++)
{
f=0;
for(j=0;j<10;j++)
{
if(arr[i]==vowel.charAt(j))
{
b+=code[j];
f=1;
break;
}
}
if(f==0&&Character.isLetter(arr[i]))
{
if((arr[i]>='A'&&arr[i]<'X')||(arr[i]>='a'&&arr[i]<'x'))
{
arr[i]+=3;
b=b+arr[i];
}
else
{
arr[i]-=23;
b+=arr[i];
}
}

else if(f==0)
b+=arr[i];
}
}
// Method to decode the sentence
void decode()
{
char vowel1[]={'A','E','I','O','U'};
char vowel2[]={'a','e','i','o','u'};
int n = a.length(), i,j;
char arr[]=new char[n];
for(i=0;i<n;i++)
arr[i] = a.charAt(i);
for(i=0;i<n;)
{
if(arr[i]>='A'&&arr[i]<='Z')
{
if(i!=n-1&&arr[i]=='V'&&Character.isDigit(arr[i+1]))
{
int pos1 = (arr[i+1]-'0');
b+=vowel1[pos1-1];
i+=2;
continue;
}
else
{
if(arr[i]<='C')
{
arr[i]+=23;
b+=arr[i];
}
else
{
arr[i]-=3;
b+=arr[i];
}
i+=1;
}
}
else if(arr[i]>='a'&&arr[i]<='z')
{
if(i!=n-1&&arr[i]=='v'&&Character.isDigit(arr[i+1]))
{
int pos2 = (arr[i+1]-'0');
b+=vowel2[pos2-1];
i+=2;
continue;
}
else
{
if(arr[i]<='c')
{
arr[i]+=23;
b+=arr[i];
}
else{
arr[i]-=3;
b+=arr[i];
}
i+=1;
}
}
else
{
b+=arr[i];
i+=1;
}
}
}
// Method to display the encoded or decoded sentence
void display()
{
if(ch==1)
{
encode();
System.out.println(b);
}
else if(ch==2)
{
decode();
System.out.println(b);
}
else
System.out.println("Invalid Choice");
}
// Main method to accept input and perform encoding or decoding
void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter sentence");
String s = sc.nextLine();
Pro9 s1 = new Pro9(s);
System.out.println("Enter choice : \n1.Encode\n2.Decode");
s1.ch=sc.nextInt();
s1.display();
}
}

VARIABLE DESCRIPTION TABLE

Variable Datat
name ype Scope Purpose

a String Class: Sentence Stores the input sentence.

Stores the result of encoding or


b String Class: Sentence
decoding.

Stores the user's choice (1 for


ch int Class: Sentence
encoding, 2 for decoding).

Senten Class: Sentence Object of the Sentence class used to


s1
ce main process input and display results.

Methods: encode, Stores the length of the input


n int
decode, display sentence.

Methods: encode, Temporary array to store characters


arr char[]
decode, display of the input sentence.

Methods: encode,
i int Loop variable for iterations.
decode, display

Methods: encode,
j int Loop variable for iterations.
decode, display

Flag to check if a character is a


f int Methods: encode
vowel.

vowel String Methods: encode Stores the vowels in the order A, E,


I, O, U, a, e, i, o, u.

Stores the corresponding codes for


code String[] Methods: encode
vowels.

Stores uppercase vowels for


vowel1 char[] Methods: decode
decoding.

Stores lowercase vowels for


vowel2 char[] Methods: decode
decoding.

Scanne
sc Methods: main Scanner object for taking user input
r

METHOD DESCRIPTION TABLE

Return type Signature Purpose

Encodes the input sentence based on vowel and


void encode()
letter shifting rules. Stores the result in b.

Decodes the input sentence, reversing the


void decode()
encoding process. Stores the result in b.

Calls either encode() or decode() based on user


void display()
choice (ch). Prints the result (b) to the console.

Entry point of the program. Takes user input,


void main() creates a Sentence object, and calls display() to
perform encoding or decoding.

OUTPUT
10. Write a program to design the following class:
int a[], b;
void input() – Take input of array elements in a[] and
element to search in b. void linear(int p) – Perform linear
search by recursion.
void bubbleSortOuter(int i) – The
outer loop of bubble sort. void
bubbleSortInner(int j, int k) – The inner
loop of bubble sort.
int bisearch(int lo, int hi) – Will search element by binary search
recursively.
void create() – Create one object. Call input() to input size of
array, elements of array, element to be searched. Then call the
methods. First linear then binary search.

ALGORITHM

A) Begin
B) Declare data members(a[],b)
C) Algorithm for void input()
1. Begin.
2. Declare memory variables(c,i).
3. Display "Enter the size of the array".
4. Input the size in c.
5. Create array a of size c.
6. Display "Enter elements".
7. Initialize i with 0.
8. To run a loop continue steps 9 to 10 if i is less than c otherwise go to step 11.
9. Input a number at i position of a[].
10. Increase the value of i by and go to step 8 to continue the loop.
11. Display "Enter the element to be searched".
12. Input the element in b.
13. End of method.
D) Algorithm for void linear(int p)
1. Begin.
2) If p is equal to the length of a then display b and "not found" and return the control
to method call
otherwise
i) If the number at p position of a is equal to b then display b, "found at index", p
and “by linear search” and return the control to method call
ii) otherwise recursively call linear() with p+1 as parameter.
3. End of method.
D) Algorithm for void bubbleSortOuter(int i)
1. If i is equal to the length of a-1 then return the control to method call.
2. Call bubbleSortInner method with 0 and i as parameters.
3. Recursively call bubbleSortOuter with i+1 as parameter.
4. End of method.
E) Algorithm for void bubbleSortInner(int j, int k)
1. Begin.
2. Declare memory variable(temp).
3. If j is equal to the length of a-k-1 then return the control to method call.
4. If the number at j position of a is greater than the number at j+1 position of a then
i) Store the number at j position of a in temp.
ii) Store the number which is at j position of a in j+1 position of a.
iii) Store temp in j+1 position of a.
5. Recursively call bubbleSortInner() with j+1 and k as parameter.
6. End of method.
F) Algorithm for int bisearch(int lo, int hi)
1. Begin.
2. Declare memory variable(mid).
3. If lo is greater than hi then return -1.
4. Add lo and hi then divide the result with 2 and store in mid.
5. If the number at mid position of a is equal to b then return mid
otherwise if the number at mid position of a is less than b then recursively call
bisearch() with mid+1 and hi as parameter and return it
otherwise recursively call bisearch() with lo and mid-1 as parameter and return it.
6. End of method.
G) Algorithm for void create()
1) Call input() method.
2) Call linear() method with 0 as parameter.
3) Call bubbleSortOuter() method with 0 as parameter.
4) Call bisearch() method with 0 and the length of a as parameter and store the
return value in ans.
5) If ans is equal to -1 then display "Element not found"
otherwise display b, "Element found at index", ans and “by binary search after
sorting”.
6. End of method.
H) End of program.

PROGRAM

import java.util.*;
class Pro10
{
int a[],b; // Declaration of array 'a' and integer 'b'
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array");
int c = sc.nextInt();// Read the size of the array from user
a = new int[c];
System.out.println("Enter elements");
for(int i = 0;i<c;i++)
{
a[i] = sc.nextInt();// Read elements of the array from user
}
System.out.println("Enter the element to be searched");
b = sc.nextInt();
}
void linear(int p)
{
if(p==a.length)
{
System.out.println(b + " not found"); // If end of array is reached and element not found
return;
}
else
{
if(a[p]==b)
{
System.out.println(b + " found at index " + p + " by linear search");
return;
}
else
linear(p+1);
}
}
void bubbleSortOuter(int i)
{
if(i==a.length-1)
return;
bubbleSortInner(0,i);
bubbleSortOuter(i+1);
}
void bubbleSortInner(int j, int k)
{
if(j==a.length-k-1)
return;
if(a[j]>a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
bubbleSortInner(j+1,k);
}
int bisearch(int lo, int hi)
{
if(lo>hi)
return -1;
int mid = (lo+hi)/2;
if(a[mid]==b)
return mid;
else if(a[mid]<b)
return bisearch(mid+1,hi);
else
return bisearch(lo,mid-1);
}
void create()
{
input();// Take input from user
linear(0); // Perform linear search
bubbleSortOuter(0);
int ans = bisearch(0,a.length);
if(ans==-1)
System.out.println("Element not found");
else
System.out.println(b + " found at index " + ans + " by binary search after sorting"); // Element
found by binary search after sorting
}
}

VARIABLE DESCRIPTION TABLE

Variable Name Datatype Scope Purpose


a[] int To store an array
b int Pro10 class To store the
element to be
searched
c int To store the size
input() of the array
i int Loop variable
p int linear(int p) Loop variable
j int Loop variable
k int bubbleSortInner(in Loop variable
temp int t j,int k) To shuffle the
values of two
variables
lo int To store lower limit
hi int To store upper
bisearch(int lo,int limit
mid int hi) To store middle
value
ans int create() To store index
number

METHOD DESCRIPTION TABLE

Return Type Signature Purpose


void input() To input data in variables
void linear(int p) To perform linear search
void bubbleSortOuter(int i) To sort the outer loop
void bubbleSortInner(int j,int k) To sort the inner loop
void bisearch(int lo,int hi) To perform binary search
void create() To create an object and
perform tasks

OUTPUT
11. Write a program to perform the following tasks by recursion:
i) boolean magic(int n) – To check n is magic or not. It will call
sod(int).
ii) int sod(int n) – To calculate sum of digits recursively.
iii) String change(String w)- To increase vowels by 2 position
and consonants by 3 position. (Case sensitive). Perform
the task recursively.
iv) boolean happy (int n) – To check a number is happy or not.
(Sum of square of all digits = 1). It will call sosq (int).
v) int sosq(int n) – To calculate the sum of squares of digits.
vi) String remove (String k) – To remove all vowels from k.
vii) void main () – No object required. Just call the methods.

ALGORITHM

Algorithm for boolean magic(int n)


1) Begin.
2. Declare memory variables(sum).
3. Call sod() method with n as parameter and store the result in sum.
4. If sum is equal to 1 then return true
otherwise if sum is greater than 9 then recursively call magic() method with sum as
parameter
otherwise return false.
5. End of method.
Algorithm for int sod(int n)
1. Begin.
2. If n is equal to 0 then return 0
otherwise return the sum of the remainder of integer division of n by 10 and the
result of the
recursive calling of sod() method with the quotient of integer division of n by 10 as
parameter.
3. End of method.
Algorithm for String change(String w)
1. If the length of w is equal to zero then return "".
otherwise
i) Store the character at 0th position of w in ch.
ii) If ch is greater than or equal to 65 and less than or equal to 87
a) If ch is present in the string "AEIOU" then return the concatenation of the
character conversion of the ASCII of ch+2
and the recursive calling of change method with all the letters extracted from
position 1 to the end of
the sentence w as parameter
otherwise
return the concatenation of the character conversion of the ASCII of ch+3
and the recursive calling of change method with all the letters extracted from
position 1 to the end of
the sentence w as parameter
otherwise if ch is greater than or equal to 97 and less than or equal to 119
a) If ch is present in the string "aeiou" then return the concatenation of the
character conversion of the ASCII of ch+2
and the recursive calling of change method with all the letters extracted from
position 1 to the end of
the sentence w as parameter
otherwise
return the concatenation of the character conversion of the ASCII of ch+3
and the recursive calling of change method with all the letters extracted from
position 1 to the end of
the sentence w as parameter
otherwise
a) If ch is equal to 'X' then return the concatenation of "A" and the recursive
calling of change method with all the letters extracted from position 1 to the end of
the sentence w as parameter.
b) If ch is equal to 'Y' then return the concatenation of "B" and the recursive
calling of change method with all the letters extracted from position 1 to the end of
the sentence w as parameter.
c) If ch is equal to 'Z' then return the concatenation of "C" and the recursive
calling of change method with all the letters extracted from position 1 to the end of
the sentence w as parameter.
d) If ch is equal to 'x' then return the concatenation of "a" and the recursive
calling of change method with all the letters extracted from position 1 to the end of
the sentence w as parameter.
e) If ch is equal to 'y' then return the concatenation of "b" and the recursive
calling of change method with all the letters extracted from position 1 to the end of
the sentence w as parameter.
f) If ch is equal to 'z' then return the concatenation of "c" and the recursive
calling of change method with all the letters extracted from position 1 to the end of
the sentence w as parameter.
g) return "".
2. End of method.
Algorithm for boolean happy(int n)
1. Begin.
2. Declare memory variable(sum).
3. If n is equal to 1 then return true
otherwise if n is equal to 4 then return false
otherwise call sosq() method with n as parameter and store the result in sum and
return the recursive call of happy with sum as parameter.
4. End of method.
Algorithm for int sosq(int n)
1. If n is equal to 0 then return 0
otherwise return the sum of the square of the remainder of the integer division of n
by 10 and sosq() with n/10 as parameter.
2. End of method.
Algorithm for String remove(String k)
1. Begin.
2. Declare memory variable(ch).
3. If the length of k is equal to 0 then return "".
otherwise
i) Store the character at 0th position of k in ch.
ii) If ch is present in "AEIOUaeiou" then return the concatenation of ch and the
recursive call for remove method with
all the letters extracted from position 1 to the end of the sentence k as
parameter.
otherwise
return the recursive call for remove method with all the letters extracted from
position 1 to the end of the sentence k as parameter.
4. End of method.
Algorithm for void main()
1. Begin.
2. Declare memory variables(p,q).
3. Display "Enter a number to check if it is a magic number or not".
4. Input an integer value in p.
5. Store the result obtained from magic() method with p as parameter in ans1.
6. If ans1 is equal to true then display p and " is a Magic number"
otherwise display p and " is not a Magic number".
7. Display "Enter a string to encode it".
8. Input a sentence in q.
9. Display the result obtained from change() method with q as parameter.
10. Display "Enter a number to check if it is a happy number or not".
11. Input an integer value in p.
12. Store the result obtained from happy() method with p as parameter in ans2.
13. If ans2 is equal to true then display p and " is a Happy number"
otherwise display p and " is not a Happy number".
14. Display "Enter a string to remove its vowels".
15. Input a sentence in q.
16. Display the result obtained from remove() method with q as parameter.
17. End of method.{End of program}.

PROGRAM

import java.util.*;
class Pro11 // start of class
{
boolean magic(int n) // Method to check if a number is a magic number
{
int sum = sod(n);
if(sum == 1)
return true;
else if(sum > 9)
return magic(sum); // Recursive call if sum is greater than 9
else
return false;
}

int sod(int n) // Method to find the sum of digits of a number recursively


{
if(n == 0)
return 0; // Base case: if number is 0, return 0
else
return (n%10) + sod(n/10);
}

String change(String w) // Method to change characters of a string based on certain


conditions
String change(String w) {
{
if(w.length() == 0)
return "";
else
{
char ch = w.charAt(0);
if(ch>=65 && ch<=87)
{
if("AEIOU".indexOf(ch) > - 1)
return (char)(ch+2) + change(w.substring(1));
else
return (char)(ch+3) + change(w.substring(1));
}
else if(ch>=97 && ch<=119)
{
if("aeiou".indexOf(ch) > - 1)
return (char)(ch+2) + change(w.substring(1));
else
return (char)(ch+3) + change(w.substring(1));
}
else
{
switch(ch)
{
case 'X': return "A" + change(w.substring(1));
case 'Y': return "B" + change(w.substring(1));
case 'Z': return "C" + change(w.substring(1));
case 'x': return "a" + change(w.substring(1));
case 'y': return "b" + change(w.substring(1));
case 'z': return "c" + change(w.substring(1));
}
return "";
}
}
}

boolean happy(int n)
{
if(n == 1)
return true;
else if(n == 4)
return false;
else
{
int sum = sosq(n);
return happy(sum); // Recursive call with sum of squares of digits
}
}

int sosq(int n) // Method to find the sum of squares of digits of a number recursively
{
if(n == 0)
return 0;
else
return ((n%10)*(n%10)) + sosq(n/10);
}

String remove(String k)
{
if(k.length() == 0)
return "";
else
{
char ch = k.charAt(0);
if("AEIOUaeiou".indexOf(ch) < 0)
return ch + remove(k.substring(1));
else
return remove(k.substring(1));
}
}
void main()
{
int p;
String q;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check if it is magic number or not");
p = sc.nextInt();
boolean ans1 = magic(p);
if(ans1==true)
System.out.println(p + " is a Magic number");
else
System.out.println(p + "is not a Magic number" ); // Display result for magic number
sc.nextLine();
System.out.println("Enter a String to encode it"); //Display encoded string
q = sc.nextLine();
System.out.println(change(q));
System.out.println("Enter a number to check if it is happy number or not");
p = sc.nextInt();
sc.nextLine();
boolean ans2 = happy(p);
if(ans2==true)
System.out.println(p + " is a Happy number"); //Display result for happy number
else
System.out.println(p + " is not a Happy number");
System.out.println("Enter a String to remove its vowels");
q = sc.nextLine();
System.out.println(remove(q)); // Display string without vowels
}
}
VARIABLE DESCRIPTION TABLE

Variable Name Datatype Scope Purpose


sum int magic(int n) To store sum of
digits
w String change(String w) To store a string
k String remove(String k) To store a string
p int To store a number
q String main() To store a string

n int magic(int n) To store a number

METHOD DESCRIPTION TABLE

Return Type Signature Purpose


boolean magic(int n) To check if the a number
is magic number or not
int sod(int n) To calculate sum of digits
String change(String w) To increase position of
letters (case sensitive)
boolean happy(int n) To check if the number is
happy number or not
int sosq(int n) To find sum of squares of
digits
String remove(String k) To remove the vowels
from a string
void main() To call the methods

OUTPUT
12. Write a program with the following recursive methods.
i) String rev ( String x) => It will reverse the word by recursion
ii) String change ( String a) => Will remove all the vowels present
in the word recursively.
iii) String code ( String x) => It will convert a word by the ASCII
values of the alphabets. Take help of other methods if required.
Example CAT => 765648&846567
iv) int reverse ( int n, int r ) = > will reverse the number present in n
in its reverse form by r.

ALGORITHM

Algorithm for String rev(String x)


1. Begin.
2. Declare memory variable(ch).
3. If the length of x is equal to 0 then return ""
otherwise
i) Store the character at the 0 position of x in ch.
ii) Return the recursive calling of rev() method with the concatenation of ch with all
the letters extracted
from position 1 to the end of x as parameter.
4. End of method.
Algorithm for String change(String a)
1. Begin.
2. Declare memory variable(ch).
3. If the length of a is equal to zero then return "".
otherwise
i) Store the character at 0 position of a in ch.
ii) If the position of ch is greater than 0 in "AEIOUaeiou" then
return the recursive calling of change() method with the concatenation of ch with
all the letters extracted
from position 1 to the end of a as parameter.
otherwise
return the recursive calling of change() method with all the letters extracted
from position 1 to the end of a as parameter.
4. End of method.
Algorithm for int reverse(int n,int r)
1. Begin.
2. If n is equal to 0 then return r
otherwise
i) Otherwise calculate the sum of the product of r and 10 and the remainder of the
integer division of n by 10 and store in r.
ii) Return the recursive call of reverse() method with the quotient of n divided by 10
and r as parameters.
3. End of method.
Algorithm for String code(String x)
1. Begin.
2. Declare memory variable(ch).
3. If the length of x is equal to 0 then return ""
otherwise
i) Store the character at 0 position of x in ch.
ii) Call reverse() method with the integer value of ch and 0 as parameters and
convert the result to a word
and concatenate the entire thing with the recursive call of code() method with all
the letter extracted from position 1
to the end of x.
4. End of method.
Algorithm for void main()
1. Begin.
2. Declare memory variable(str).
3. Display "Enter a string".
4. Input a sentence in str.
5. Display "String without vowels" and the result from the method call of change()
method with str as parameter.
6. Display "String encoded in ASCII", the result from the method call of code()
method with str as parameter,"&", and the result
of reverse() method with -the integer form of the result from code() method with str
as parameter- as parameter.
7.End of method.{End of program}.

PROGRAM

import java.util.*;
class Pro12
{
String rev(String x) // Method to reverse a string recursively
{
if(x.length() == 0)
return " "; // Base case: if string is empty, return empty string
else
{
char ch = x.charAt(0);
return rev(x.substring(1)) + ch;
}
}
String change(String a) // Method to remove vowels from a string recursively
{
if(a.length() == 0)
return "";
else
{
char ch = a.charAt(0); // Extract the first character
if("AEIOUaeiou".indexOf(ch) < 0)
return ch + change(a.substring(1));
else
return change(a.substring(1)); // If character is a vowel, skip it and recursively process
the rest of the string
}
}

int reverse(int n,int r)


{
if(n == 0)
return r;
else
{
r = (r * 10) + (n%10);
return reverse((n/10),r);
}
}

String code(String x)
{
if(x.length() == 0)
return "";
else
{
char ch = x.charAt(0);
return (Integer.toString(reverse((int)ch,0)) + code(x.substring(1))); // Convert
character to ASCII, reverse it, and concatenate with the encoded rest of the string
}
}

void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String str = sc.nextLine();
System.out.println("\n String without vowels: " + change(str));
System.out.println("\n String encoded in ASCII: " + code(str) + "&" +
reverse(Integer.parseInt(code(str)), 0) ); // Displaying the encoded string and its reverse in ASCII
}
}
VARIABLE DESCRIPTION TABLE

Variable name Datatype Scope Purpose


x String rev() Contains string
which has to be
reversed.
a String change() Contains string
from which all
vowels have to be
removed.
n int reverse() Contains integer
which has to be
reversed.
r int reverse() Contains integer
ch char rev() Stores character
ch char change() Stores character
ch char code() Stores character

METHOD DESCRIPTION TABLE

Return type Signature Purpose


String rev(String x) It will reverse the string by
recursion.
String change(String a) It will remove all the
vowels present in the word
recursively.
String code(String x) It will encode the string.
int reverse(int n, int r) It will reverse the number
present in n in its reverse
form by r.
void main() Will call the methods

OUTPUT
13. Write a program to create a binary file to store records of the students.
Roll, name, total, grade will be the fields. After creation of the file print
the data present in it.

ALGORITHM

1. Begin.
2. Declare memory variables (i,n,roll,name,marks,grade).
3. Open a file “P13.bin” in writing mode by using the name fos {fos is the file creation
object} if any error occurs display “error” and go to step 23.
4. Display “Enter number of students”.
5. Take input in n.
6. Initialise i by 1.
7. To run a loop continue steps 8 to 17 till the value of i is less than or equal to n
otherwise go to step 18.
8. Display “Enter details of student”.
9. Display “Enter roll number”.
10.Take input and store in roll.
11. Display “Enter name of student”.
12. Take input and store in name.
13. Display “Enter total marks”.
14. Take input and store in marks.
15. Display “Enter grade”.
16. Take input and store in grade.
17. Increase i by 1 and go to step 7 to continue the loop.
18. Write data in the file using file creation object.
19. Open a file “P13.bin” in reading mode by using the name fis {fis is the file
creation object} if any error occurs display “error” and go to step 23.
20. To run a loop continue steps 21 to 22 until the file has been parsed completely.
21. Read each data and then display them in order.
22. Go to step 21.
23. End of program.

PROGRAM

import java.io.*;
import java.util.*;
class Pro13
{
public static void main() throws IOException
{
File = new File("P28.bin"); // Creating a File object with the name "P28.bin"
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos); // Creating a DataOutputStream
to write primitive data types
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of students");
int n = sc.nextInt();

for(int i = 1;i<=n;i++)
{
System.out.println("Enter details for Student " + i);
System.out.println("Enter roll number");
int roll = sc.nextInt();
sc.nextLine();
System.out.println("Enter name of Student");
String name = sc.nextLine();
System.out.println("Enter Total Marks");
double marks = sc.nextDouble();
System.out.println("Enter Grade");
char grade = sc.next().charAt(0);

try
{
dos.writeInt(roll); // Writing roll number to file
dos.writeUTF(name); // Writing name to file
dos.writeDouble(marks); // Writing marks to file
dos.writeChar(grade); // Writing marks to file
}
catch(Exception E)
{
System.out.println("ERROR");
}
}

FileInputStream fis = new FileInputStream(file);


DataInputStream dis = new DataInputStream(fis);
try
{
while(true)
{
int roll = dis.readInt();//Reading roll number from file
String name = dis.readUTF();//Reading name from file
double marks = dis.readDouble();//Reading marks from file
char grade = dis.readChar();//Reading grade from file

System.out.println("Roll Number: " + roll + ", Name: " + name + ", Marks: "
+ marks + ", Grade: " + grade);
}
}
catch(Exception E)
{
System.out.println("File parsed completely"); // Message when end of file is reached
}
}
}
}

VARIABLE DESCRIPTION TABLE

Variable Name Datatype Scope Purpose


n int To input number of
students
i int main() Loop variable
roll int To store roll
number
name String To store name
marks double To store marks
grade char To store grade

METHOD DESCRIPTION TABLE

Return Type Signature Purpose


void main() To create a binary file and
store records of the
students and then print it
OUTPUT
14. Write a program to create a text file paragraph.txt to store sentences.
Then create two more files a.txt and b.txt. From the first file extract the
sentence with odd number of words and store in a.txt. Similarly extract
the sentence with even number of words and store in b.txt.
Display contents of both the files.

ALGORITHM

1. Begin.
2 Declare memory variables (s, t, x, y, g, h, i, j, ch, c).
3 Open a file “D:\Paragraph.txt” in writing mode using the object fw.
If any error occurs, display the error message and go to step 23.
4. Create BufferedWriter and PrintWriter objects bw and pw for writing to the file.
5. Display “Enter para:”.
6. Take input in variable s.
7. Write the content of s to the file and close the file using pw.
8. Open files “D:\b.txt” and “D:\a.txt” in writing mode using objects fw2 and fw1.
If any error occurs, display the error message and go to step 23.
9. Create BufferedWriter and PrintWriter objects bw2, pw2 for “D:\b.txt” and bw1,
pw1 for “D:\a.txt”.
10. Initialize variables t, x, y as empty strings.
11. To process each character in s, run a loop from i = 0 to length of s – 1.
Continue steps 12 to 17.
12. Extract the character ch from s at position i.
13. If ch is not a period (‘.’), append it to t. Otherwise, continue to step 14.
14. Append a space to t and initialize c to 0.
15. Run a loop from j = 0 to length of t – 1 to count the number of spaces.
16. If the number of spaces (c) is odd, remove extra spaces from t, append a period,
and add it to x.
Otherwise, remove extra spaces from t, append a period, and add it to y.
17. Reset t to an empty string and repeat step 11.
18. Write the content of x to “D:\a.txt” using pw1 and close the file.
19. Write the content of y to “D:\b.txt” using pw2 and close the file.
20. Open files “D:\a.txt” and “D:\b.txt” in reading mode using objects frr and frrr.
If any error occurs, display the error message and go to step 23.
21. Create BufferedReader objects brr and brrr to read from the files.
22. Read lines from both files simultaneously until the end of either file is reached.
Read line g from “D:\a.txt” and h from “D:\b.txt”.
Display “a.txt” followed by content g and “b.txt” followed by content h.
Close both file readers.
23. End of program.

PROGRAM
import java.io.*;
import java.util.*;

class Pro14{
public static void main(){
Scanner sc=new Scanner(System.in);
try{
FileWriter fw=new FileWriter("D:\\Paragraph.txt");
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw= new PrintWriter(bw);
System.out.println("Enter para:");
String s=sc.nextLine();
pw.println(s);
pw.close();
FileWriter fw2=new FileWriter("D:\\b.txt");
BufferedWriter bw2=new BufferedWriter(fw2);
PrintWriter pw2= new PrintWriter(bw2);
FileWriter fw1=new FileWriter("D:\\a.txt");
BufferedWriter bw1=new BufferedWriter(fw1);
PrintWriter pw1= new PrintWriter(bw1);String t="",x="",y="";
for(int i=0;i<s.length();i++)
{char ch=s.charAt(i);
if(ch!='.')
{t=t+ch;}
else
{int c=0;t=t+" ";
for(int j=0;j<t.length();j++)
{if(t.charAt(j)==' ')
c++;}
if(c%2!=0)
{t=t.trim()+".";x=x+t;}
else
{t=t.trim()+".";y=y+t;}
t="";}}
pw1.println(x);
pw1.close();
pw2.println(y);
pw2.close();
String g="",h="";
FileReader frr=new FileReader("D:\\a.txt");
BufferedReader brr=new BufferedReader(frr);
FileReader frrr=new FileReader("D:\\b.txt");
BufferedReader brrr=new BufferedReader(frrr);
while((g=brr.readLine())!=null && (h=brrr.readLine())!=null)
{System.out.println("a.txt"+"\n"+g);
System.out.println("b.txt"+"\n"+h);brrr.close();brr.close();}}
catch(Exception e){System.out.println(e);}
})
VARIABLE DESCRIPTION TABLE
Variable Name Datatype Scope Purpose
s String To store a
paragragh
t String To store a text
x String To store a text
y String main() To store a text
g String To store a text
h String To store a text
i int Loop variable
ch char To store a
character
c int To keep count

METHOD DESCRIPTION TABLE

Return Type Signature Purpose


void main() Creates a file and stores
paragraph. Creates two
more files and stores
sentences with odd
number of words and
even number of words
separately. Finally prints
them.

OUTPUT
15. Write a program which will deal four different types of exceptions
during a program execution. Example : Index Out Of Bounds, Number ,
Arithmetic Exception etc.

ALGORITHM

1.Begin.
2. Declare memory variables (result, numbers[], number, invalidNumber,
parsedNumber, nullString)
3. Divide 10 by 0 and store the result in result
4. Arithmetic Exception is handled by the program showing error message “Division
by 0”
5 Create an array called numbers which stores 3 numbers 1 2 and 3.
6. Store the value present in index 5 of the array
7. Array Index Out of Bound Exception is handled by the program showing error
message “Array Index Out of Bound Exception”
8. Store “abc” in invalidNumber
9. Convert the word in invalidNumber to an integer and store it in parsedNumber.
10. Number Format Exception is handled by the program showing error message
“Invalid parsing”
11. Store null in nullString
12. Display the length of nullString
13. Null Pointer Exception is handled by the program showing error message “Null
Pointer Exception”
14. Display “Program completed successfully”
15. End of program

PROGRAM

class Pro15 {
public static void main(String[] args) {
try {
// ArithmeticException
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}

try {
// ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
int number = numbers[5]; // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}

try {
// NumberFormatException
String invalidNumber = "abc";
int parsedNumber = Integer.parseInt(invalidNumber); // Invalid parsing
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}

try {
// NullPointerException
String nullString = null;
System.out.println(nullString.length()); // Accessing method on null
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}

System.out.println("Program completed successfully.");


}
}

VARIABLE DESCRIPTION TABLE

Variable Name Datatype Scope Purpose


result int To store arithmetic
result
numbers[] int main() To store an array
number int To store a number
parsedNumber int To store a String
nullString String To store a String

METHOD DESCRIPTION TABLE

Return Type Signature Purpose


void main() Demonstrates how to deal
with four types of
exceptions while program
execution using try catch
blocks.
OUTPUT

You might also like