Class Xi Programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

Program 1:

Design a class to overload a function area( ) as follows:

1. double area (double a, double b, double c) with three double arguments, returns the area of a scalene triangle
using the formula:
area = √(s(s-a)(s-b)(s-c))
where s = (a+b+c) / 2
2. double area (int a, int b, int height) with three integer arguments, returns the area of a trapezium using the
formula:
area = (1/2)height(a + b)
3. double area (double diagonal1, double diagonal2) with two double arguments, returns the area of a rhombus
using the formula:
area = 1/2(diagonal1 x diagonal2)

SOLUTION:
Algorithm:
1. Create a public class named `areaOverload`.
2. Define a method named `area` that takes three double parameters: `a`, `b`, and `c`.
3. Inside the `area` method for calculating the area of a scalene triangle:
a. Calculate the semi-perimeter `s` as `(a + b + c) / 2`.
b. Calculate the expression `x` as `s * (s - a) * (s - b) * (s - c)`.
c. Calculate the area `result` by taking the square root of `x` using `Math.sqrt(x)`.
d. Return the `result`.
4. Define another method named `area` that takes two integer parameters: `d` and `e`, and one integer `height`.
5. Inside the `area` method for calculating the area of a trapezium:
a. Calculate the area `result` as `(1.0 / 2.0) * height * (d + e)`.
b. Return the `result`.
6. Define another method named `area` that takes two double parameters: `diagonal1` and `diagonal2`.
7. Inside the `area` method for calculating the area of a rhombus:
a. Calculate the area `result` as `1.0 / 2.0 * diagonal1 * diagonal2`.
b. Return the `result`.
8. In the `main` method:
a. Create an instance of the `areaOverload` class named `arOvr`.
b. Calculate the area of a scalene triangle with sides 20.0, 30.0, and 40.0 using the `area` method that takes three
double parameters, and store it in a variable.
c. Print the area of the scalene triangle.
d. Calculate the area of a trapezium with bases 50 and 60, and height 70, using the `area` method that takes two
integers and one integer `height`, and store it in a variable.
e. Print the area of the trapezium.
f. Calculate the area of a rhombus with diagonals 80.0 and 150.0 using the `area` method that takes two double
parameters, and store it in a variable.
g. Print the area of the rhombus.

CODE:
public class areaOverload
{
double area(double a, double b, double c) {
double s = (a + b + c) / 2;
double x = s * (s-a) * (s-b) * (s-c);
double result = Math.sqrt(x);
return result;
}

double area (int d, int e, int height) {


double result = (1.0 / 2.0) * height * (d + e);
return result;
}

double area (double diagonal1, double diagonal2) {


double result = 1.0 / 2.0 * diagonal1 * diagonal2;
return result;
}
public static void main(String args[])
{
areaOverload arOvr = new areaOverload();
System.out.println("Area of Scalene Triangle = "
+arOvr.area(20.0d,30.0d,40.0d) + " sq.units");
System.out.println("Area of Trapezium = "
+arOvr.area(50,60,70) + " sq.units");
System.out.println("Area of Rhombus = "
+arOvr.area(80.0d,150.0d) + " sq.units");
}
}

VARIABLE
VARIABLE DESCRIPTION TABLE:
SRNO VARIABLE VARIABLE USAGE
NAME TYPE
1 a double Contains
Length of 1st
Side
2 b double Contains
Length of 2nd
Side
3 c double Contains
Length of 3rd
Side
4 d int Contains
Length of 1st
Side
5 e int Contains
Length of 2nd
Side
6 height int Contains Value
of Height
7 diagonal1 double Contains
Length of 1st
Diagonal
8 diagonal2 double Contains
Length of 2nd
Diagonal
9 result double Contains Area

OUTPUT SCREEN:
Program 2:
WRITE A PROGRAM IN JAVA TO DO BASE CONVERSION FROM DECIMAL TO
HEXADECIMAL NUMBER AND VICE VERSA USING THESE TWO METHODS:

1. String d2h(int num) : to covert decimal number to hexadecimal number.

2. Int h2d( String s, int l) : to convert hexadecimal to decimal number.

