Raycomp.pdf (1)
Raycomp.pdf (1)
Computer Science
Project
30 Programs Practicals
NUMBER-BASED
class Prime_Range {
int c=0,t=0;
for(int i=1;i<=x;i++)
if(x%i==0)
return true;//True
else
}
public static void main (String args[])
{
if(IsPrime(i)==true)
{
System.out.print(i+" ");
freq++;
}
System.out.println();
System.out.println("Frequency of Prime Numbers is: "+freq);
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Prime_Range
3. Define the IsPrime method:
a. static boolean IsPrime(int x)
b. Initialize int c and t to 0.
c. For i from 1 to x (inclusive):
i. If x is divisible by i, increment c.
d. If c is equal to 2, return true; otherwise, return false.
4. Define the main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Declare int m, n, and freq.
d. Prompt user to enter starting limit (m) and read input.
e. Prompt user to enter ending limit (n) and read input.
f. Initialize freq to 0.
g. For i from m to n (inclusive):
i. If IsPrime(i) is true:
- Print i followed by a space.
- Increment freq.
h. Print a new line.
i. Print "Frequency of Prime Numbers is: " followed by freq.
j. Close the Scanner object (sc).
OUTPUT:
100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
2. Prime_Palindrome
import java.util.*;
class Prime_Palindrome
int c=0,t=0;
for(int i=1;i<=x;i++)
if(x%i==0)
return true;//True
else
int c=x,d=0,rev=0;
while(c>0)
{
d=c%10;
rev=rev*10+d;
c=c/10;
if(rev==x)
return true;
else
return false;
m=sc.nextInt();
System.out.println("Enter Ending Limit(n): ");
n=sc.nextInt();
int freq=0;
for(int i=m;i<=n;i++)
{
System.out.print(i+" ");
freq++;
}
System.out.println();
System.out.println("Frequency of Prime Palindrome Numbers is: "+freq);
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Prime_Palindrome
3. Define the IsPrime method:
a. static boolean IsPrime(int x)
b. Initialize int c and t to 0.
c. For i from 1 to x (inclusive):
i. If x is divisible by i, increment c.
d. If c is equal to 2, return true; otherwise, return false.
4. Define the IsPalindrome method:
a. static boolean IsPalindrome(int x)
b. Initialize int c, d, and rev.
c. While x is greater than 0:
i. Set d to x % 10.
ii. Update rev as rev * 10 + d.
iii. Update x as x / 10.
d. If rev is equal to the original number, return true; otherwise, return false.
5. Define the main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Declare int m, n, and freq.
d. Prompt user to enter starting limit (m) and read input.
e. Prompt user to enter ending limit (n) and read input.
f. Initialize freq to 0.
g. For i from m to n (inclusive):
i. If IsPrime(i) and IsPalindrome(i) are both true:
- Print i followed by a space.
- Increment freq.
h. Print a new line.
i. Print "Frequency of Prime Palindrome Numbers is: " followed by freq.
j. Close the Scanner object (sc).
OUTPUT:
1000
2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929
3. Composite_Magic
/** Program to print Composite Magic Numbers from a given Range
Composite Number: Number which has more than 2 Factors ie, Not Prime
int c=0,t=0;
for(int i=1;i<=x;i++)
{
if(x%i==0)
return true;//True
else
int c=x,d=0,sum=0;
while(c>0)
{
d=c%10;
sum+=d;//Sum of Digits
c=c/10;
if(sum>9)//Finding Eventual Sum of Digits. Finding the Sum of Digits of the Sum number again
return Magic(sum);
return sum;
int m,n;
m=sc.nextInt();
System.out.print(i+" ");
freq++;
}
System.out.println();
System.out.println("Frequency of Composite Magic Numbers is: "+freq);
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Composite_Magic
3. Define the IsComposite method:
a. static boolean IsComposite(int x)
b. Initialize int c and t to 0.
c. For i from 1 to x (inclusive):
i. If x is divisible by i, increment c.
d. If c is greater than 2, return true; otherwise, return false.
4. Define the Magic method:
a. static int Magic(int x)
b. Initialize int c, d, and sum.
c. While x is greater than 0:
i. Set d to x % 10.
ii. Update sum as sum + d.
iii. Update x as x / 10.
d. If sum is greater than 9, call Magic with sum; otherwise, return sum.
5. Define the main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Declare int m, n, and freq.
d. Prompt user to enter starting limit (m) and read input.
e. Prompt user to enter ending limit (n) and read input.
f. Initialize freq to 0.
g. For i from m to n (inclusive):
i. If IsComposite(i) and Magic(i) are both true:
- Print i followed by a space.
- Increment freq.
h. Print a new line.
i. Print "Frequency of Composite Magic Numbers is: " followed by freq.
j. Close the Scanner object (sc).
OUTPUT:
Enter Starting Limit(m):
1
Enter Ending Limit(n):
100
10 28 46 55 64 82 91 100
Frequency of Composite Magic Numbers is: 8
4. Emirp_Number
int n;
n=sc.nextInt();
int c1=0,t1=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
t1=0;
else
t1=1;
int c=n,d=0,rev=0;
while(c>0)
{
d=c%10;
rev=rev*10+d;
c=c/10;
int c2=0,t2=0;
for(int j=1;j<=rev;j++)
{
if(rev%j==0)
c2++; //No. of Factors
t2=0;
else
t2=1;
if(t1==0 && t2==0)//Checking whether both the Numbers are Prime or not
System.out.println("Emirp Number");
else
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Emirp_Number
3. Main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Declare an integer variable n.
d. Prompt the user to enter a number (n) and read the input.
4. Check if Original Number is Prime:
a. Initialize int c1 and t1 to 0. b. For i
from 1 to n (inclusive):
i. If n is divisible by i, increment c1.
c. If c1 is equal to 2, set t1 to 0; otherwise, set t1 to 1.
5. Reverse the Number:
a. Initialize int c to n, d to 0, and rev to 0.
b. While c is greater than 0:
i. Set d to c % 10.
ii. Update rev as rev * 10 + d.
iii. Update c as c / 10.
c. Print "Reversed Number(rev): " followed by rev.
6. Check if Reversed Number is Prime:
a. Initialize int c2 and t2 to 0.
b. For j from 1 to rev (inclusive):
i. If rev is divisible by j, increment c2.
c. If c2 is equal to 2, set t2 to 0; otherwise, set t2 to 1.
7. Check for Emirp Number:
- If t1 is 0 and t2 is 0, print "Emirp Number".
- Otherwise, print "Not Emirp Number".
8. Close the Scanner object (sc).
OUTPUT:
Enter a Number(n):
13
Reversed Number(rev): 31
Emirp Number
5. Kapreka_Number
/** Program to check for Kapreka Number.
Kapreka Number: Number whose square is divided into two parts in any conditions and parts are
added, the sum is equal to the number*/
import java.util.*;;
class Kapreka_Number
{
System.out.println("Enter a Number");
int n=sc.nextInt();
boolean IsKapreka=false;
int sq=n*n;
int c=sq;
int numdigits=0;
while(c>0)
numdigits++;
c=c/10;
for(int i=1;i<numdigits;i++)
int sum=quo+rem;
if(sum==n)
IsKapreka=true;
if(IsKapreka==true)
System.out.println("Kapreka Number");
else
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Kapreka_Number
3. Main method:
a. public static void main(String[] args)
b. Create a Scanner object (sc).
c. Prompt the user to enter a number (n) and read the input.
d. Declare a boolean variable IsKapreka and initialize it to false.
e. Compute the square of the input number and store it in the variable sq.
4. Count Number of Digits in Square:
a. Initialize int c to sq and numdigits to 0.
b. Use a while loop to count the number of digits in the square:
i. Increment numdigits for each iteration.
ii. Update c as c / 10 until it becomes 0.
5. Check for Kapreka Number:
a. Use a for loop from i=1 to numdigits-1 (exclusive).
b. Calculate int div as (int)Math.pow(10, i).
c. Calculate int quo as sq / div.
d. Calculate int rem as sq % div.
e. Calculate int sum as quo + rem.
f. Print "Divisor= " + div.
g. Print "Quotient(Left)= " + quo.
h. Print "Remainder(Right)= " + rem.
i. If sum is equal to n, set IsKapreka to true.
6. Print Result:
- If IsKapreka is true, print "Kapreka Number"; otherwise, print "Not Kapreka
Number".
7. Close the Scanner object (sc).
OUTPUT:
Enter a Number
297
Kapreka Number
6. Circular_Prime
/** A Circular Prime is a prime number that remains prime under cyclic shifts of its digits.
* When the leftmost digit is removed and replaced at the end of the remaining string of digits, the
generated number is still prime.
* The process is repeated until the original number is reached again.
import java.util.*;
class Circular_Prime
int c=0;
for(int i=1;i<=x;i++)
if(x%i==0)
c++;
}
if(c==2)
return true;
else
return false;
String s1=Integer.toString(x);
String s2=s1.substring(1)+s1.charAt(0);
int a=Integer.parseInt(s2);
return a;
void IsCircularPrime(int x)
{
int a=x;
boolean Prime = true;
do
{
System.out.println(a);
if(isPrime(a) == false)
{
Prime = false;
break;
}
a=Shift(a);
}
while (a!=x);
if(Prime==true)
else if(Prime==false)
System.out.println("Enter a Number:");
int n=sc.nextInt();
Circular_Prime cp=new Circular_Prime();
cp.IsCircularPrime(n);
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Circular_Prime
3. Define the isPrime method:
a. static boolean isPrime(int x)
b. Initialize int c to 0.
c. For i from 1 to x (inclusive):
i. If x is divisible by i, increment c.
d. If c is equal to 2, return true; otherwise, return false.
4. Define the Shift method:
a. static int Shift(int x)
b. Convert x to a string s1.
c. Create a new string s2 by taking the substring from the second character to the
end of s1 and appending the first character.
d. Parse s2 back to an integer and return it.
5. Define the IsCircularPrime method:
a. void IsCircularPrime(int x)
b. Initialize int a to x and boolean Prime to true.
c. Use a do-while loop until a becomes equal to x:
i. Print a.
ii. If isPrime(a) is false, set Prime to false and break out of the loop.
iii. Update a by shifting its digits using the Shift method.
d. If Prime is true, print "Circular Prime Number"; otherwise, print "Not a
Circular Prime Number".
6. Define the main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Prompt the user to enter a number (n) and read the input.
d. Create an instance of the Circular_Prime class (cp) and call the
IsCircularPrime method with the entered
number.
7. Close the Scanner object (sc).
OUTPUT: Enter a Number: 1193 1193 1931 9311
import java.util.*;
class Twin_Prime
int n1,n2;
n1=sc.nextInt();
System.out.println("Enter a Number(2): ");
n2=sc.nextInt();
int c1=0,t1=0;
for(int i=1;i<=n1;i++)
{
if(n1%i==0)
}
if(c1==2)//Checking whether Number(1) is Prime or not
t1=0;
else
t1=1;
int c2=0,t2=0;
for(int j=1;j<=n2;j++)
{
if(n2%j==0)
}
if(c2==2)//Checking whether Number(2) is Prime or not
t2=0;
else
t2=1;
if(t1==0 && t2==0)//Checking whether both the Numbers are Prime or not
{
}
else if(t1==1&&t2==1)
System.out.println("Both the Numbers are not Prime");
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Twin_Prime
3. Main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Declare int n1 and n2.
d. Prompt the user to enter the first number (n1) and read the input.
e. Prompt the user to enter the second number (n2) and read the input.
4. Check if Number(1) is Prime:
a. Initialize int c1 and t1 to 0.
b. For i from 1 to n1 (inclusive):
i. If n1 is divisible by i, increment c1.
c. If c1 is equal to 2, set t1 to 0; otherwise, set t1 to 1.
5. Check if Number(2) is Prime:
a. Initialize int c2 and t2 to 0.
b. For j from 1 to n2 (inclusive):
i. If n2 is divisible by j, increment c2.
c. If c2 is equal to 2, set t2 to 0; otherwise, set t2 to 1.
6. Check for Twin Prime Numbers:
- If t1 is 0 and t2 is 0:
- If the difference between n2 and n1 is 2, print "Twin Prime".
- Otherwise, print "Not Twin Prime".
- If either t1 or t2 is 1, print "Both the Numbers are not Prime".
7. Close the Scanner object (sc).
OUTPUT:
Enter a Number(1):
137
Enter a Number(2):
139
Twin Prime
8. Goldbach Number
/** A Goldbach number is a positive even integer that can be expressed as sum of two odd primes.
* FInd and display all the odd prime pair whose sum is equal to N. */
import java.util.*;
class Goldbach
int c=0,t=0;
for(int i=1;i<=x;i++)
if(x%i==0)
return true;//True
else
int n=sc.nextInt();
if(n%2!=0)
System.out.println("Invalid Input");
else
{
}
}
}}}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Goldbach
3. Define the isPrime method:
a. static boolean IsPrime(int x)
b. Initialize int c to 0.
c. For i from 1 to x (inclusive):
i. If x is divisible by i, increment c.
d. If c is equal to 2, return true; otherwise, return false.
4. Define the main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Prompt the user to enter a number (n) and read the input.
5. Check for Valid Input:
- If n is odd, print "Invalid Input" and exit the program.
6. Find and Display Prime Pairs:
a. Print "Pair of Prime Numbers: ".
b. Use nested loops to iterate over odd numbers from 3 to n (inclusive) and vary
the value of i.
c. For each i, iterate over values from i to n and vary the value of j.
d. Check if both i and j are prime using the IsPrime method.
e. If both are prime, check if the sum of i and j is equal to n.
f. If true, print the pair: "i + j = n".
7. Close the Scanner object (sc).
OUTPUT:
Enter a Number(9 to 50):
12
Pair of Prime Numbers:
5 + 7 = 12
9. Combinations
/** A positive number can be expressed as a combination of consecutive number that adds up to the
number.
Program to input a positive integer and display all possible Combinations */
import java.util.*;
class Combinations
System.out.println("Combinations: ");
for(int i=1;i<=(n/2);i++) //***(n/2)***is the Maximum number that can be expressed
{
int sum=0,x=i;
String comb="";//To save Combinations
while(sum<n)//Combination value should be less than the Original Number
x++;//Increment
System.out.println(comb);
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Combinations
3. Define the main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Prompt the user to enter a positive number (n) and read the input.
4. Display Combinations:
a. Print "Combinations: ".
b. Use a for loop to iterate from i=1 to n/2 (inclusive):
i. Initialize int sum to 0 and int x to i. ii. Initialize an empty
string comb to store combinations.
iii. Use a while loop to iterate while sum is less than n:
- Add x to sum.
- Append x + " + " to the comb string.
- Increment x.
iv. If sum is equal to n, print the combination string (comb).
5. Close the Scanner object (sc).
OUTPUT:
100
Combinations:
9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 +
18 + 19 + 20 + 21 + 22 +
10. Unique Digit Number
* Unique Digit Number: Positive Number whose digits are not repeated */
import java.util.*;
class Unique_Digit
int r1,r2,n1,n2,c=0;
n1=x;
n2=x;
while(n1>0)
while(n2>0)
{
c++;
}
n1=n1/10; //Removing Last Digit of n1
}
if(c==1)
return true;
else
return false;
int m,n;
System.out.println("Enter Starting Limit(m): ");
m=sc.nextInt();
n=sc.nextInt();
int freq=0;
for(int i=m;i<=n;i++)
if(IsUnique_Digit(i)==true)
System.out.print(i+" ");
freq++;
}
System.out.println();
System.out.println("Frequency of Unique Digit Numbers is: "+freq);
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Unique_Digit
3. Define the isUnique_Digit method:
a. static boolean IsUnique_Digit(int x)
b. Initialize int n1 and n2 to x.
c. Initialize int c to 0.
d. Use a while loop to iterate while n1 is greater than 0:
i. Extract the last digit of n1 and store it in r1.
ii. Use another while loop to iterate while n2 is greater than 0:
- Extract the last digit of n2 and store it in r2.
- If r1 is equal to r2, increment the counter c.
- Remove the last digit of n2.
iii. Remove the last digit of n1.
e. If c is equal to 1, return true; otherwise, return false.
4. Define the main method:
a. public static void main(String args[])
b. Create a Scanner object (sc).
c. Declare int m, n, and freq.
d. Prompt the user to enter the starting limit (m) and read the input.
e. Prompt the user to enter the ending limit (n) and read the input.
f. Initialize freq to 0.
5. Check and Display Unique Digit Numbers:
a. Print "Frequency of Unique Digit Numbers is: ". b. Use a
for loop to iterate from i=m to n (inclusive). c. Inside the
loop, check if IsUnique_Digit(i) is true:
i. Print the current value of i.
ii. Increment freq.
6. Display Frequency:
- Print the value of freq.
7. Close the Scanner object (sc).
OUTPUT:
50
1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32 34 35 36 37 38 39
40 41 42 43 45 46 47 48 49 50
Frequency of Unique Digit Numbers is: 46
ARRAY-Based
1. TwoD_Array
* Data Members:
* Member Methods:
import java.util.*;
class TwoD_Array
int m;//Rows
int n;//Columns
m=mm;
n=nn;
a=new int[m][n];
void fill()
a[i][j]=sc.nextInt();//Input
}
}
void display()
System.out.println("Array:(Matrix Form)");
System.out.print(a[i][j]+" ");//Output
}
System.out.println();
}
public static void main(String args[])
{
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class TwoD_Array
3. Declare class members:
a. Scanner sc
b. int a[][] (2D Array)
c. int m (Number of Rows)
d. int n (Number of Columns)
4. Define parameterized constructor:
a. TwoD_Array(int mm, int nn) b. Set m to mm c. Set n to nn
d. Initialize 2D array a with dimensions m rows and n columns
OUTPUT: Enter
Elements: 1 2 3 4 5
6 7 8 9 Array:(Matrix
Form) 1 2 3 4 5 6 7 8
2. TwoD_Min_Max
/** Program to find Minimum and Maximum Element of a Two Dimensional Array */
import java.util.*;
class TwoD_Min_Max
{
Scanner sc=new Scanner(System.in);
int m=3,n=3;
int a[][] = new int[m][n];
a[i][j]=sc.nextInt();//Input
}
System.out.println("Array:(Matrix Form)");
System.out.print(a[i][j]+" ");//Output
}
System.out.println();
int min=a[0][0];
if(a[i][j]<min)
{
min=a[i][j];
}
int max=a[0][0];
for (int i=0;i<m;i++) //row
{
if(a[i][j]>max)
max=a[i][j];
}
System.out.println("Maximum Number "+max);
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class TwoD_Min_Max
3. Declare class members:
a. Scanner sc
b. int m (Number of Rows)
c. int n (Number of Columns)
d. int a[][] (2D Array)
4. Initialize array dimensions:
a. Set m and n to 3
b. Initialize 2D array a with dimensions m rows and n columns
5. Input elements into array:
a. Print "Enter Elements: "
6. Display array in matrix form:
a. Print "Array: (Matrix Form)"
b. Use nested loops to iterate through rows and columns:
i. Print each element of the array in matrix form ii.
Move to the next line after printing each row
7. Find minimum element:
a. Initialize int min to a[0][0]
i. If the current element is less than min, update min with the current element
8. Print minimum element:
- Print "Minimum Number" followed by the value of min
9. Find maximum element:
a. Initialize int max to a[0][0]
i. If the current element is greater than max, update max with the current
element
10. Print maximum element:
- Print "Maximum Number" followed by the value of max
OUTPUT:
Enter Elements:
1
2
3
4
5
6
7
8
9
Array:(Matrix Form)
123
456
789
Minimum Number 1
Maximum Number 9
3. TwoD_Symmetric
/** Program to check for a Symmetric Matrix */
import java.util.*;
class TwoD_Symmetric
{
int m=3,n=3;
int a[][] = new int[m][n];
a[i][j]=sc.nextInt();//Input
System.out.println("Array:(Matrix Form)");
System.out.print(a[i][j]+" ");//Output
}
System.out.println();
int k=0;
if(a[i][j]==a[j][i])
k=1;
if(k==1)
System.out.println("Symmetric");
else
System.out.println("Not Symmetric");
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class TwoD_Symmetric
3. Declare class members:
a. Scanner sc
b. int m (Number of Rows)
c. int n (Number of Columns)
d. int a[][] (2D Array)
4. Initialize array dimensions:
a. Set m and n to 3
b. Initialize 2D array a with dimensions m rows and n columns
5. Input elements into array:
a. Print "Enter Elements: "
b. Use nested loops to iterate through rows and columns:
i. Read an integer from the user and store it in the corresponding position of
the array
6. Display array in matrix form:
a. Print "Array: (Matrix Form)"
b. Use nested loops to iterate through rows and columns:
i. Print each element of the array in matrix form
ii. Move to the next line after printing each row
7. Check for symmetry:
a. Initialize int k to 0
b. Use nested loops to iterate through rows and columns:
i. If a[i][j] is equal to a[j][i], set k to 1
8. Print result:
a. If k is equal to 1, print "Symmetric"
b. Otherwise, print "Not Symmetric"
9. Close the Scanner object (sc).
OUTPUT: Enter Elements: 7 5 1 5 8 3 1 3
4 Array:(Matrix Form) 7 5 1 5 8 3 1 3 4
Symmetric 4. TwoD_TRC_Sums
/** Program to find Total Sum, Row Sums and Column Sums of a Two Dimensional Array */
import java.util.*;
class TwoD_TRC_Sums
{
a[i][j]=sc.nextInt();//Input
}
System.out.println("Array:(Matrix Form)");
for(int i=0;i<m;i++)//Loop for Rows(m)
{
System.out.print(a[i][j]+" ");//Output
System.out.println();
int totalsum=0;
for(int i=0;i<m;i++)//Loop for Rows(m)
{
int rowsum=0,colsum=0;
for(int j=0;j<n;j++)//Loop for Columns(n)
{
totalsum+=a[i][j];
rowsum+=a[i][j];
colsum+=a[j][i];
}
System.out.println("Sum of Row "+(i+1)+"="+rowsum);//Output
System.out.println();
System.out.println("Sum of Column "+(i+1)+"="+colsum);//Output
System.out.println();
}
System.out.print("Total Sum of Elements: "+totalsum);//Output
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class TwoD_TRC_Sums
3. Declare class members:
a. Scanner sc
b. int m (Number of Rows)
c. int n (Number of Columns)
d. int a[][] (2D Array)
4. Initialize array dimensions:
a. Set m and n to 3
b. Initialize 2D array a with dimensions m rows and n columns
5. Input elements into array:
a. Print "Enter Elements: "
b. Use nested loops to iterate through rows and columns:
6. Display array in matrix form:
a. Print "Array: (Matrix Form)"
b. Use nested loops to iterate through rows and columns:
i. Print each element of the array in matrix form ii.
Move to the next line after printing each row
7. Calculate total sum, row sums, and column sums:
a. Initialize int totalsum to 0
b. Use nested loops to iterate through rows and columns:
i. Calculate and update totalsum, rowsum, and colsum during each iteration
ii. Print the sum of the current row and column after each row iteration
8. Print total sum:
- Print "Total Sum of Elements: " followed by the value of totalsum
9. Close the Scanner object (sc).
OUTPUT: Enter Elements: 1 2 3 4 5 6 7 8
9 Array:(Matrix Form) 1 2 3 4 5 6 7 8 9
Sum of Row 1=6
/** Program to find Sum of Left and Right Diagonal Elements of a Two Dimensional Array */
import java.util.*;
class TwoD_Diagonal_Sums
{
a[i][j]=sc.nextInt();//Input
}
System.out.println("Array:(Matrix Form)");
for(int i=0;i<m;i++)//Loop for Rows(m)
{
System.out.print(a[i][j]+" ");//Output
System.out.println();
}
int t=m=n;
int ldsum=0,rdsum=0;
for(int i=0;i<m;i++)//Loop for Rows(m)
{
if(i==j)
ldsum+=a[i][j]; //Left Diagonal Sum Logic ie. When row no.==column no.
else if(i!=j)
rdsum+=a[i][t-(i+1)]; //Right agonal Sum Logic ie. When row increases and column
decreases simaltaneously
}
}
rdsum=rdsum/2;
ALGORITHM:
1. Import java utilities: import java.util.*; 2.
Define the class: class TwoD_Diagonal_Sums 3.
Declare class members:
a. Scanner sc
b. int m (Number of Rows - assumed equal to Number of Columns)
c. int n (Number of Columns)
d. int a[][] (2D Array)
4. Initialize array dimensions:
a. Set m and n to 3 (for a 3x3 square array)
b. Initialize 2D array a with dimensions m rows and n columns
5. Input elements into array:
a. Print "Enter Elements: "
b. Use nested loops to iterate through rows and columns:
6. Display array in matrix form:
a. Print "Array: (Matrix Form)"
b. Use nested loops to iterate through rows and columns:
i. Print each element of the array in matrix form
ii. Move to the next line after printing each row
7. Calculate sum of left and right diagonal elements:
a. Initialize int t to the value of m
b. Use nested loops to iterate through rows and columns:
i. If i is equal to j, update ldsum with the current element
(Left Diagonal Sum Logic)
ii. If i is not equal to j, update rdsum with the element from the right
diagonal position (Right Diagonal Sum Logic)
8. Adjust right diagonal sum:
- Divide rdsum by 2
9. Print results: 10. Close the
Scanner object (sc)
OUTPUT: Enter Elements: 1 2 3 4 5 6 7 8
9 Array:(Matrix Form) 1 2 3 4 5 6 7 8 9
int m=3,n=3;
int a[][] = new int[m][n];
a[i][j]=sc.nextInt();//Input
}
System.out.println("Array:(Matrix Form)");
System.out.print(a[i][j]+" ");//Output
}
System.out.println();
for(int i=0;i<m;i++)
for(int j=0;j<n-1;j++)
{
for(int k=0;k<n-j-1;k++)
if(a[i][k]>a[i][k+1])//Ascending Order
{
int t=a[i][k];
a[i][k]=a[i][k+1];
a[i][k+1]=t;
System.out.print(a[i][j]+" ");//Output
System.out.println();
}
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class TwoD_Row_Sort
3. Declare class members:
a. Scanner sc
b. int m (Number of Rows)
c. int n (Number of Columns)
d. int a[][] (2D Array)
4. Initialize array dimensions:
a. Set m and n to 3 (for a 3x3 array)
b. Initialize 2D array a with dimensions m rows and n columns
5. Input elements into array:
6. Display original array in matrix form:
a. Print "Array: (Matrix Form)"
b. Use nested loops to iterate through rows and columns:
i. Print each element of the array in matrix form
ii. Move to the next line after printing each row
7. Sort each row in ascending order:
a. Use nested loops to iterate through rows:
i. Use a sorting algorithm (e.g., Bubble Sort) to sort each row in
ascending order
ii. The sorting logic is applied to each row individually
8. Display row sorted array in matrix form:
9. Close the Scanner object (sc)
OUTPUT: Enter
Elements: 10 9 8
76543
2 Array:(Matrix Form) 10 9 8 7 6 5 4 3 2 Row Sorted Array:
(Matrix Form) 8 9 10 5 6 7 2 3 4 7. TwoD_Column_Sort /**
Program to sort each Column in a Two Dimensional Array */
import java.util.*; class TwoD_Column_Sort {
int m=3,n=3;
int a[][] = new int[m][n];
a[i][j]=sc.nextInt();//Input
}
System.out.println("Array:(Matrix Form)");
for(int i=0;i<m;i++)//Loop for Rows(m)
System.out.print(a[i][j]+" ");//Output
System.out.println();
for(int i=0;i<m;i++)
for(int j=0;j<n-1;j++)
for(int k=0;k<n-j-1;k++)
int t=a[k][i];
a[k][i]=a[k+1][i];
a[k+1][i]=t;
}
}
System.out.print(a[i][j]+" ");//Output
}
System.out.println();
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class TwoD_Column_Sort
3. Declare class members:
a. Scanner sc
b. int m (Number of Rows)
c. int n (Number of Columns)
d. int a[][] (2D Array)
4. Initialize array dimensions:
a. Set m and n to 3 (for a 3x3 array)
b. Initialize 2D array a with dimensions m rows and n columns
5. Input elements into array:
a. Print "Enter Elements: "
b. Use nested loops to iterate through rows and columns:
i. Read an integer from the user and store it in the corresponding position of
the array
6. Display original array in matrix form:
7. Sort each column in ascending order:
a. Use nested loops to iterate through columns:
i. Use a sorting algorithm (e.g., Bubble Sort) to sort each column in ascending
order ii. The sorting logic is applied to each column individually
OUTPUT: Enter
Elements: 9 3 7
61
2 9 2 4 Array:(Matrix Form) 9 3 7 6 1 2 9 2 4 Column Sorted Array:(Matrix Form) 6 1 2 9 2 4 9 3 7 8.
TwoD_NB_B /** Program to declare a square matrix A[][] of order (M × M) where 'M' must be
greater than 3 and
less than 10.
Allow the user to input positive integers into this matrix. Perform the following tasks on the matrix:
(i)Sort the non-boundary elements in ascending order using any standard sorting technique and
rearrange them in the matrix.
(ii)Calculate the sum of both the diagonals.
(iii)Display the Original matrix, Rearranged matrix and only the Diagonal elements of the rearranged
matrix with their sum. */
import java.util.*;
class TwoD_NB_B
{
int m=sc.nextInt();
int a[][]=new int[m][m];//Square Matrix
a[i][j]=sc.nextInt();//Input
System.out.print(a[i][j]+" ");//Output
System.out.println();
int k=0;
for(int i=1;i<m-1;i++)
{
for(int j=1;j<m-1;j++)
for(int i=0;i<k-1;i++)
for(int j=0;j<k-i-1;j++)
{
if(b[j]>b[j+1]) //Ascending Order Sort
int t=b[j];
b[j]=b[j+1];
b[j+1]=t;
k=0;
for(int i=1;i<m-1;i++)
{
for(int j=1;j<m-1;j++)
a[i][j]=b[k++]; //Rearrange total Matrix
System.out.print(a[i][j]+" ");//Output
System.out.println();
int dsum=0;
if((i==j) || (i+j==m-1))
{
}
else
{
System.out.print("\t");
}
System.out.println();
}
System.out.println("Sum of Diagonal Elements: "+dsum);
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class TwoD_NB_B
3. Declare class members:
a. Scanner sc
b. int m (Order of the Square Matrix)
c. int a[][] (2D Array)
4. Initialize matrix dimensions:
a. Print "Enter Order of Square Matrix(m*m): "
b. Read an integer from the user and store it in m
c. Initialize a square 2D array a with dimensions m x m
5. Input elements into matrix: a. Print "Enter Elements: "
b. Use nested loops to iterate through rows and columns:
i. Read an integer from the user and store it in the corresponding position of
the matrix
6. Display original matrix in matrix form:
a. Print "Original Array: (Matrix Form)"
b. Use nested loops to iterate through rows and columns:
i. Print each element of the matrix in matrix form
ii. Move to the next line after printing each row
7. Extract and sort non-boundary elements:
a. Initialize an array b to store non-boundary elements
b. Use nested loops to iterate through rows and columns (excluding the boundary):
i. Extract non-boundary elements and store them in array b
c. Use a sorting algorithm (e.g., Bubble Sort) to sort array b in ascending order
8. Rearrange matrix with sorted non-boundary elements:
a. Use nested loops to iterate through rows and columns (excluding the boundary):
i. Replace the original non-boundary elements with the sorted ones from array b
9. Display rearranged matrix in matrix form:
a. Print "Rearranged Array: (Matrix Form)"
b. Use nested loops to iterate through rows and columns:
i. Print each element of the rearranged matrix in matrix form
ii. Move to the next line after printing each row
10. Calculate and display diagonal elements with their sum:
a. Initialize a variable dsum to store the sum of diagonal elements
b. Print "Diagonal Elements:"
c. Use nested loops to iterate through rows and columns:
i. Check if the element is on either main or secondary diagonal
ii. Print the diagonal elements and accumulate their sum in dsum
iii. Print a tab character for non-diagonal elements
iv. Move to the next line after each row
11. Display sum of diagonal elements:
a. Print "Sum of Diagonal Elements: " followed by the value of dsum
12. Close the Scanner object (sc)
OUTPUT:
Enter Order of Square Matrix(m*m):
3
Enter Elements:
8
5
3
0
1
4
Original Array:(Matrix Form) 8 2
4 6 5 3 0 1 4 Rearranged Array:
(Matrix Form) 8 2 4 6 5 3 0 1 4
Diagonal Elements:
8 4
0 4
9. Mirror
class Mirror
int m=3;
a[i][j]=sc.nextInt();//Input
System.out.println("Array:(Matrix Form)");
System.out.print(a[i][j]+" ");//Output
System.out.println();
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
b[i][m-1-j]=a[i][j];
System.out.print(b[i][j]+" ");//Output
}
System.out.println();
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Mirror
3. Declare class members:
a. Scanner sc
b. int m (Order of the Square Matrix)
c. int a[][] (Original 2D Array)
d. int b[][] (Mirror Image 2D Array)
4. Initialize matrix dimensions:
a. Initialize m to 3
b. Initialize two square 2D arrays, a and b, with dimensions m x m
5. Input elements into matrix:
a. Print "Enter Elements: "
b. Use nested loops to iterate through rows and columns:
i. Read an integer from the user and store it in the corresponding position of
the original matrix a
6. Display original matrix in matrix form:
7. Create mirror image:
a. Use nested loops to iterate through rows and columns:
i. Copy elements from the original matrix a to the mirror image matrix b,
reversing the order of columns:
- b[i][m-1-j] = a[i][j]
8. Display mirror image in matrix form:
OUTPUT:
Enter Elements:
1
2
3
4
5
6
7
8
9
Array:(Matrix Form)
123
456
789
Mirror Image:(Matrix Form)
321
654
987
10. Denomination
/** Program to accept amount from user and display the break-up in descending order denominaion
along with total no. of notes */
import java.util.*;
class Denomination
{
int amt=sc.nextInt();
int c=amt;
int rev=0;
int d=0;
while(c>0)
d=c%10;
rev=rev*10+d;
c=c/10;
while(rev>0)
d=rev%10;
switch(d)
case 0:
System.out.println("ZERO");
break;
case 1:
System.out.println("ONE");
break;
case 2:
System.out.println("TWO");
break;
case 3:
System.out.println("THREE");
break;
case 4:
System.out.println("FOUR");
break;
case 5:
System.out.println("FIVE");
break;
case 6:
System.out.println("SIX");
break;
case 7:
System.out.println("SEVEN");
break;
case 8:
System.out.println("EIGHT");
break;
case 9:
System.out.println("NINE");
break;
}
rev=rev/10;
System.out.println("OUTPUT: ");
int total=0;
int t=0;
while(amt!=0)
rev=amt/den[t];
if(rev!=0)
{
System.out.println(den[t]+"x"+rev+"="+rev*den[t]);
total+=rev;
}
amt=amt%den[t];
t++;
}
System.out.println("Total Number of Notes= "+total);
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Denomination
3. Declare class members:
a. Scanner sc
b. int den[] (Denominations array)
c. int amt (Amount)
d. int c (Temporary variable)
e. int rev (Reverse of the amount)
f. int d (Digit variable)
g. int total (Total number of notes)
h. int t (Index for denominations array)
4. Initialize denominations array:
a. Initialize den array with denominations in descending order: {1000, 500, 100,
50, 20, 10, 5, 2, 1}
5. Input amount:
6. Calculate reverse of amount:
a. Initialize c with the value of amt
b. Initialize rev and d to 0
c. Use a loop to reverse the digits of amt and store the result in rev
7. Display reverse of amount in words:
a. Use a loop to extract each digit from the reversed amount and display it in
words using a switch statement
8. Output denomination break-up:
a. Print "OUTPUT:"
b. Initialize total and t to 0
c. Use a loop to calculate the number of each denomination and display break-up
d. Update the total number of notes
9. Display total number of notes
OUTPUT:
Enter Amount:
4568321
FOUR
FIVE
SIX
EIGHT
THREE
TWO
ONE
OUTPUT:
1000x4568=4568000
100x3=300
20x1=20
1x1=1
Total Number of Notes= 4573
STRING
1. String_Tokenizer
/** Program to input a Sentence and check for Validity and Display the OG Sentence.
* Convert the Sentence into Uppercase and Display the New Sentence.
* Also store the words along with their lengths */
import java.util.*;
class String_Tokenizer
String s=sc.nextLine();
int l=s.length();
char ch=s.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!')
s=s.toUpperCase();
s=s.substring(0,l-1);
int w=st.countTokens();
while(st.hasMoreTokens())
String s1=st.nextToken();
int l1=s1.length();
System.out.println(s1+"\t"+l1);
else
System.out.println("Invalid Input");
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class String_Tokenizer
3. Declare class members:
a. Scanner sc
b. String s
c. int l
d. char ch
4. Input sentence:
a. Print "Enter a Sentence: "
b. Read a line from the user and store it in s
c. Get the length of the sentence and store it in l
d. Extract the last character of the sentence and store it in ch
5. Check sentence validity:
a. Check if the last character is '.', '?' or '!'
b. If false, print "Invalid Input" and terminate the program
6. Convert sentence to uppercase:
a. Convert the sentence to uppercase using s.toUpperCase() and store the result
back in s
7. Remove ending punctuation:
a. Remove the last character from the sentence using s.substring(0, l-1)
8. Tokenize the sentence:
a. Use StringTokenizer to tokenize the modified sentence
b. Count the number of tokens and store it in w
c. Print "Total Number of Words: " followed by the value of w
9. Display words and their lengths:
a. Print "Words are: "
b. Use a loop with StringTokenizer to iterate through each word
c. For each word, get its length and display the word along with its length
OUTPUT:
Enter a Sentence:
Hi hello Java!
Words are:
HI 2
HELLO 5
JAVA 4
2. VowelConsonant
/** Program to display the Frequency of Vowels and Consonants in each word in a sentence */
import java.util.*;
class VowelConsonant
String s=sc.nextLine();
int l=s.length();
char ch=s.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!')
s=s.toUpperCase();
s=s.substring(0,l-1);
int w=st.countTokens();
System.out.println("Number of Words: "+w);
System.out.println("Words:"+"\t"+"Vowels"+"\t"+"Consonants");
while(st.hasMoreTokens())
{
String s1=st.nextToken();
int l1=s1.length();
int vc=0,cc=0;
for(int i=0;i<l1;i++)
{
char ch1=s1.charAt(i);
if(ch1=='A' || ch1=='E' || ch1=='I' || ch1=='O' || ch1=='U')
vc++;
else if(ch1!='A' || ch1!='E' || ch1!='I' || ch1!='O' || ch1!='U')
cc++;
}
System.out.println(s1+"\t"+vc+"\t"+cc);
else
System.out.println("Invalid Input");
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class VowelConsonant
3. Declare class members:
a. Scanner sc
b. String s
c. int l
d. char ch
4. Input sentence:
a. Print "Enter a Sentence: "
b. Read a line from the user and store it in s
c. Get the length of the sentence and store it in l
d. Extract the last character of the sentence and store it in ch
5. Check sentence validity:
a. Check if the last character is '.', '?' or '!'
b. If false, print "Invalid Input" and terminate the program
6. Convert sentence to uppercase:
a. Convert the sentence to uppercase using s.toUpperCase() and store the result
back in s
7. Remove ending punctuation:
a. Remove the last character from the sentence using s.substring(0, l-1)
8. Tokenize the sentence:
a. Use StringTokenizer to tokenize the modified sentence
b. Count the number of tokens and store it in w
c. Print "Number of Words: " followed by the value of w
d. Print column headers: "Words", "Vowels", "Consonants"
9. Display frequency of vowels and consonants:
a. Use a loop with StringTokenizer to iterate through each word
b. For each word, initialize vc (vowel count) and cc (consonant count) to 0
c. Use a nested loop to iterate through each character of the word
d. For each character, check if it's a vowel (A, E, I, O, U) and increment vc,
otherwise increment cc
e. Print the word, vc, and cc for each word
OUTPUT:
Enter a Sentence:
it is a good day!
Number of Words: 5
Words: Vowels Consonants
IT IS A
1 1
GOOD 2 1 1
1 0
2
DAY 1 2
3. Alphabetical_Order
String s=sc.nextLine();
int l=s.length();
char ch=s.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!')
s=s.toUpperCase();
s=s.substring(0,l-1);
String s1[]=s.split(" "); //Splits the sentence into words ie, through " "
int l1=s1.length;
for(int i=0;i<l1;i++)
for(int j=0;j<l1-i-1;j++)
if(s1[j].compareTo(s1[j+1])>0)//Bubble Sort
String t=s1[j];
s1[j]=s1[j+1];
s1[j+1]=t;
for(int i=0;i<l1;i++)
System.out.print(s1[i]+" ");
}
else
System.out.println("Invalid Input");
}
}
ALGORITHM:
1. Import java utilities: import java.util.*; 2.
Define the class: class Alphabetical_Order 3.
Declare class members:
a. Scanner sc
b. String s
c. int l
d. char ch
4. Input sentence:
a. Print "Enter a Sentence: "
b. Read a line from the user and store it in s
c. Get the length of the sentence and store it in l
d. Extract the last character of the sentence and store it in ch
5. Check sentence validity:
a. Check if the last character is '.', '?' or '!'
b. If false, print "Invalid Input" and terminate the program
6. Convert sentence to uppercase:
a. Convert the sentence to uppercase using s.toUpperCase() and store the result
back in s
7. Remove ending punctuation:
a. Remove the last character from the sentence using s.substring(0, l-1)
8. Split sentence into words:
a. Use String.split(" ") to split the modified sentence into an array of words,
stored in s1
9. Sort words alphabetically:
a. Use a nested loop with the Bubble Sort algorithm to arrange the words in
alphabetical order
b. Compare adjacent words using compareTo and swap them if necessary
10. Display rearranged sentence:
a. Print "Rearranged Sentence: " followed by the sorted words separated by spaces
OUTPUT:
Enter a Sentence:
Java is a computer software.
Rearranged Sentence:
A COMPUTER IS JAVA SOFTWARE
4. Ceaser_Cipher
/** Program to shift the characters of a string by 13 according to their postion in alphabets(26) */
import java.util.*;
class Ceaser_Cipher
{
char ch=s.charAt(i);
if(ch<'N')
ss+=(char)(ch+13);
else
ss+=(char)(ch-13);
}
System.out.println(ss);
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Ceaser_Cipher
3. Declare class members:
a. Scanner sc
b. String s
c. int l
d. String ss
4. Input sentence:
a. Print "Enter a Sentence: "
b. Read a line from the user and store it in s
c. Get the length of the sentence and store it in l
5. Convert sentence to uppercase:
a. Convert the entire sentence to uppercase using s.toUpperCase()
6. Shift characters by 13:
a. Initialize an empty string ss
b. Use a loop to iterate through each character of the sentence
c. For each character, check if it is less than 'N' (in the ASCII sequence)
i. If true, add 13 to the character's ASCII value
ii. If false, subtract 13 from the character's ASCII value
d. Append the modified character to the string ss
7. Display the result:
a. Print the shifted string ss
OUTPUT:
Enter a Sentence:
I am a good boy!
V-T`-T-ZbbW-Ubl.
5. Unique_Word
boolean check(): checks and returns true if word starts and ends with a vowel.
void show(): Displays thw word starting and ending with a vowel by invoking boolean check() */
import java.util.*;
class Unique_Word
{
String word;
int len;
Unique_Word()
{
word="";
len=0;
}
Scanner sc=new Scanner(System.in);
void accept()
word=sc.next();
len=word.length();
boolean checkv()
char ch1=word.charAt(0);
char ch2=word.charAt(len-1);
if((ch1=='A'||ch1=='E'||ch1=='I'||ch1=='O'||ch1=='U') &&
(ch2=='A'||ch2=='E'||ch2=='I'||ch2=='O'||ch2=='U'))
return true;
else
return false;
void display()
if(checkv()==true)
else
System.out.println("The Word "+word+" does not start and end with a vowel.");
uw.display();
ALGORITHM:
1. Import java utilities: import java.util.*; 2.
Define the class: class Unique_Word 3. Declare
data members:
a. String word
b. int len
4. Create a default constructor Unique_Word():
a. Initialize word to an empty string.
b. Initialize len to 0.
5. Declare a Scanner object sc for input.
6. Create a method accept():
a. Print "Enter a Word(Uppercase): ".
b. Read a word from the user and store it in the word variable.
c. Calculate and store the length of the word in the len variable.
7. Create a method checkv():
a. Get the first character (ch1) and the last character (ch2) of the word.
b. Check if ch1 and ch2 are vowels ('A', 'E', 'I', 'O', 'U').
c. Return true if both ch1 and ch2 are vowels; otherwise, return false.
8. Create a method display():
a. Invoke checkv() to determine if the word starts and ends with a vowel.
b. Print a message based on the result.
9. Create the main method:
a. Create an instance of the Unique_Word class (uw).
b. Invoke the accept() method to input a word.
c. Invoke the display() method to check and display if the word starts and ends
with a vowel.
OUTPUT:
Enter a Word(Uppercase):
APPLE
String s=sc.nextLine();
int l=s.length();
char ch=s.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!')
{
s=s.toUpperCase();
s=s.substring(0,l-1);
StringTokenizer st=new StringTokenizer(s);
int w=st.countTokens();
System.out.println("Total Number of Words: "+w);
while(st.hasMoreTokens())
{
String s1=st.nextToken();
int l1=s1.length();
int vc=0;
int flag=0;
char ch1=s1.charAt(0);
for(int i=0;i<l1;i++)
{
char chi=s1.charAt(i);
char ch2=s1.charAt(l1-1);
if((ch1=='A'||ch1=='E'||ch1=='I'||ch1=='O'||ch1=='U') &&
(ch2=='A'||ch2=='E'||ch2=='I'||ch2=='O'||ch2=='U'))
flag=1;
if((chi=='A'||chi=='E'||chi=='I'||chi=='O'||chi=='U'))
vc++;
}
}
if(flag==1)
System.out.println(s1+"\t"+vc+" Vowels");
}
else
System.out.println("Invalid Input");
ALGORITHM:
1. Import java utilities: import java.util.*; 2.
Define the class: class Unique_Sentence 3.
Main method:
a. Create a Scanner object sc for input.
b. Print "Enter a Sentence: ".
c. Read a sentence from the user and store it in the variable s.
d. Get the last character (ch) of the sentence.
4. Check Sentence Validity:
- Check if ch is '.', '?', or '!'. If not, print "Invalid Input" and exit the
program.
5. Preprocess Sentence:
a. Convert the sentence to uppercase using s.toUpperCase().
b. Remove the last character using s.substring(0, l-1).
6. Tokenization:
- Tokenize the preprocessed sentence using StringTokenizer st = new
StringTokenizer(s).
7. Count Number of Words:
- Get the total number of words using st.countTokens() and store it in w.
- Print "Total Number of Words: " + w.
8. Word Processing Loop:
- Iterate through each word using a while loop while (st.hasMoreTokens()):
a. Get the next word using String s1 = st.nextToken().
b. Get the length of the word using int l1 = s1.length().
9. Word Processing:
a. Initialize variables vc (vowel count) and flag to 0.
b. Get the first character (ch1) of the word.
c. Iterate through each character in the word using a for loop:
i. Get the current character (chi) and the last character (ch2) of the word.
ii. Check if the word starts and ends with a vowel.
iii. If yes, set flag to 1 and count the vowels (vc).
d. If flag is 1, print "Number of Words starting and ending with Vowels:" and
display the word and its vowel count.
10. Output Invalid Input:
- If the sentence does not end with '.', '?', or '!', print "Invalid Input".
OUTPUT:
Enter a Sentence:
an apple a day keeps the doctor awa!
Total Number of Words: 8
Number of Words starting and ending with Vowels:
APPLE 2 Vowels
Number of Words starting and ending with Vowels:
A 1 Vowels
AWA 2 Vowels
7. Palindrome_Sentence
/** Program to display only the palindrome words of a sentence along with their frequencies. */
import java.util.*;
class Palindrome_Sentence
{
String s=sc.nextLine();
int l=s.length();
char ch=s.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!')
s=s.toUpperCase();
s=s.substring(0,l-1);
int w=st.countTokens();
int pw=0;
while(st.hasMoreTokens())
String s1=st.nextToken();
int l1=s1.length();
String rev="";
int flag=0;
for(int i=l1-1;i>=0;i--)
char chr=s1.charAt(i);
rev+=chr;
if(s1.compareTo(rev)==0)
flag=1;
pw++;
if(flag==1)
System.out.println(rev);
}
else
System.out.println("Invalid Input");
ALGORITHM:
OUTPUT:
Enter a Sentence:
Madam speaks Malayalam.
MADAM
MALAYALAM
8. Insert_Word
/** Program to insert a given word in a given position in a given sentence */
import java.util.*;
class Insert_Word
{
String s=sc.nextLine();
int l=s.length();
char ch=s.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!')
{
s=s.toUpperCase();
s=s.substring(0,l-1);
System.out.println("Enter the Word to be Inserted: ");
String word=sc.next();
word=word.toUpperCase();
System.out.println("Enter the Position of the Word to be Inserted: ");
int pos=sc.nextInt();
String s1[]=s.split(" "); //Splits the sentence into words ie, through " "
int l1=s1.length;
String s2[]=new String [l1+1]; //New array with an extra block [] for insertion of a word
s2[pos-1]=word; //Assigning the word to be insrted in the required position in the new array
for(int i=0;i<=l1;i++)
System.out.println("Invalid Input");
}
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Palindrome_Sentence
3. Main method:
a. Create a Scanner object sc for input.
b. Print "Enter a Sentence: ".
c. Read a sentence from the user and store it in the variable s.
d. Get the last character (ch) of the sentence.
4. Check Sentence Validity:
- Check if ch is '.', '?', or '!'. If not, print "Invalid Input" and exit the
program.
5. Preprocess Sentence:
a. Convert the sentence to uppercase using s.toUpperCase().
b. Remove the last character using s.substring(0, l-1).
6. Tokenization:
- Tokenize the preprocessed sentence using StringTokenizer st = new
StringTokenizer(s).
7. Count Number of Words:
- Get the total number of words using st.countTokens() and store it in w.
- Print "Total Number of Words: " + w.
8. Palindrome Word Processing Loop:
- Initialize a variable pw (palindrome word count) to 0.
- Iterate through each word using a while loop while (st.hasMoreTokens()):
a. Get the next word using String s1 = st.nextToken().
b. Get the length of the word using int l1 = s1.length().
c. Initialize an empty string rev for word reversal.
d. Initialize a variable flag to 0.
9. Palindrome Checking Loop:
- Iterate through each character of the word in reverse order using a for loop:
a. Get the current character (chr).
b. Append chr to rev.
c. Check if the original word is equal to its reverse (s1.compareTo(rev) == 0).
d. If yes, set flag to 1 and increment pw.
- If flag is 1, print the reversed palindrome word.
10. Output Palindrome Count:
- Print "Number of Palindrome Words: " + pw.
11. Output Invalid Input:
- If the sentence does not end with '.', '?', or '!', print "Invalid Input".
OUTPUT:
Enter a Sentence:
It is a day.
Enter the Word to be Inserted:
good
Enter the Position of the Word to be Inserted:
4
IT IS A GOOD DAY
9. Delete _Word
s=s.toUpperCase();
s=s.substring(0,l-1);
System.out.println("Enter the Word to be Deleted: ");
String word=sc.next();
word=word.toUpperCase();
System.out.println("Enter the Position of the Word to be Deleted: ");
int pos=sc.nextInt();
String s1[]=s.split(" "); //Splits the sentence into words ie, through " "
int l1=s1.length;
String ns="";
for(int i=0;i<pos-1;i++) //Loop for framing words before the position/delete word
for(int i=pos;i<l1;i++) //Loop for framing words after the position/delete word
ns=ns+" "+s1[i]; //Equating words after position/delete word by excluding the word in the
position
System.out.println(ns); //Output
}
else
System.out.println("Invalid Input");
}
}
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Delete_Word
3. Main method:
a. Create a Scanner object sc for input.
b. Print "Enter a Sentence: ".
c. Read a sentence from the user and store it in the variable s.
d. Get the last character (ch) of the sentence.
4. Check Sentence Validity:
- Check if ch is '.', '?', or '!'. If not, print "Invalid Input" and exit the
program.
5. Preprocess Sentence:
a. Convert the sentence to uppercase using s.toUpperCase().
b. Remove the last character using s.substring(0, l-1).
6. Input Word to Delete:
- Print "Enter the Word to be Deleted: ".
- Read the word to be deleted from the user and store it in the variable word.
- Convert word to uppercase using word.toUpperCase().
7. Input Position of Word to Delete:
- Print "Enter the Position of the Word to be Deleted: ".
- Read the position of the word to be deleted from the user and store it in the
variable pos.
8. Tokenization:
- Split the preprocessed sentence into words using String s1[] = s.split(" ").
9. Create Modified Sentence:
- Initialize an empty string ns to store the modified sentence.
- Use a loop to concatenate words before the position/delete word:
- Use another loop to concatenate words after the position/delete word (excluding
the word at the given position): for (int i = pos; i < l1; i++) ns += " " + s1[i].
10. Print Modified Sentence:
OUTPUT:
Enter a Sentence:
bad
HE IS A GOOD PERSON
10. Potential_Word
class Potential_Word
String s=sc.nextLine();
int l=s.length();
char ch=s.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!')
s=s.toUpperCase();
s=s.substring(0,l-1);
int w=st.countTokens();
while(st.hasMoreTokens())
String s1=st.nextToken();
int l1=s1.length();
int sum=0;
for(int i=0;i<l1;i++)
char chw=s1.charAt(i);
sum=sum+((int)(chw));
System.out.println(s1+"-"+sum);
}
}
else
System.out.println("Invalid Input");
ALGORITHM:
1. Import java utilities: import java.util.*;
2. Define the class: class Potential_Word
3. Main method:
a. Create a Scanner object sc for input.
b. Print "Enter a Sentence: ".
c. Read a sentence from the user and store it in the variable s.
d. Get the last character (ch) of the sentence.
e. Print "Potential=Sum of ASCII values of a Word".
4. Check Sentence Validity:
- Check if ch is '.', '?', or '!'. If not, print "Invalid Input" and exit the
program.
5. Preprocess Sentence
- Split the preprocessed sentence into words
7. Count Words:
- Count the total number of words using int w = st.countTokens().
8. Calculate Potential of Words:
- Print "Potential of Words: ".
- Use a while loop to iterate through each word:
a. Inside the loop, get the next word using String s1 = st.nextToken().
b. Get the length of the word (l1).
c. Use a loop to iterate through each character of the word and calculate the
sum of ASCII values.
d. Print the word and its potential (sum of ASCII values).
9. Output Total Number of Words:
OUTPUT:
Enter a Sentence:
Potential of Words:
STUDENTS-634
ARE-216
STUDYING-631
IN-151
SCHOOL-456