SOLUTION:
Algorithm:
Start:
Step 1: Define a class named "BaseConversion".
Step 2: Declare static variables: no, sav, hex, deci, sv, c1, c2, sc.
Step 3: Define a method "h2d(String s, int l)" for hexadecimal to decimal
conversion.
Step 3.1: If l is less than 0, return 0.
Step 3.2: Get the character at index l from string s and store it in
ch.
Step 3.3: If ch is a digit, set no as ch - 48. Otherwise, set no as ch -
55.
Step 3.4: Calculate sav as no multiplied by 16 raised to the power of
(s.length() - 1 - l).
Step 3.5: Recursively call h2d(s, l - 1) and return the sum of sav and the
recursive result.
Step 4: Define a method "d2h(int num)" for decimal to hexadecimal
conversion.
Step 4.1: If num is 0, return "0".
Step 4.2: Calculate the remainder of num divided by 16 and store
it in d.
Step 4.3: If d is less than or equal to 9, concatenate d to the beginning of sv.
Otherwise, concatenate (char)(d + 55) to sv.
Step 4.4: Update num by dividing it by 16.
Step 4.5: Recursively call d2h(num) and return the result.
Step 5: Define the "main" method.
Step 5.1: Create an instance of the "Baseconversion" class named "vers".
Step 5.2: Create a Scanner object sc to read input from the user. Step 5.3:
Display "Enter decimal number".
Step 5.4: Read and store the input decimal number in the variable
deci.
Step 5.5: Display "Enter hexadecimal number".
Step 5.6: Read and store the input hexadecimal number in the
variable hex.
Step 5.7: Get the length of the hex string and store it in len.
Step 5.8: Call the h2d(hex, len - 1) method using the "vers" object and store
the result in c1.
Step 5.9: Display "The decimal number is " followed by c1.
Step 5.10: Call the d2h(deci) method using the "vers" object and store the
result in c2.
Step 5.11: Display "The hexadecimal number is " followed by c2.
Step 6: End.

Code:
import java.util.Scanner;

public class BaseConversion {


static int no; // Declaring variables
static int sav = 0;
static String hex = "";
static int deci;
static String sv = "";

int h2d(String s, int l) // Converting hexadecimal to


decimal
{
if (l < 0)
return 0;
else {
char ch = s.charAt(l);
if (Character.isDigit(ch))
no = ch - 48;
else
no = ch - 55;

sav = no * (int) Math.pow(16, s.length() - 1 -


l);
return sav + h2d(s, l - 1);
}
}

String d2h(int num) // Converting decimal to hexadecimal


{
if (num == 0)
return sv;
else {
int d = num % 16;
if (d <= 9)
sv = d + sv;
else
sv = (char) (d + 55) + sv;
return d2h(num / 16);
}
}

public static void main(String args[]) {


BaseConversion vers = new BaseConversion();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Decimal Number: ");
deci = sc.nextInt();
System.out.print("Enter Hexadecimal Number: ");
hex = sc.next();
int len = hex.length();
int c1 = vers.h2d(hex, len - 1);
System.out.println("Decimal Equivalent is :" + c1);
VARIABLE DESCRIPTION TABLE:

OUTPUT SCREEN:
PROGRAM 3
WRITE A PROGRAM IN JAVA TO SEARCH A NUMBER GIVEN BY THE USER USING BUBBLE SORT.
1. Void accept ( ) : to accept n array elements.
2. Void bubblesort( ) : to perform sorting Void display(
) : to display sorted array
3. Call main method to call display function.

ALGORITHM WRITING
Start:
Step 1: Define a class named "bubble".
Step 2: Declare the static variables n and arr.
Step 3: Define a static method "accept()" to read the input range and
elements.
Step 3.1: Create a Scanner object sc to read input from the user.
Step 3.2: Display "Enter range".
Step 3.3: Read and store the input value in variable n. Step
3.4: Initialize the array arr with size n.
Step 3.5: Display "Enter elements". Step
3.6: Loop from i = 0 to n-1.
Step 3.6.1: Read an integer from the user and store it in arr[i]. Step
3.7: End loop.
Step 4: Define a static method "bubblesort(int arr[], int n)" to perform
bubble sort.
Step 4.1: Loop from i = 0 to n-2.
Step 4.1.1: Loop from j = 0 to n-2-i.
Step 4.1.1.1: Check if arr[j] is less than arr[j+1].
Step 4.1.1.1.1: Swap arr[j] and arr[j+1].
Step 4.1.1.2: End if.
Step 4.1.2: End loop.
Step 4.2: Loop from i = 0 to n-1.
Step 4.2.1: Display arr[i] followed by a space.
Step 4.3: End loop.
Step 5: Define a static method "display()" to accept input and perform
bubble sort.
Step 5.1: Call the "accept()" method.
Step 5.2: Call the "bubblesort(arr, n)" method.
Step 6: Define the "main" method.
Step 6.1: Call the "display()" method.
Step 7: End.

CODE:
import java.util.*;

class bubble {
static int n;
static int arr[];

static void accept() // to accept range of array


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter range");
n = sc.nextInt();
arr = new int[n];
System.out.println("Enter elements");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
}

static void bubblesort(int arr[], int n) // to sort


the elements in array
{
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}

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


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

}
}

static void display() // to display the sorted array


{
accept();
bubblesort(arr, n);
}

public static void main(String args[]) {


display();
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT SCREEN:
PROGRAM 4
WRITE A PROGRAM IN JAVA TO ACCEPT M AND N ARRAY ELEMENTS FROM THE USER and perform the
following tasks:
1. void accept : to accept members of two arrays.
2. void display( int size, int arr[ ]): to display the new merged array.
3. void merge(int x[ ],int y [ ]): to merge array elements.

Call main method to create object to call these functions

Solution:
Algorithm:
Start:
Step 1: Define a class named "arraymerge".
Step 2: Declare static variables m, n, merge, g, k, r. Step 3: Define a method
"accept()" to read input arrays.
Step 3.1: Create a Scanner object sc to read input from the user.
Step 3.2: Display "Enter size of m".
Step 3.3: Read and store the input value in variable k. Step 3.4: Display "Enter
size of n".
Step 3.5: Read and store the input value in variable r.
Step 3.6: Initialize arrays m and n with sizes k and r, respectively.
Step 3.7: Display "Enter array elements". Step 3.8: Loop from
i = 0 to k-1.
Step 3.8.1: Read an integer from the user and store it in m[i].
Step 3.9: End loop.
Step 3.10: Loop from i = 0 to r-1.
Step 3.10.1: Read an integer from the user and store it in n[i].
Step 3.11: End loop.
Step 4: Define a method "merge(int m[], int n[])" to merge arrays.
Step 4.1: Calculate the total number of elements in the merged array, g = k + r.
Step 4.2: Initialize the merge array with size g. Step 4.3: Compare the
sizes of arrays m and n.
Step 4.3.1: If r >= k, then:
Step 4.3.1.1: Loop from i = 0 to k-1.
Step 4.3.1.1.1: Assign m[i] to merge[i].
Step 4.3.1.2: Loop from i = k to g-1.
Step 4.3.1.2.1: Assign n[i-k] to merge[i].
Step 4.3.2: Else:
Step 4.3.2.1: Loop from i = 0 to r-1.
Step 4.3.2.1.1: Assign n[i] to merge[i].
Step 4.3.2.2: Loop from i = r to g-1.
Step 4.3.2.2.1: Assign m[i-r] to merge[i].
Step 5: Define a method "display(int merge[], int g)" to display the merged array.
Step 5.1: Display "The array is". Step 5.2: Loop
from i = 0 to g-1.
Step 5.2.1: Display merge[i] followed by a space.
Step 5.3: End loop.
Step 6: Define the "main" method.
Step 6.1: Create an object am of the "arraymerge" class. Step 6.2: Call the "accept()"
method using the am object. Step 6.3: Call the "merge(m, n)" method using the am object.
Step 6.4: Call the "display(merge, g)" method using the am object. Step 7: End.

CODE:
import java.util.Scanner;

public class arraymerge {


static int m[], n[]; // declaration of two arrays and
new array static int merge[];
static int g;
static int merge[];
static int k, r;

void accept() // to accept ranges of two arrays


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of m");
k = sc.nextInt();
System.out.println("Enter size of n");
r = sc.nextInt();
m = new int[k];
n = new int[r];
System.out.println("Enter array elements");
for (int i = 0; i < k; i++) {
m[i] = sc.nextInt();
}

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


n[i] = sc.nextInt();
}
}

void merge(int m[], int n[]) // method to merge the


arrays
{
g = k + r;
merge = new int[g];
//now put elements of m&n in merge if(r>=k)
{
for (int i = 0; i < k; i++) {
merge[i] = m[i];
}
for (int i = k; i < g; i++) {
// merge[i]=n[i-k];
}
}
for (int i = 0; i < r; i++) {
merge[i] = n[i];
}
for (int i = r; i < g; i++) {
merge[i] = m[i - r];
}
}

}
VARIABLE DESCRIPTION TABLE:
OUTPUT SCREEN:
PROGRAM 5
WRITE A PROGRAM IN JAVA IN ACCEPT ’S’ ARRAY ELEMENTS AND REMOVE DUPLICATE ELEMENTS
FROM THE ARRAY. DISPLAY THE ARRAY ELEMENTS AFTER REMOVING DUPLICATE ELEMENTS
PERFORM THE FOLLOWING TASK USING THESE METHODS
1. void accept ( ) : to accept s array elements from the user.
2. void remove (int a[ ], int s ) : to remove duplicate elements .
3. void display ( int a[ ], int s) : display elements after removing.

` ALGORITHM
Step 1: Define a class named
“arrayduplicate”. Step 2: Declare static
variables a and s.
Step 3: Define a method "accept()" to read input array.
Step 3.1: Create a Scanner object sc to read input from the user.
Step 3.2: Display "Enter range".
Step 3.3: Read and store the input value in variable s.
Step 3.4: Initialize array a with size s.
Step 3.5: Display "Enter array elements”.
Step 3.6.1 : Read an integer from the user and store it in a[I].
Step 3.7: End loop.
Step 4: Define a method "remove(int a[], int s)" to remove
duplicates from the array.
Step 4.1: Initialize variables duff = Integer.MIN_VALUE and fst = 0.
Step 4.2: Loop from i = 0 to s-2.
Step 4.2.1: Set fst = i.
Step 4.2.2: Loop from j = i+1 to s-1.
Step 4.2.2.1: If a[fst] equals a[j], set a[j] to duff.
Step 4.2.3: End loop.
Step 4.3: End loop.
Step 5: Define a method "display()" to display the array with
duplicates removed.
Step 5.1: Display "The array with duplicates removed: “.
Step 5.2: Loop from i = 0 to s-1.
Step 5.2.1: If a[i] is not equal to Integer.MIN_VALUE, display a[i] followed by a
space.
Step 5.3: End loop.
Step 6: Define the "main" method.
Step 6.1: Create an object ad of the "arrayduplicate" class. Step 6.2:
Call the "accept()" method using the ad object.
Step 6.3: Call the "remove(a, s)" method using the ad object. Step
6.4: Call the "display()" method using the ad object.
Step 7: End.

PROGRAM CODE
import java.util.*;
import java.util.Scanner; class
arrayduplicate
{
static int a[],s;// Declaration of variables

void accept( ) // to accept the array and range


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter range");
s=sc.nextInt();
a=new int[s]; // Initialisation of array
System.out.println("Enter array"); for(int
i=0;i<s;i++)
{
a[i]=sc.nextInt();
}
}
void remove(int a[],int s)
{
int duff=Integer.MIN_VALUE;
int fst=0;
for(int i=0;i<s-1;i++)
{
fst=i;
for(int j=I+1;j<s ;j++)
{
if(a[fst]==a[j])
a[j]=duff;
}
}

}
void display( ) // to display the array
{
System.out.println("The array is “);
for(int i=0;i<s;i++)
{
if(a[I]!=Integer.MIN_VALUE)
System.out.println(a[i]);
}
}
public static void main(String args[])
{
arrayduplicate ad=new arrayduplicate(); // Calling methods ad.accept();
ad.remove(a, s);
ad.display();
}
}

VARIABLE DESCRIPTION TABLE


OUTPUT WINDOW
PROGRAM 6
WRITE A PROGRAM IN JAVA TO INPUT A DECIMAL A NUMBER AND FOLLOW THESE METHODS
1) void accept : to accept decimal and octal number.
2) void dec_2bin(int n) : to convert decimal number to binary number.
3) void oct_2dec(int n) : to covert octal number to
decimal number .
Create main method to call the above methods.

ALGORITHM WRITING
Start:
Step 1: Define a class named "baseconvo".
Step 2: Declare static variables deci, octs, bin, mal. Step 3:
Define a method "accept()" to read input and perform
conversions.
Step 3.1: Create a Scanner object sc to read input from the
user.
Step 3.2: Display "Enter decimal number".
Step 3.3: Read and store the input value in variable deci. Step 3.4:
Display "Enter octal number".
Step 3.5: Read and store the input value in variable octs. Step 3.6:
Display "Enter choice".
Step 3.7: Read and store the input value in variable choice. Step
3.8: If choice is 1, then:
Step 3.8.1: Display "Decimal to binary".
Step 3.8.2: Call the method "dec_2bin(deci)".
Step 3.9: Else:
Step 3.9.1: Display "Octal to decimal".
Step 3.9.2: Call the method "oct_2dec(octs)". Step
4: Define a method "dec_2bin(int n)" to convert decimal to
binary.
Step 4.1: Initialize an empty string s.
Step 4.2: Loop while n is not equal to 0.
Step 4.2.1: Calculate the remainder of n divided by 2 and store
it in rem.
Step 4.2.2: Concatenate rem to the beginning of string s. Step
4.2.3: Update n by dividing it by 2.
Step 4.3: Convert string s to an integer and store it in variable bin.
Step 4.4: Display "Binary is " followed by bin.
Step 5: Define a method "oct_2dec(int n)" to convert octal to
decimal.
Step 5.1: Initialize mal as 0 and pos as 0. Step 5.2:
Loop while n is not equal to 0.
Step 5.2.1: Calculate the last digit of n and store it in digit.
Step 5.2.2: Add digit * 8^pos to mal. Step
5.2.3: Increment pos.
Step 5.2.4: Update n by removing the last digit.
Step 5.3: Display "Octal is " followed by mal.
Step 6: Define the "main" method.
Step 6.1: Create an object bsc of the "baseconvo" class. Step 6.2:
Call the "accept()" method using the bsc object.
Step 7: End.

PROGRAM CODE
import java.util.*;
class baseconvo
{
static int deci; // declaring variables
static int octs;
static int bin;
static int mal;
void accept( ) // to accept decimal and octal number
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter decimal number");
deci=sc.nextInt();
System.out.println("Enter octal number");
octs=sc.nextInt();
int choice;
System.out.println("Enter choice");
choice=sc.nextInt();
if(choice==1)
{
System.out.println("Decimal to binary"); dec_2bin(deci);
}

else
{
System.out.println("Octal to decimal"); oct_2dec(octs);
}
}
void dec_2bin(int n) // to convert decimal to binary number.
{
String s="";
while(n!=0)
{
int rem=n%2;
s=rem+s; n=n/2;
}
bin=Integer.parseInt(s);
System.out.println("Binary is "+bin);
}
void oct_2dec(int n) // to convert octal to decimal number.
{
int pos=0;
while(n!=0)
{
int digit=n%10; mal=mal+(digit*(int)
(Math.pow(8, pos))); pos++;
n=n/10;
}
System.out.println("Octal is "+mal);
}
public static void main(String args[])
{
baseconvo bsc=new baseconvo(); // calling the method bsc.accept();
}
}
VARIABLE DESCRIPTION TABLE
OUTPUT
PROGRAM 7
WRITE A PROGRAM IN JAVA TO ACCEPT A SENTENCE
AND FIND THE FREQUENCY OF WORDS THAT CONTAIN
CONSECUTIVE VOWELS.
1) void accept ( ) : to enter sentence given by user.
2) Void extract ( ): to extract each word from sentence.
3) Int consecutivevowel (String word) : to check
consecutive vowels.
4) Boolean isvowel( char ch) : to check alphabet is vowel or not.
Create main function to call the above methods.

ALGORITHM WRITING

Start:
Step 1: Define a class named "vow".
Step 2: Declare variables word and ss.
Step 3: Define a method "accept()" to read input sentence.
Step 3.1: Create a Scanner object sc to read input from the user.
Step 3.2: Display "Enter sentence".
Step 3.3: Read the input line and store it in the variable ss.
Step 3.4: Return.
Step 4: Define a method "extract()" to extract words and find
consecutive vowels.
Step 4.1: Create a StringTokenizer object st using ss
and delimiter " ".
Step 4.2: Loop while st has more tokens.
Step 4.2.1: Get the next token and store it in the variable word.
Step 4.2.2: Call the method "consecutivevowel(word)" to count
consecutive vowels.
Step 4.2.3: If the count k is greater than 0, display the word
and its frequency k.
Step 5: Define a method "consecutivevowel(String word)" to check
consecutive vowels in a word.
Step 5.1: Convert the word to lowercase and append a space to
the end.
Step 5.2: Initialize freq as 0.
Step 5.3: Create a char array store to store characters of the
word.
Step 5.4: Get characters from the word and store them in the
store array.
Step 5.5: Loop from i = 0 to store.length - 2.
Step 5.5.1: If isvowel(store[i]) is true and isvowel(store[i+1]) is
true, increment freq.
Step 5.6: Return freq.
Step 6: Define a method "isvowel(char ch)" to check if a character
is a vowel.
Step 6.1: If ch is 'a', 'e', 'i', 'o', or 'u', return true. Otherwise,
return false.
Step 7: Define the "main" method.
Step 7.1: Create an object vw of the "vow" class.
Step 7.2: Call the "accept()" method using the vw object.
Step 7.3: Call the "extract()" method using the vw object.
Step 8: End.

PROGRAM CODE
import java.util.Scanner; import
java.util.StringTokenizer; class
vow
{
String word;
String ss;

void accept( ) // method to accept sentence


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter sentence");
ss=sc.nextLine();
return;
}
void extract( ) // method to extract words from sentence
{
StringTokenizer st=new StringTokenizer(ss," ");
while(st.hasMoreTokens())
{
word=st.nextToken();
int k=consecutivevowel(word);
// calling consecutivevowel function
if(k>0)
System.out.println(word+" frequency is "+k);
}
}
int consecutivevowel(String word)
// Method to check consecutive vowels
{
word=word+" ";
word=word.toLowerCase(); int
freq=0;
char[ ]store =new char[word.length()-1];
int start=0, end=word.length()-1;
word.getChars(start, end, store, 0); for(int
i=0;i<store.length-2;i++)
{
if(isvowel(store[I])==true) // calling the isvowel function
{
if(isvowel(store[I+1])==true) // calling the isvowel function
{
freq++;
}
}
}
return freq;
}
boolean isvowel(char ch)
// method to check if alphabet is vowel or not
{
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') return
true;
else
return false;
}
public static void main(String args[])
{
vow vw=new vow(); // making object to call the methods
vw.accept();
vw.extract();
}
VARIABLE DESCRIPTION TABLE
OUTPUT
PROGRAM 8
WRITE A PROGRAM IN JAVA TO ACCEPT A SENTENCE
AND REVERSE EACH WORD AT ITS POSITION. DISPLAY
THE FREQUENCY OF PALINDROME WORD.
ALGORITHM WRITING

Start:
Step 1: Define a class named "frequency".
Step 2: Declare instance variables: String s and String word.
Step 3: Define a method "accept".
Step 3.1: Create a Scanner object sc to read input from the user.
Step 3.2: Display "Enter sentence".
Step 3.3: Read and store the input sentence in the variable s.
Step 4: Define a method "check".
Step 4.1: Get the length of the input sentence and store it in l.
Step 4.2: Get the last character of the input sentence and
store it in last.
Step 4.3: If last is '.', '?' or '!', display "Invalid choice" and
exit the program.
Step 4.4: Trim the input sentence by removing leading and
trailing spaces.
Step 5: Define a method "isPalindrome(String gg)".
Step 5.1: Initialize a String rev to store the reversed gg.
Step 5.2: Iterate through the characters of gg in reverse order.
Step 5.2.1: Append each character to rev.
Step 5.3: If rev is equal to gg, return true; otherwise, return false.
Step 6: Define a method "wordextract".
Step 6.1: Initialize freq to 0.
Step 6.2: Initialize save as an empty string.
Step 6.3: Create a StringTokenizer st with the input sentence
and space delimiter.
Step 6.4: While st has more tokens:
Step 6.4.1: Get the next token and store it in word.
Step 6.4.2: Get the reversed version of word using the
"Palindrome" method and store it in gg.
Step 6.4.3: Append gg followed by a space to save.
Step 6.4.4: If gg is a palindrome (using the "isPalindrome"
method): Step 6.4.4.1: Display word.
Step 6.4.4.2: Increment freq by 1.
Step 6.5: Display "The frequency of palindrome words is"
followed by freq.
Step 6.6: Display save.
Step 7: Define the "main" method.
Step 7.1: Create an instance of the "frequency" class named f.
Step 7.2: Invoke the "accept" method on f to get the input
sentence.
Step 7.3: Invoke the "check" method on f to validate the
sentence.
Step 7.4: Invoke the "wordextract" method on f to extract and
display palindrome words.
Step 8: End.

PROGRAM CODE
import java.util.*;
import java.util.StringTokenizer;
class frequency
{
String s;
String word;
void accept( ) // to accept sentence
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter sentence");
s=sc.nextLine();
}
void check( ) // to check sentence ends with . or ! or ?
{
int l=s.length();
char last=s.charAt(l-1);
if(last=='.'|| last=='?'|| last=='!')
{
System.out.println("Invalid choice");
System.exit(0);
}
s=s.trim();
}
void wordextract( ) // to extract words from sentence
{
int freq=0;
String save="";
StringTokenizer st=new StringTokenizer(s," ");
while(st.hasMoreTokens())
{
word=st.nextToken();
String gg=Palindrome(word); // calling Palindrome method
save=save+gg+" ";
if(isPalindrome(gg)==true) // calling isPalindrome method
{
System.out.println(word); freq+
+;
}
}
System.out.println("The frequency of palindrome words is"+freq);
System.out.println(save);
}
boolean isPalindrome(String gg) // to check word is palindrome
{
String rev="";
for(int i=word.length()-1;i>=0;i--)
{
rev=rev+gg.charAt(i);
}
if(rev.equals(gg))
return true;
else
return false;
}
String Palindrome(String word) // to find palindrome of a word
{
String rev="";
for(int i=word.length()-1;i>=0;i--)
{
rev=rev+word.charAt(i);
}
return rev;
}
public static void main(String args[])
{
frequency f=new frequency(); // calling methods
f.accept();
f.check();
f.wordextract();
}
}
VARIABLE DESCRIPTION TABLE
OUTPUT
PROGRAM 9
WRITE A PROGRAM IN JAVA TO ACCEPT A SENTENCE
AND PRINT THE LONGEST WORD AND LENGTH OF
EACH WORD IN THE INPUT.
1) void accept ( ) : to accept sentence from user.
2) Void eachwordlength( ) : to display length of each word.
3) Void lonword ( ) : to display longest words .
Call main method to call above methods.

ALGORITHM WRITING

Start:
Step 1: Define a class named "LoSiento".
Step 2: Declare instance variables: String n, String s, String lo and
int n
Step 3: Define a method "accept".
Step 3.1: Create a Scanner object sc to read input from the user.
Step 3.2: Display "Enter sentence".
Step 3.3: Read and store the input sentence in the variable n.
Step 3.4: Copy the value of n to s.
Step 3.5: Initialize lo as an empty string.
Step 4: Define a method "eachwordlength".
Step 4.1: Display "Length of each word is".
Step 4.2: Create a StringTokenizer std using n and space
delimiter. Step 4.3: Iterate while std has more tokens:
Step 4.3.1: Get the next token and store it in word.
Step 4.3.2: Get the length of word and store it in len.
Step 4.3.3: Display word and len.
Step 5: Define a method "lonword".
Step 5.1: Initialize a temporary string w as empty.
Step 5.2: Append a space to the end of s.
Step 5.3: Get the length of s and store it in l.
Step 5.4: Initialize lo as an empty string.
Step 5.5: Iterate from i = 0 to l - 1:
Step 5.5.1: Get the character at index i from s and store it in ch.
Step 5.5.2: If ch is not a space:
Step 5.5.2.1: Append ch to w.
Step 5.5.3: Else (when a word ends):
Step 5.5.3.1: If the length of w is greater than the length
of lo, set lo as w.
Step 5.5.3.2: Reset w as an empty string.
Step 5.6: Display "longest word is/are".
Step 5.7: Iterate from i = 0 to l - 1:
Step 5.7.1: Get the character at index i from s and store it in ch.
Step 5.7.2: If ch is not a space:
Step 5.7.2.1: Append ch to w.
Step 5.7.3: Else (when a word ends):
Step 5.7.3.1: If the length of w is equal to the length of lo, display w.
Step 5.7.3.2: Reset w as an empty string.
Step 6: Define the "main" method.
Step 6.1: Create an instance of the "LoSiento" class named ls.
Step 6.2: Invoke the "accept" method on ls to get the input
sentence.
Step 6.3: Invoke the "lonword" method on ls to find and display
the longest word(s).
Step 6.4: Invoke the "eachwordlength" method on ls to display
the length of each word.
Step 7: End.

PROGRAM CODE

import java.util.StringTokenizer;
import java.util.Scanner;
class LoSiento
{
String n, s;
String lo;
int l;
void accept( ) // to accept sentence
{
Scanner sc=new Scanner(System.in);
System.out.println("enter sentence");
n=sc.nextLine();
s=n;
lo="";
}

void eachwordlength( ) // to find length of each word


{
String longg="";
int c=0;
System.out.println("Length of each word is");
StringTokenizer std=new StringTokenizer(n," ");
while(std.hasMoreTokens())
{
String word=std.nextToken();
int len=word.length();
System.out.println(word+" "+len);
}
}

void lonword( ) // to find the longest words in sentence


{
String w="";
s=s+" ";
int l=s.length();
for(int i=0;i<l;i++)
{
char ch=s.charAt(i);
if(ch!=' ')
{
w=w+ch;
}
else
{
if(w.length()>lo.length())
{
lo=w;
}
w="";
}
}
System.out.println("longest word is/are "); for(int
i=0;i<l;i++)
{
char ch=s.charAt(i);
if(ch!=' ')
{
w=w+ch;
}
else
{
if(w.length()==lo.length())
{
System.out.println(w);
}
w="";
}
}

System.out.println();
}
public static void main(String args[])
{
LoSiento ls=new LoSiento(); // calling methods
ls.accept( );
ls.lonword( );
ls.eachwordlength( );
}
}
VARIABLE DESCRIPTION TABLE
OUTPUT
PROGRAM 10
WRITE A PROGRAM IN JAVA TO ACCEPT A SENTENCE
AND DISPLAY EACH WORD AFTER LENGTHWISE
SORTING IN ASCENDING ORDER.

ALGORITHM
Start:
Step 1: Define a class named "sentosimple".
Step 2: Declare instance variables: sen (String), c (int), arr
(String[]). Step 3: Define a method "accept":
Step 3.1: Create a Scanner object sc to read input from the user.
Step 3.2: Display "Enter sentence".
Step 3.3: Read and store the input sentence in the variable sen.
Step 4: Define a method "extract":
Step 4.1: Create a StringTokenizer st using sen and space
delimiter.
Step 4.2: Get the count of tokens using st and store it in c.
Step 4.3: Initialize an array arr of Strings with size c.
Step 4.4: Initialize an index variable ind as
0. Step 4.5: Iterate while st has more
tokens:
Step 4.5.1: Get the next token using st and store it in arr[ind].
Step 4.5.2: Increment ind by 1.
Step 5: Define a method "arrange":
Step 5.1: Iterate from i = 0 to c - 2:
Step 5.1.1: Iterate from j = 0 to c - 2 - I:
Step 5.1.1.1: If the length of arr[j] is greater than the
length of arr[j+1]:
Step 5.1.1.1.1: Swap arr[j] and arr[j+1].
Step 6: Define a method "print":
Step 6.1: Iterate from i = 0 to c - 1:
Step 6.1.1: Print arr[i] followed by a space.
Step 7: Define the "main" method:
Step 7.1: Create an instance of the "sentosimple" class named ss.
Step 7.2: Invoke the "accept" method on ss to get the
input sentence.
Step 7.3: Invoke the "extract" method on ss to tokenize and
store words.
Step 7.4: Invoke the "arrange" method on ss to arrange
words by length.
Step 7.5: Invoke the "print" method on ss to display the
sorted words.
Step 8: End.

PROGRAM CODE
import java.util.*; class
sentosimple
{
String sen;
int c;
String arr[];

void accept( ) // method to accept sentence


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter sentence");
sen=sc.nextLine();
}

void extract( ) // method to extract words from sentence


{
StringTokenizer st=new StringTokenizer(sen," ");
c=st.countTokens();
arr=new String[c];
int ind=0;
while(st.hasMoreTokens())
{
arr[ind++]=st.nextToken();
}
}
void arrange( ) // method to arrange the words
{
for(int i=0;i<c-1;i++)
{
for(int j=0;j<c-1-i ;j++)
{
if(arr[j].length()>arr[j+1].length())
{
String tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
}
}
}
void print( ) // to print in lengthwise order
{
for(int i=0;i<c;i++)
{
System.out.print(arr[i]+" ");
}
}
public static void main(String args[])
{
sentosimple ss=new sentosimple(); // calling methods ss.accept();
ss.extract();
ss.arrange();
ss.print();
}
}
VARIABLE DESCRIPTION TABLE
OUTPUT
PROGRAM 10
WRITE A PROGRAM IN JAVA TO THE PRINT THE
FIBONACCI SERIES UNTILL ’n’ GIVEN BY THE USER
USING RECURSIVE TECHNIQUE.

ALGORITHM WRITING

Start:
Step 1: Define a class named "FibonacciRecursion".
Step 2: Define a static method "fibonacci(int n)" for calculating the
nth Fibonacci number:
Step 2.1: If n is 0, return 0.
Step 2.2: If n is 1, return 1.
Step 2.3: Otherwise, return the sum of fibonacci(n - 1) and
fibonacci(n - 2).
Step 3: Define the "main" method.
Step 3.1: Create a Scanner object named scanner to read input
from the user.
Step 3.2: Display "Enter the number of terms in Fibonacci series: ".
Step 3.3: Read and store the input integer n representing the
number of terms.
Step 3.4: Display "Fibonacci series up to " + n + " terms:".
Step 3.5: Iterate from i = 0 to n - 1:
Step 3.5.1: Display fibonacci(i) followed by a space.
Step 3.6: Close the scanner.
Step 4: End.
PROGRAM CODE

import java.util.Scanner;
public class FibonacciRecursion
{
static int fibonacci(int n) // recursive method for fibonacci series
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); System.out.print("Enter
the number of terms in Fibonacci series: "); int n = scanner.nextInt(); //
enter the range

System.out.println("Fibonacci series up to " + n + " terms:"); for


(int i = 0; i < n; i++)
{
System.out.print(fibonacci(i) + " "); // calling fibonacci method
}
scanner.close();
}
}
VARIABLE DESCRIPTION TABLE

OUTPUT

You might also like