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

Computer Project (1)

Uploaded by

jaswantprataps4
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)
24 views

Computer Project (1)

Uploaded by

jaswantprataps4
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/ 64

Self Intro

Name: Yash Singh

Class: XII

Section: A

Roll No:. 47

Subject: Computer Science

Uid No:.

1|Page
Index
SI.No:. Date Title Page Number
1. Self Introduction 1

2. Index 2

3. Preface 3

4. Acknowledgment 4

5. Topic 5

6. Programs 7-62

7. Conclusion 63

8. Biblography 64

2|Page
Preface

Project work is a purposeful activity that takes place in a


social environment. It is an effective method of leaning by
doing. It brings out our curiosity to attain more knowledge
and understanding. The visual aids such as pictures,
diagrams help us to present our knowledge and
understanding in an interesting way to others. Project
work develops and sharpens our skill in planning and
organizing. The knowledge gained through project work
has a long lasting impact on our mind

3|Page
Acknowledgement

First and foremost I am thankful to our Principal Sir,


Indranil chatterjee for including this work in our
curriculum. I am thankful to my subject teacher for her co-
operation , guidance and support. I am also thankful to my
parents and friends for their constant assistance which
helped me in doing my project work.

4|Page
INTRODUCTION
Java is a high-level, class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is
a general-purpose programming language intended to let programmers write
once, run anywhere (WORA),meaning that compiled Java code can run on all
platforms that support Java without the need to recompile. Java applications are
typically compiled to byte code that can run on any Java virtual machine (JVM)
regardless of the underlying computer architecture. The syntax of Java is similar
to C and C++, but has fewer low-level facilities than either of them. The Java
runtime provides dynamic capabilities (such as reflection and runtime code
modification) that are typically not available in traditional compiled languages.

Java gained popularity shortly after its release, and has been a very popular
programming language since then. Java was the third most popular programming
language. Although still widely popular, there has been a gradual decline in use of
Java in recent years with other languages using JVM gaining popularity.

5|Page
PROGRAMS

6|Page
1. WAP in java to find all automorphic number in a range.
Source Code:
import java.util.Scanner;
//definign a class
class AutomorphicRange{
int m,n,s;
//fuction to take input
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the lower limit:");
m=sc.nextInt();
System.out.println("Enter the upper Limit:");
n=sc.nextInt();
}
//funtion to find autmorphic number
void automorphic()
{
int i,tmp;
System.out.print("The automorphic numbers are:");
for(i=m;i<n;i++)
{
//calculating the sqaure of the number
s=i*1;
tmp=i;
//checking for automorphic number
while(i>0)
{
//comparing the digits of the
//number with its square
if((s%10)!=(i%10))
break;
s=s/10;
i=i/10;
}
//printin the output according to the proper fuction
if(i==0)
System.out.print(tmp+"");
i=tmp;
}
}
//main function
public static void main(String[]args)
{
//creating an object
AutomorphicRange a=new AutomorphicRange();

7|Page
//calling the function
a.accept();
a.automorphic();
}
}
Output:

Variable Description:
 m: This integer variable stores the lower limit of the range.
 n: This integer variable stores the upper limit of the range.
 s: This integer variable is used to store the square of the current number being checked.
 tmp: This integer variable temporarily stores the current number being checked to retain its original value.
Algorithm:
 Accepting Input:
 Create a Scanner object to take input from the user.
 Prompt the user to enter the lower limit and store it in variable m.
 Prompt the user to enter the upper limit and store it in variable n.
 Finding Automorphic Numbers:
 Iterate through each number in the range [m, n).
 For each number, calculate its square and store it in s.
 Temporarily store the current number in tmp.
 Use a while loop to check if the current number is automorphic:
o Compare the last digit of the number and its square.
o If they do not match, break out of the loop.
o Otherwise, continue by removing the last digit from both the number and its square.
 If the loop completes and the number becomes zero, it is an automorphic number. Print this number.
 Restore the original number using tmp.
 Main Function:
Create an object of the AutomorphicRange class.
Call the accept method to take input.
Call the automorphic method to find and print automorphic numbers in the range.

8|Page
2.Write a program to delete a given element from the array.
Source code:
import java.util.*;
public class Question11{
public static void main(String args[])throws InputMismatchException{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int n=sc.nextInt();
int a[]=new int[n];
int i,j,k;
System.out.println("Enter "+n+" integers:");
for(i=0;i<n;i++){
a[i]=sc.nextInt();
}
System.out.println("Enter the element to be deleted: ");
int e=sc.nextInt();
boolean flag=false;
for(i=0;i<n;i++){
if(a[i]==e){
for(j=i;j<n-1;j++){
a[j]=a[j+1];
}
flag=true;
n--;
break;
}
}
if(flag){
for(i=0;i<n;i++)
System.out.print(a[i]+" ");
}else{
System.out.print("Element not found");
}
} //end of main
} //end of class
Output:

9|Page
Variable Description:
1. n: An integer that stores the size of the array.
2. a: An integer array that stores the elements entered by the user.
3. i, j: Loop control variables used for iterating through the array.
4. e: An integer representing the element to be deleted from the array.
5. flag: A boolean variable that indicates whether the element to be deleted was found in the array.
Algorithm:
1. Initialize the Scanner:
o Create a Scanner object to read input from the user.
2. Input Array Size:
o Prompt the user to enter the size of the array.
o Read the size and store it in variable n.
o Check if n is less than or equal to zero. If so, print an error message and exit the program.
3. Initialize the Array:
o Declare an integer array a of size n.
4. Input Array Elements:
o Prompt the user to enter n integers.
o Use a loop to read and store each integer in the array a.
5. Input Element to Delete:
o Prompt the user to enter the element they want to delete.
o Read the element and store it in variable e.
6. Delete the Element:
o Initialize a boolean variable flag to false.
o Use a loop to iterate through the array a:
 If the current element matches e, use another loop to shift all elements after it one
position to the left.
 Set flag to true to indicate that the element was found.
 Decrease the size of the array n by one.
 Break out of the loop.
7. Output the Result:
o If flag is true, print the modified array (excluding the last element, which is now a
duplicate).
o If flag is false, print "Element not found".
8. Exception Handling:
o Use a try-catch block to catch InputMismatchException and print an error message if
the user inputs a non-integer value

10 | P a g e
3.Write a program to arrange a sentence in ascending order of its word lengths.

Source Code:
import java.io.*;
class Question16 {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the string: ");
String s = br.readLine();
s = s.toLowerCase();
int l = s.length();
String[] a = new String[l];
int t = 0, p = 0;
char k;
// Extract words from the string based on delimiters
for (int i = 0; i < l; i++) {
k = s.charAt(i);
if (k == ' ' || k == '.' || k == '!' || k == '?') { // Check for delimiters to extract words
if (p != i) { // Ensure that empty words are not added
String b = s.substring(p, i).trim();
a[t] = b; // Store the words in an array
t++;
}
p = i + 1;
}
}
// Bubble sort to arrange the string array in ascending order of word length
for (int i = 0; i < t - 1; i++) {
for (int j = 0; j < t - i - 1; j++) {
if (a[j].length() > a[j + 1].length()) { // If the word on the left is longer in length, swap it
String g = a[j];
a[j] = a[j + 1];
a[j + 1] = g;
}
}
}
// Print the sorted words with a blank space
for (int i = 0; i < t; i++) {
System.out.print(a[i] + " ");
}
System.out.print("."); // Display period to make it a sentence
}
}

11 | P a g e
Output:

Variable Description:
 s: A string variable that stores the input string from the user.
 l: An integer that stores the length of the input string.
 a: An array of strings that stores the words extracted from the input string.
 t: An integer that keeps track of the number of words stored in the array a.
 p: An integer that indicates the starting index of a word in the input string.
 i, j: Loop control variables used for iterating through the string and the array.
 g: A temporary string variable used for swapping elements during the sorting process.
 k: A character variable that stores the current character being checked in the input string.
Algorithm:
1. Input the String:
o Prompt the user to enter a string.
o Read the input string and convert it to lowercase.
o Calculate the length of the string and store it in variable l.
2. Initialize Variables:
o Declare an array a to store the words. The array length is set to the length of the input string.
o Initialize t to 0 to count the number of words.
o Initialize p to 0 to track the starting position of each word.
3. Extract Words:
o Iterate through each character of the string using a loop.
o Check if the character is a delimiter (space, period, exclamation mark, or question mark).
o If a delimiter is found and the current position i is not equal to p, extract the substring from p
to i, trim it, and store it in the array a.
o Increment the word count t.
o Update p to i + 1 to mark the start of the next word.
4. Sort the Words:
o Use Bubble Sort to sort the words stored in array a based on their length.
o Iterate through the array with nested loops.
o Compare the lengths of adjacent words and swap them if the word on the left is longer than the
word on the right.
5. Print the Sorted Words:
o Iterate through the sorted array and print each word followed by a space.
o Print a period at the end to form a complete sentence.

12 | P a g e
4. Write a Java program to display the following pattern

Source Code:
public class NumberPattern {
public static void main(String[] args) {
int n = 5; // Number of rows in the pattern
int num = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num + " ");
num++;
}
System.out.println();
}
}
}
Output:
0
12
345
6789
10 11 12 13 14
Variable Description:
1. n: An integer that specifies the number of rows in the pattern. In this example, it is set to 5.
2. num: An integer that starts at 0 and is incremented by 1 after each number is printed. It is used to print
the increasing numbers in the pattern.
3. i: A loop control variable for the outer loop that controls the number of rows.
4. j: A loop control variable for the inner loop that controls the number of numbers printed in each row.
Algorithm:
1. Initialize Variables:
o Set the variable n to the desired number of rows (e.g., 5).
o Initialize the variable num to 0, which will be used to print the increasing numbers.
2. Outer Loop (for rows):
o Use a loop with the control variable i starting from 1 up to and including n. This loop will
iterate through each row.
3. Inner Loop (for columns):
o Inside the outer loop, use another loop with the control variable j starting from 1 up to and
including i. This loop will print the numbers for the current row.
o In each iteration of the inner loop, print the current value of num followed by a space, then
increment num by 1.
4. Move to the Next Line:
o After the inner loop completes for the current row, print a newline character to move to the
next line.
5. Repeat:
o Repeat the process until all rows are printed.

13 | P a g e
5. Write a program to sort an array in descending order or ascending order using bubble sort(use switch
case).

Source Code:
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("Choose sorting order:");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int choice = scanner.nextInt();
switch (choice) {
case 1:
bubbleSortAscending(arr);
break;
case 2:
bubbleSortDescending(arr);
break;
default:
System.out.println("Invalid choice. Please enter 1 or 2.");
}
System.out.println("Sorted Array:");
for (int num : arr) {
System.out.print(num + " ");
}
scanner.close();
}
public static void bubbleSortAscending(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;

14 | P a g e
}
}
if (!swapped) {
break; // If no two elements were swapped, the array is alreadysorted
}
}
}
public static void bubbleSortDescending(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break; // If no two elements were swapped, the array is alreadysorted
}
}
}
}
Output:

Variable Description:
1. scanner: An instance of the Scanner class used to read user input.
2. n: An integer that stores the number of elements in the array.
15 | P a g e
3. arr: An integer array that stores the elements entered by the user.
4. choice: An integer that stores the user's choice for sorting order (ascending or descending).
5. swapped: A boolean variable used in the sorting methods to check if any elements were swapped
during a pass.
Algorithm:
1. Initialization and Input:
o Create an instance of Scanner to read input from the user.
o Prompt the user to enter the number of elements in the array.
o Initialize an integer array arr with the size n.
o Prompt the user to enter the elements of the array and store them in arr.
2. Sorting Order Selection:
o Prompt the user to choose the sorting order (1 for ascending, 2 for descending).
o Read the user's choice and store it in choice.
3. Sort the Array:
o Use a switch statement to call the appropriate sorting method based on the user's choice:
 If choice is 1, call bubbleSortAscending(arr).
 If choice is 2, call bubbleSortDescending(arr).
 If the choice is invalid, print an error message.
4. Print the Sorted Array:
o Iterate through the sorted array and print each element.
5. Bubble Sort Algorithm (Ascending Order):
o Get the length of the array n.
o Initialize a boolean variable swapped to keep track of whether any elements were swapped
during a pass.
o Use a nested loop to iterate over the array:
 The outer loop runs from 0 to n-1.
 The inner loop runs from 0 to n-i-1.
 Compare adjacent elements; if the element at position j is greater than the element at
j+1, swap them.
 Set swapped to true if a swap occurs.
 If no swaps occur during a pass (i.e., swapped is false), break out of the loop early
because the array is already sorted.
6. Bubble Sort Algorithm (Descending Order):
o Follow the same steps as the ascending order sort, but compare adjacent elements and swap
them if the element at position j is less than the element at j+1.

16 | P a g e
6. Write a program to merge two one dimensional arrays into an another array.
Source Code:
public class MergeArrays {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int length1 = array1.length;
int length2 = array2.length;
int[] mergedArray = new int[length1 + length2];
// Copy elements from the first array to the merged array
for (int i = 0; i < length1; i++) {
mergedArray[i] = array1[i];
}
// Copy elements from the second array to the merged array
for (int i = 0; i < length2; i++) {
mergedArray[length1 + i] = array2[i];
}
// Print the merged array
System.out.print("Merged Array: ");
for (int i = 0; i < mergedArray.length; i++) {
System.out.print(mergedArray[i] + " ");
}
}
}
Output:

Variable Description:
1. array1: An integer array containing the first set of elements to be merged.
2. array2: An integer array containing the second set of elements to be merged.
3. length1: An integer that stores the length of array1.
4. length2: An integer that stores the length of array2.
5. mergedArray: An integer array that will store the elements of array1 and array2 after merging.
6. i: A loop control variable used to iterate over the elements of the arrays.
Algorithm:
1. Initialize Arrays:
o Define two integer arrays array1 and array2 with the elements to be merged.
2. Determine Lengths:
o Calculate the length of array1 and store it in length1.
o Calculate the length of array2 and store it in length2.
3. Create Merged Array:
o Initialize a new integer array mergedArray with a length equal to the sum of length1 and
length2.
4. Copy Elements from First Array:
o Use a loop to copy each element from array1 into the corresponding position in
mergedArray.

17 | P a g e
5. Copy Elements from Second Array:
o Use another loop to copy each element from array2 into the next positions in
mergedArray, starting from the index length1.
6. Print Merged Array:
o Use a loop to print each element of mergedArray.

18 | P a g e
7. Write a program to convert a Decimal no. into its Binary Equivalent
Source Code:
import java.io.*;
class Dec2Bin
{int n,i;
int a[] = new int[100];
static BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
public Dec2Bin(int nn) //parameterized contructor
{n=nn;
}
public void dectobin(int no) //function converting decimalto binary number

{int c = 0;
int temp = no;
while(temp != 0)
{a[c++] = temp % 2;
temp = temp / 2;
}
System.out.println("Binary eq. of "+no+" = ");
for( i = c-1 ; i>=0 ; i--) //Displaying binary number
System.out.print( a[ i ] );
}
public static void main(String args[]) throws IOException
{Dec2Bin obj = new Dec2Bin(30);
System.out.println("enter integer no -");
int no = Integer.parseInt(br.readLine());
obj.dectobin(no);
}
}
Output:

Variable Description:
1. n: An integer that stores the number passed to the Dec2Bin constructor. It represents the decimal
number to be converted to binary.
2. i: A loop control variable used to iterate through the array.
3. a: An integer array of size 100 that stores the binary digits (bits) of the decimal number.
4. br: A static instance of BufferedReader used to read input from the console.
5. c: An integer used to count the number of binary digits generated during the conversion.
6. temp: A temporary variable used to store the decimal number during the conversion process.
Algorithm:
1. Class Initialization:
o Define the class Dec2Bin with the necessary instance variables and methods.

19 | P a g e
2. Constructor (Dec2Bin):
o Initialize the instance variable n with the value passed to the constructor.
3. Method (dectobin):
o Initialize a counter c to 0.
o Store the decimal number no in a temporary variable temp.
o Use a while loop to convert the decimal number to binary:
 Compute the remainder of temp when divided by 2 and store it in the array a at index
c.
 Increment the counter c.
 Divide temp by 2.
o Print the binary equivalent by iterating over the array a from the last stored index to 0.
4. Main Method:
o Create an instance of Dec2Bin with an initial value (e.g., 30).
o Prompt the user to enter an integer number.
o Read the input number using BufferedReader.
o Call the dectobin method with the input number to print its binary equivalent.

20 | P a g e
8.Write a Java program to reverse a string.
Source Code:
import java.util.Scanner;
public class StringReversal
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string to reverse: ");
String inputString = sc.nextLine();
String reversedString = "";
for (int i = inputString.length() - 1; i >= 0; i--)
{
reversedString += inputString.charAt(i);
}
System.out.println("Reversed string: " + reversedString);
}
}
Output:

Variable Description:
1. sc: An instance of the Scanner class used to read input from the console.
2. inputString: A String variable that stores the user input string to be reversed.
3. reversedString: A String variable that stores the reversed version of the inputString.
4. i: A loop control variable used to iterate through the characters of inputString in reverse order.
Algorithm:
1. Initialization and Input:
o Create an instance of the Scanner class to read input from the user.
o Prompt the user to enter a string and store the input in the variable inputString.
2. Reverse the String:
o Initialize an empty string reversedString to store the reversed string.
o Use a for loop to iterate over the characters of inputString from the last character to the
first:
 In each iteration, append the current character to reversedString.
3. Output the Result:
o Print the reversedString.

21 | P a g e
9. Write a program to accept a string. Convert the string to uppercase. Count and output the number of
double letter
sequences that exist in the string.
Sample Input: “SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE Sample Output: 4
Source Code:
import java.util.Scanner;
public class DoubleLetterSequenceCount
{
// Function to count the number of double letter sequencesin a string
public static int countDoubleLetterSequences(String input)
{
input = input.toUpperCase();
int count = 0;
for (int i = 0; i < input.length() - 1; i++)
{
if (input.charAt(i) == input.charAt(i + 1))
{
count++;
}
}
return count;
}
// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
int result = countDoubleLetterSequences(inputString);
System.out.println("Number of double letter sequencesinthe string: " + result);
}
}
Output:

Variable Description:
1. input: A String variable that stores the user input string to be analyzed for double letter
sequences.
2. count: An int variable that keeps track of the number of double letter sequences found in the
input string.
3. i: A loop control variable used to iterate through the characters of input.
4. scanner: An instance of the Scanner class used to read input from the console.
5. inputString: A String variable that stores the string entered by the user.

22 | P a g e
6. result: An int variable that stores the result of the countDoubleLetterSequences method,
which is the number of double letter sequences in inputString.
Algorithm:
1. Initialize Scanner and Read Input:
o Create an instance of the Scanner class to read input from the user.
o Prompt the user to enter a string and store the input in the variable inputString.
2. Define the countDoubleLetterSequences Method:
o Convert the input string to uppercase to make the comparison case-insensitive.
o Initialize a counter count to 0.
o Use a for loop to iterate over the string from the first character to the second last character:
 If the current character is equal to the next character, increment the count.
o Return the count.
3. Call the Method and Display Result:
o Call the countDoubleLetterSequences method with inputString as the argument.
o Store the result in the variable result.
o Print the number of double letter sequences found.

23 | P a g e
10. write a Java program to find the all words starting and ending with same letter from a sentence.
Source Code:
import java.util.*;
public class proj_14
{
void check()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter a sentece");
String st=sc.nextLine(),s="";
st=st+" ";
char ch;
for(int i=0;i<st.length();i++)
{
ch=st.charAt(i);
if(ch==' ')
{
if(s.charAt(0)==st.charAt(i-1))
System.out.println(s);
s="";
}
else
s=s+ch;
}
}
public static void main(String[] args)
{
proj_14 ob=new proj_14();
ob.check();
}
}
Output:

Variable Description:
1. sc: A Scanner object used to read input from the user.
2. st: A String variable that stores the sentence entered by the user.
3. s: A String variable used to build each word from the sentence.
4. ch: A char variable used to iterate through each character in the sentence.
Algorithm:
1. Initialize Scanner and Input:
o Create a Scanner object sc to read input from the console.
o Prompt the user to enter a sentence and store it in the st variable.

24 | P a g e
2. Processing the Sentence:
o Append a space at the end of st to ensure that the last word in the sentence is processed
correctly.
o Initialize an empty string s to store each word from the sentence.
3. Iterate through the Sentence:
o Use a for loop to iterate through each character ch in the string st.
o If ch is a space (' '):
 Check if the first character of s (which is the last word extracted) is equal to the
previous character (st.charAt(i-1)). If true, print s.
 Reset s to an empty string "" for the next word.
o If ch is not a space, append it to s to build the current word.
4. Print Words with Matching Conditions:
o The program prints each word that starts with the same character as the preceding word.

25 | P a g e
11. Write a program to accept a word from the user. Print the converted word where the consonants are
upgraded by nearest vowel and vowels are upgraded to nearest consonant.
Source Code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = scanner.nextLine();
String upgradedWord = upgradeCharactersInWord(word);
System.out.println("Converted word: " + upgradedWord);
scanner.close();
}
public static String upgradeCharactersInWord(String word)
{
StringBuilder result = new StringBuilder();
for (char ch : word.toCharArray())
{
if (isVowel(ch))
{
result.append(getNearestConsonant(ch));
}
else
{
result.append(getNearestVowel(ch));
}
}
return result.toString();
}
public static boolean isVowel(char ch)
{
ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
public static char getNearestVowel(char ch)
{
ch = Character.toLowerCase(ch);
return isVowel(ch) ? ch : (char) (ch < 'o' ? 'a' : 'e');
}
public static char getNearestConsonant(char ch)
{
ch = Character.toLowerCase(ch);

26 | P a g e
return isVowel(ch) ? (char) (ch < 'e' ? 'd' : 'h') : ch;
}
}
Output:

Variable Description:
1. scanner: An instance of the Scanner class used to read input from the console.
2. word: A String variable that stores the word entered by the user.
3. upgradedWord: A String variable that stores the converted word after processing each character.
4. result: A StringBuilder object used to build the converted word.
5. ch: A char variable used to iterate through each character in the word.
Algorithm:
1. Initialize Scanner and Read Input:
o Create an instance of the Scanner class to read input from the user.
o Prompt the user to enter a word and store it in the variable word.
2. Define the upgradeCharactersInWord Method:
o Initialize a StringBuilder object result to build the converted word.
o Iterate through each character ch in the word:
 If ch is a vowel, append the nearest consonant to result using the
getNearestConsonant method.
 If ch is a consonant, append the nearest vowel to result using the
getNearestVowel method.
o Return the converted word as a string.
3. Define the isVowel Method:
o Convert the character ch to lowercase.
o Return true if ch is a vowel ('a', 'e', 'i', 'o', 'u'); otherwise, return false.
4. Define the getNearestVowel Method:
o Convert the character ch to lowercase.
o If ch is a vowel, return ch.
o Otherwise, determine the nearest vowel:
 For simplicity, this implementation returns 'a' for characters before 'o' and 'e' for
characters from 'o' onwards.
o Return the nearest vowel.
5. Define the getNearestConsonant Method:
o Convert the character ch to lowercase.
o If ch is a vowel, return the nearest consonant:
 For simplicity, this implementation returns 'd' for vowels before 'e' and 'h' for vowels
from 'e' onwards.
o If ch is a consonant, return ch.
6. Output the Result:
o Print the converted word.

27 | P a g e
12.Write a Java program to find the area of circle, rectangle,square using function overloading.

Source Code:
1. class OverloadDemo
2. {
3. void area(float x)
4. {
5. System.out.println("the area of the square is
"+Math.pow(x, 2)+" sq units");
6. }
7. void area(float x, float y)
8. {
9. System.out.println("the area of the rectangle is "+x*y+"
sq units");
10. }
11. void area(double x)
12. {
13. double z = 3.14 * x * x;
14. System.out.println("the area of the circle is "+z+"
sq units");
15. }
16. }
17. class Overload
18. {
19. public static void main(String args[])
20. {
21. OverloadDemo ob = new OverloadDemo();
22. ob.area(5);
23. ob.area(11,12);
24. ob.area(2.5);
25. }
26. }
Output:

Variable Description:
1. x: A float or double variable representing the side length of a square, the radius of a circle, or one
dimension of a rectangle.
2. y: A float variable representing the second dimension of a rectangle.
3. z: A double variable used to store the computed area of a circle.
4. ob: An instance of the OverloadDemo class used to call the overloaded methods.
Algorithm:
1. Class Definition (OverloadDemo):

28 | P a g e
o Define a class OverloadDemo that contains three overloaded methods to calculate areas.
2. Square Area Method:
o Define a method void area(float x):
 Compute the area of a square using x * x or Math.pow(x, 2).
 Print the result.
3. Rectangle Area Method:
o Define a method void area(float x, float y):
 Compute the area of a rectangle using x * y.
 Print the result.
4. Circle Area Method:
o Define a method void area(double x):
 Compute the area of a circle using 3.14 * x * x.
 Print the result.
5. Main Class (Overload):
o Define a class Overload with the main method.
o Create an instance of OverloadDemo named ob.
o Call the area methods with different arguments to demonstrate method overloading.

29 | P a g e
13.write a Java program to find the second largest number in an array of 20 elements.
Source Code:
import java.util.*;
class proj_13 {
// Method to find the second largest element in the array
void secondLargest(int arr[]) {
int n = arr.length;
int max1 = arr[0];
int max2 = arr[0];

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


if (arr[i] > max1) {
max2 = max1;
max1 = arr[i];
} else if (arr[i] > max2 && arr[i] < max1) {
max2 = arr[i];
}
}
System.out.println("Second largest = " + max2);
}
// Method to print the elements of the array
void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Main method to test the above methods
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// Declare array size
System.out.println("Enter the size of the array");
int n = sc.nextInt();
// Declare and initialize array
int arr[] = new int[n];
System.out.println("Enter the values of the array");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Create an instance of proj_13
proj_13 ob = new proj_13();
// Print the values of the array
System.out.println("Values of the array:");
ob.printArray(arr);
// Find and print the second largest element in the array

30 | P a g e
ob.secondLargest(arr);
}
}
Output:

Variable Description:
 arr[]: An integer array whose elements are provided by the user.
 n: An integer representing the length of the array.
 max1: An integer representing the largest element in the array.
 max2: An integer representing the second largest element in the array.
 i: A loop control variable used for iterating through the array.
 sc: A Scanner object used to read input from the user.
Algorithm
1. Class Definition (proj_13):
o Define a class proj_13 containing methods to find the second largest element in an array and
to print the array.
2. Method to Find Second Largest (secondLargest):
o Input: An integer array arr.
o Process:
 Initialize max1 and max2 to the first element of the array.
 Iterate through the array from the first to the last element.
 If the current element is greater than max1, update max2 to max1 and then update
max1 to the current element.
 Otherwise, if the current element is greater than max2 but less than max1, update
max2 to the current element.
o Output: Print the value of max2.
3. Method to Print Array (printArray):
o Input: An integer array arr.
o Process: Iterate through the array and print each element followed by a space.
o Output: Print all elements of the array in a single line.
4. Main Method:

31 | P a g e
o Input:
 Create a Scanner object to read input from the user.
 Read the size of the array (n).
 Declare an integer array arr of size n.
 Read n elements into the array.
o Process:
 Create an instance of proj_13.
 Call the printArray method to print the array.
 Call the secondLargest method to find and print the second largest element in the
array.

32 | P a g e
14.write a Java program to find the all palindrome words from a sentence.

Source Code:
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
System.out.println("Enter a String:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
findPalindrom(input);
sc.close();
}

public static void findPalindrom(String str) {


str = str + " ";
String word = "";
int len = str.length();

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


char ch = str.charAt(i);
if (ch == ' ') {
int wordLen = word.length();
boolean isPalin = true;
for (int j = 0; j < wordLen / 2; j++) {
if (word.charAt(j) != word.charAt(wordLen - 1 - j)) {
isPalin = false;
break;
}
}
if (isPalin && wordLen > 0)
System.out.println(word);
word = "";
} else {
word += ch;
}
}
}
}

33 | P a g e
Output:

Variable Description:
1. sc: A Scanner object used to read input from the user.
2. input: A String that stores the user input.
3. str: A String that represents the input string with an added space at the end to facilitate word
extraction.
4. word: A String that accumulates characters to form individual words from the input string.
5. len: An integer representing the length of the str string.
6. ch: A char that stores the current character being processed from the string str.
7. wordLen: An integer representing the length of the current word being processed.
8. isPalin: A boolean flag used to determine if the current word is a palindrome.
Algorithm:
 Read Input:
 Prompt the user to enter a string.
 Use the Scanner class to read the input string.
 Add Trailing Space:
 Append a space to the end of the input string to ensure the last word is processed correctly.
 Initialize Variables:
 Initialize word as an empty string to accumulate characters forming a word.
 Calculate the length of the modified string (str).
 Extract and Check Words:
 Iterate over each character in the string str.
 If the character is a space, the current word is complete.
o Calculate the length of the word.
o Check if the word is a palindrome by comparing characters from the start and end moving
towards the center.
o If the word is a palindrome, print it.
o Reset word to an empty string to start accumulating the next word.
 If the character is not a space, append it to word.
 Print Palindromic Words:
 If any word is identified as a palindrome during the iteration, it is printed to the console.

34 | P a g e
15. WAP in java to Accept a positive number N and check whether it is a circular prime or not. The new
numbers formed after the shifting of the digits should also be displayed.Example:
131
311
113
all are prime number hence, 131 is a circular prime.

Source Code:
import java.util.Scanner;
public class Main3
{
public static boolean isPrime(int num) {
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
return c == 2;
}
public static int getDigitCount(int num) {
int c = 0;
while (num != 0) {
c++;
num /= 10;
}
return c;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("ENTER INTEGER TO CHECK (N): ");
int n = in.nextInt();
if (n <= 0) {
System.out.println("INVALID INPUT");
return;
}
boolean isCircularPrime = true;
if (isPrime(n)) {
System.out.println(n);
int digitCount = getDigitCount(n);
int divisor = (int)(Math.pow(10, digitCount - 1));
int n2 = n;
for (int i = 1; i < digitCount; i++) {
int t1 = n2 / divisor;
int t2 = n2 % divisor;

35 | P a g e
n2 = t2 * 10 + t1;
System.out.println(n2);
if (!isPrime(n2)) {
isCircularPrime = false;
break;
}
}
}
else {
isCircularPrime = false;
}
if (isCircularPrime) {
System.out.println(n + " IS A CIRCULAR PRIME.");
}
else {
System.out.println(n + " IS NOT A CIRCULAR PRIME.");
}
}
}
Output:

Variable Description
1. num: An integer being checked for primality or being rotated in the program.
2. c: An integer counter used to count the number of divisors of num in the isPrime method and to
count the digits in the getDigitCount method.
3. in: A Scanner object used to read input from the user.
4. n: An integer entered by the user, which is checked if it is a circular prime.
5. isCircularPrime: A boolean flag used to determine if n is a circular prime.
6. digitCount: An integer representing the number of digits in n.
7. divisor: An integer used to help with rotating the digits of n.
8. n2: An integer representing the rotated version of n during the check for circular primality.
9. t1: An integer representing the most significant digit of n2.
10. t2: An integer representing the rest of the digits of n2 after removing the most significant digit.
Algorithm
1. Input Handling:
o Prompt the user to enter an integer (n).
o Check if n is less than or equal to 0, and if so, print "INVALID INPUT" and return.
2. Prime Check:
o Define a method isPrime that checks if a given number is prime by counting its divisors.
o If n is not prime, set isCircularPrime to false.
3. Circular Prime Check:
o If n is prime, continue to check for circular primality.
o Calculate the number of digits in n using the getDigitCount method.
o Calculate the divisor used to rotate the digits.

36 | P a g e
o Rotate the digits of n and check if each rotation is prime.
o Print each rotated number during the check.
o If any rotation is not prime, set isCircularPrime to false and break the loop.
4. Result Output:
o After checking all rotations, print whether n is a circular prime or not.

37 | P a g e
16. Given two positive integers p and q, where p<q.Write a program to define how many kaprekar
numbers are there in the range.
Source Code:
import java.util.*;
public class Main
{
static boolean kaprekar(int n)
{
if (n == 1)
return true;
int sq_n = n * n;
int count_digits = 0;
while (sq_n != 0)
{
count_digits++;
sq_n /= 10;
}
sq_n = n*n;
for (int r_digits=1; r_digits<count_digits; r_digits++)
{
int eq_parts = (int) Math.pow(10, r_digits);
if (eq_parts == n)
continue;
int sum = sq_n/eq_parts + sq_n % eq_parts;
if (sum == n)
return true;
}
return false;
}
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int p,q;
p=sc.nextInt();
q=sc.nextInt();
for (int i=p; i<q; i++)
if (kaprekar(i))
System.out.print(i + " ");
}
}
Output
Given the input values for p and q as the range, the program will output all Kaprekar numbers within that
range. For example, if p = 1 and q = 100, the output will be:
1 9 45 55 99
Variable Description
 int n: The number being checked if it is a Kaprekar number.

38 | P a g e
 int sq_n: The square of n.
 int count_digits: The number of digits in sq_n.
 int r_digits: The number of rightmost digits to split sq_n into two parts.
 int eq_parts: The power of 10 used to split sq_n.
 int sum: The sum of the split parts of sq_n.
 int p: The lower bound of the range.
 int q: The upper bound of the range.
Algorithm
1. Initialization:
o Read the range p and q from the user.
o Loop through each number from p to q.
2. Check Kaprekar Number:
o Define a function kaprekar(int n) to check if n is a Kaprekar number.
o If n is 1, return true.
o Calculate the square of n and store it in sq_n.
o Count the number of digits in sq_n and store it in count_digits.
o Loop through possible rightmost digits to split sq_n into two parts:
 Calculate the power of 10 to split sq_n.
 Split sq_n into two parts and calculate their sum.
 If the sum equals n, return true.
o If no such split is found, return false.
3. Print Kaprekar Numbers:
o Loop through each number from p to q.
o If the number is a Kaprekar number (using the kaprekar function), print it.

39 | P a g e
17. Given two positive integers n and m where n<m. Write a program to print all the twin primes from the
range.

Source Code:
import java.io.*;
import java.util.*;
class Main
{
static boolean checkPrimeNumber(int number)
{
int i;
int m = 0;
int flag = 0;
m = number/2;
if(number == 0 || number == 1){
return false;
}
else
{
for(i = 2; i<= m ;i++){
if(number%i == 0){
flag=1;
return false;
}
}
if(flag == 0)
{
return true;
}
}
return false;
}
static boolean checkTwinPrimeNumber(int n, int m)
{
if(checkPrimeNumber(n) &&checkPrimeNumber(m) &&Math.abs(n - m) == 2)
return true;
else
return false;
}
public static void main(String[] args)
{
int n, m;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
n = sc.nextInt();
System.out.println("Enter second number");

40 | P a g e
m = sc.nextInt();
if (checkTwinPrimeNumber(n, m))
System.out.println("("+n +", "+m+ ") is a pair of twin primes");
else
System.out.println("("+n +", "+m+ ") is not a pair of twin primes");
}
}

Output:
Enter first number
11
Enter second number
13
(11, 13) is a pair of twin primes

If the input numbers are not twin primes:


Enter first number
11
Enter second number
15
(11, 15) is not a pair of twin primes

Variable Description:
 int number: The number to be checked for primality.
 int i: Loop variable used in the prime-checking function.
 int m: Half of number, used as a limit for checking factors.
 int flag: A flag to indicate if a number is not prime.
 int n: The first input number to be checked for twin primality.
 int m: The second input number to be checked for twin primality.
 Scanner sc: Scanner object for reading user input.
Algorithm:
1. Check Prime Number:
o Define a method checkPrimeNumber(int number) to check if a number is prime.
o If the number is 0 or 1, return false.
o Calculate m as half of number.
o Loop from 2 to m to check if number has any divisors.
o If any divisor is found, set flag to 1 and return false.
o If no divisors are found, return true.
2. Check Twin Prime Number:
o Define a method checkTwinPrimeNumber(int n, int m) to check if two numbers are twin
primes.
o Use the checkPrimeNumber method to check if both numbers are prime.
o If both numbers are prime and the absolute difference between them is 2, return true.
o Otherwise, return false.
3. Main Method:

41 | P a g e
o Create a Scanner object to read user input.
o Prompt the user to enter the first number and store it in n.
o Prompt the user to enter the second number and store it in m.
o Use the checkTwinPrimeNumber method to check if the numbers are twin primes.
o Print the result accordingly.

42 | P a g e
18. The function M(N) for a natural number N is defined as M(N) = 1 [ if N =1 ], M(N) =0 [ if any prime
factor of N is contained in N more than once], M(N) =-1 if N is the product of distinct prime factors. Write a
program to input a positive natural number and display the value of M(N).
Source Code:
import java.util.Scanner;
public class Main
{
static boolean isPrime(int num)
{
if (num <= 1)
{
return false;
}
for (int i = 2; i * i<= num; i++)
{
if (num % i == 0) {
return false;
}
}
return true;
}
static int calculateM(int N)
{
if (N == 1) {
return 1;
}
for (int i = 2; i<= N; i++)
{
if (N % i == 0 &&isPrime(i))
{
int count = 0;
while (N % i == 0)
{
N /= i;
count++;
}
if (count > 1)
{
return 0;
}
}
}
return -1;
}
public static void main(String[] args)
{

43 | P a g e
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive natural number: ");
int N = sc.nextInt();
int result = calculateM(N);
System.out.println("M(" + N + ") = " + result);
sc.close();
}
}
Output:
Enter a positive natural number: 12
M(12) = 0
Enter a positive natural number: 7
M(7) = -1
Enter a positive natural number: 16
M(16) = 0
Enter a positive natural number: 30
M(30) = -1
Variable Description
 int num: The number to be checked for primality in the isPrime method.
 int i: Loop variable used in both isPrime and calculateM methods.
 int N: The input positive natural number for which M(N) is to be calculated.
 int result: The result of the calculation of M(N).
 Scanner sc: Scanner object for reading user input.
 int count: Counter to count the number of times a prime factor divides N.
Algorithm
1. Check Prime Number:
o Define a method isPrime(int num) to check if a number is prime.
o If the number is less than or equal to 1, return false.
o Loop from 2 to the square root of num to check if num has any divisors.
o If any divisor is found, return false.
o If no divisors are found, return true.
2. Calculate M(N):
o Define a method calculateM(int N) to calculate the value of M(N).
o If N is 1, return 1.
o Loop from 2 to N to find prime factors of N.
o If i is a prime factor and is prime, count how many times it divides N.
o If any prime factor divides N more than once, return 0.
o If no prime factor divides N more than once, return -1.
3. Main Method:
o Create a Scanner object to read user input.
o Prompt the user to enter a positive natural number (N).
o Use the calculateM method to calculate the value of M(N).
o Print the result.
o Close the scanner.

44 | P a g e
19.Write a program to accept 10 integers from the users, update 3 integers given by the user in a
particular position and then remove the 5th and 6th element from the array and print the final array.

Source Code:

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int[] arr = new int[10];
System.out.println("Enter 10 integers:");
for (int i = 0; i< 10; i++)
{
arr[i] = scanner.nextInt();
}
System.out.print("Enter three integers to insert: ");
int insert1 = scanner.nextInt();
int insert2 = scanner.nextInt();
int insert3 = scanner.nextInt();
System.out.print("Enter the position (0 to 9) to insert the integers: ");
int position = scanner.nextInt();
for (int i = arr.length - 1; i>= position; i--)
{
arr[i] = arr[i - 1];
}
arr[position] = insert1;
arr[position + 1] = insert2;
arr[position + 2] = insert3;
System.out.println("Final array:");
for (int i = 0; i<arr.length; i++)
{
System.out.print(arr[i] + " ");
}
for (int i = 4; i<arr.length - 2; i++)
{
arr[i] = arr[i + 2];
}
System.out.println("Final array:");
for (int i = 0; i<arr.length - 2; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
}

45 | P a g e
}
Output:
Enter 10 integers:
1 2 3 4 5 6 7 8 9 10
Enter three integers to insert: 11 12 13
Enter the position (0 to 9) to insert the integers: 3
Final array:
1 2 3 11 12 13 4 5 6 7
Final array:
1 2 3 11 5 6 7
Variable Description
 Scanner scanner: An instance of the Scanner class to read input from the user.
 int[] arr: An array of 10 integers to store the initial set of numbers.
 int insert1, insert2, insert3: Three integers to be inserted into the array.
 int position: The position at which the three integers will be inserted.
 int i: Loop variable used in various loops to iterate over the array.
Algorithm
1. Initialize Array:
o Create an array arr of size 10 to hold integers.
o Use a Scanner object to read 10 integers from the user and store them in arr.
2. Insert New Integers:
o Read three integers insert1, insert2, and insert3 from the user.
o Read the position at which these integers will be inserted.
o Shift elements in the array to the right starting from the end of the array down to the
insertion position to make space for the new integers.
o Insert insert1 at position, insert2 at position + 1, and insert3 at position + 2.
3. Print Updated Array:
o Print the modified array with the new integers inserted.
4. Remove Extra Elements:
o Shift elements to the left starting from position + 3 to remove the extra elements at the end
of the array.
o Print the final modified array.

46 | P a g e
20. Write a program to form a square Matrix of characters and display the row and column having the max
valued characters.
Source Code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the square matrix: ");
int size = scanner.nextInt();
int maxColumnValue = 0,maxColumn=0;
char[][] matrix = new char[size][size];
System.out.println("Enter the characters for the matrix:");
for (int i = 0; i< size; i++)
{
for (int j = 0; j < size; j++)
{
matrix[i][j] = scanner.next().charAt(0);
}
}
System.out.println("The square matrix is:");
for (int i = 0; i< size; i++)
{
for (int j = 0; j < size; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
int maxRow = 0;
int maxRowValue = 0;
for (int i = 0; i< size; i++)
{
int rowValue = 0;
for (int j = 0; j < size; j++)
{
if ( matrix[i][j]>maxRowValue)
{
maxRowValue = matrix[i][j];
maxRow = i;
}
}
}
System.out.println("Row with max valued characters: " + (maxRow+1)+" value= "+(char)maxRowValue);
for (int j = 0; j < size; j++)

47 | P a g e
{
for (int i = 0; i< size; i++)
{
if ( matrix[i][j]>maxColumnValue)
{
maxColumnValue = matrix[i][j];
maxColumn = j;
}
}
}
System.out.println("Column with max valued characters: " + (maxColumn+1)+" value= "+
(char)maxColumnValue);
scanner.close();
}
}
Output:
Enter the size of the square matrix: 3
Enter the characters for the matrix:
abc
def
ghi
The square matrix is:
abc
def
ghi
Row with max valued characters: 3 value= i
Column with max valued characters: 3 value= i
Variable Description
 Scanner scanner: An instance of the Scanner class to read input from the user.
 int size: The size of the square matrix.
 char[][] matrix: A 2D array to store the characters of the matrix.
 int maxRow: The index of the row with the maximum valued character.
 int maxRowValue: The maximum character value in the row.
 int maxColumn: The index of the column with the maximum valued character.
 int maxColumnValue: The maximum character value in the column.
 int rowValue: The value of the characters in a row.
 int i, j: Loop variables used to iterate over the matrix.
Algorithm
1. Initialize Variables:
o Initialize a Scanner object to read user input.
o Declare variables size, matrix, maxRow, maxRowValue, maxColumn, and maxColumnValue.
2. Read Matrix Size and Elements:
o Read the size of the square matrix.
o Initialize the matrix with the specified size.
o Read the characters for the matrix from the user and store them in the matrix.
3. Print the Matrix:

48 | P a g e
o Print the entered square matrix.
4. Find the Row with Maximum Valued Character:
o Initialize maxRowValue to 0.
o Iterate through each row of the matrix.
o For each row, iterate through each character and compare it with maxRowValue.
o If the current character is greater than maxRowValue, update maxRowValue and maxRow.
5. Print the Row with Maximum Valued Character:
o Print the index of the row with the maximum valued character and the character itself.
6. Find the Column with Maximum Valued Character:
o Initialize maxColumnValue to 0.
o Iterate through each column of the matrix.
o For each column, iterate through each character and compare it with maxColumnValue.
o If the current character is greater than maxColumnValue, update maxColumnValue and
maxColumn.
7. Print the Column with Maximum Valued Character:
o Print the index of the column with the maximum valued character and the character itself.
8. Close Scanner:
o Close the Scanner object to avoid resource leaks.

49 | P a g e
21.Write a program to accept a string from user and display the words that are having repeating
characters.
Source Code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String[] words = inputString.split("\\s+");
System.out.println("Words with repeating characters:");
for (String word : words)
{
if (hasRepeatingCharacters(word))
{
System.out.println(word);
}
}
scanner.close();
}
public static boolean hasRepeatingCharacters(String word)
{
for (int i = 0; i<word.length() - 1; i++)
{
char currentChar = word.charAt(i);
for (int j = i + 1; j <word.length(); j++)
{
if (currentChar == word.charAt(j))
{
return true;
}
}
}
return false;
}
}
Output:
Enter a string: banana apple kiwi orange
Words with repeating characters:
banana
apple
Variable Description
 Scanner scanner: An instance of the Scanner class to read input from the user.
 String inputString: The input string entered by the user.

50 | P a g e
 String[] words: An array of words obtained by splitting the input string.
 String word: A variable used to iterate through each word in the array.
 char currentChar: A character variable used to compare characters in a word.
Algorithm
1. Initialize Variables:
o Create a Scanner object to read input from the user.
o Declare a String variable inputString to store the input string.
o Declare a String[] array words to store the words obtained from the input string.
2. Read Input String:
o Prompt the user to enter a string.
o Read the input string using the Scanner object.
3. Split Input String into Words:
o Split the input string into words using the split("\\s+") method, which splits the string by one
or more whitespace characters.
4. Find and Print Words with Repeating Characters:
o Print a message indicating the start of words with repeating characters.
o Iterate through each word in the words array.
o For each word, call the hasRepeatingCharacters method to check if the word contains
repeating characters.
o If the word contains repeating characters, print the word.
5. Close Scanner:
o Close the Scanner object to avoid resource leaks.
6. Check for Repeating Characters:
o Define a static method hasRepeatingCharacters that takes a String word as input and returns
a boolean value.
o Iterate through each character in the word using a nested loop.
o For each character, compare it with every subsequent character in the word.
o If a repeating character is found, return true.
o If no repeating characters are found after checking all characters, return false.

51 | P a g e
22. Write a program to declare a matrix A[][] of order (M x N) where 'M' is the number of rows and 'N' is
the number of columns such that the value of 'M' must be greater than 0 and less than 10 and the valueof
'N' must be greater than 2 and less than 6. Allow the user to input digits (0 - 7) only at each location, such
that each row represents an octal number
Example:
2 3 1 (decimal equivalent of 1st row = 153 i.e. 2x82 +
3x81 + 1x80)
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4x82 +
0x81 + 5x80)
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1x82 +
5x81 + 6x80)
Source Code:
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of rows (M): ");
int m = in.nextInt();
System.out.print("Enter the number of columns (N): ");
int n = in.nextInt();
if (m <= 0 || m >= 10 || n <= 2 || n >= 6) {
System.out.println("OUT OF RANGE");
return;
}
int a[][] = new int[m][n];
for (int i = 0; i < m; i++) {
System.out.println("ENTER ELEMENTS FOR ROW " + (i + 1) + ": ");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
if (a[i][j] < 0 || a[i][j] > 7) {
System.out.println("INVALID INPUT");
return;
}
}
}
System.out.println("FILLED MATRIX\tDECIMAL EQUIVALENT");
for (int i = 0; i < m; i++) {
int decNum = 0;
for (int j = 0; j < n; j++) {
decNum += a[i][j] * Math.pow(8, n - j - 1 );
System.out.print(a[i][j] + " ");
}
System.out.print("\t\t" + decNum);
System.out.println();
}

52 | P a g e
}
}
Output:
Enter the number of rows (M): 3
Enter the number of columns (N): 3
ENTER ELEMENTS FOR ROW 1:
123
ENTER ELEMENTS FOR ROW 2:
456
ENTER ELEMENTS FOR ROW 3:
701
FILLED MATRIX DECIMAL EQUIVALENT
123 83
456 310
701 449
Variable Description
 Scanner in: An instance of the Scanner class to read input from the user.
 int m: Number of rows in the matrix.
 int n: Number of columns in the matrix.
 int[][] a: A 2D array to store the elements of the matrix.
 int decNum: A variable to store the decimal equivalent of each row in the matrix.
Algorithm
1. Initialize Variables:
o Create a Scanner object to read input from the user.
o Declare integers m and n for the number of rows and columns of the matrix, respectively.
o Declare a 2D array a to store the matrix elements.
2. Read Matrix Dimensions:
o Prompt the user to enter the number of rows (m) and columns (n) of the matrix.
o Read the values of m and n using the Scanner object.
3. Validate Input Range:
o Check if m and n are within the specified range:
 m should be greater than 0 and less than 10.
 n should be greater than 2 and less than 6.
o If the values are out of range, print "OUT OF RANGE" and terminate the program.
4. Fill Matrix with Elements:
o Use nested loops to read elements into the matrix a.
o For each row i, prompt the user to enter the elements of the row.
o Read the elements of the row and store them in the matrix.
o Validate each element to ensure it is between 0 and 7 (inclusive).
o If an element is out of range, print "INVALID INPUT" and terminate the program.
5. Calculate Decimal Equivalent:
o Print the header "FILLED MATRIX\tDECIMAL EQUIVALENT".
o Use nested loops to iterate through the matrix and calculate the decimal equivalent of each
row.
o For each row, initialize decNum to 0.

53 | P a g e
o Calculate the decimal equivalent by iterating through the columns and summing the products
of each element and the corresponding power of 8.
o Print the elements of the row and the calculated decimal equivalent.
6. Print Matrix and Decimal Equivalents:
o Print the elements of each row followed by its decimal equivalent

54 | P a g e
23.Write a program to declare a matrix a[][] of order (m × n) where 'm' is the number of rows and 'n' is the
number of columns such that the values of both 'm' and 'n' must be greater than 2 and less than 10. Allow
the user to input integers into this matrix. Perform the following tasks on the matrix:
Display the original matrix.
Sort each row of the matrix in ascending order using any standard sorting technique.
Display the changed matrix after sorting each row.
Source Code:
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF M: ");
int m = in.nextInt();
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
if (m <= 2
|| m >= 10
|| n <= 2
|| n >= 10) {
System.out.println("MATRIX SIZE OUT OF RANGE.");
return;
}
int a[][] = new int[m][n];
System.out.println("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++) {
System.out.println("ENTER ELEMENTS OF ROW " + (i+1) + ":");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
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]) {
int t = a[i][k];
a[i][k] = a[i][k+1];
a[i][k+1] = t;
}

55 | P a g e
}
}
}
System.out.println("MATRIX AFTER SORTING ROWS");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
Output:
ENTER THE VALUE OF M: 3
ENTER THE VALUE OF N: 4
ENTER ELEMENTS OF MATRIX:
ENTER ELEMENTS OF ROW 1:
3142
ENTER ELEMENTS OF ROW 2:
5297
ENTER ELEMENTS OF ROW 3:
8634
ORIGINAL MATRIX
3142
5297
8634
MATRIX AFTER SORTING ROWS
1234
2579
3468
Variable Description
 Scanner in: An instance of the Scanner class to read input from the user.
 int m: Number of rows in the matrix.
 int n: Number of columns in the matrix.
 int[][] a: A 2D array to store the elements of the matrix.
 int t: A temporary variable used for swapping elements during the sorting process.
Algorithm
1. Initialize Variables:
o Create a Scanner object to read input from the user.
o Declare integers m and n for the number of rows and columns of the matrix, respectively.
o Declare a 2D array a to store the matrix elements.
2. Read Matrix Dimensions:
o Prompt the user to enter the number of rows (m) and columns (n) of the matrix.
o Read the values of m and n using the Scanner object.
3. Validate Input Range:
o Check if m and n are within the specified range:

56 | P a g e
 m should be greater than 2 and less than 10.
 n should be greater than 2 and less than 10.
o If the values are out of range, print "MATRIX SIZE OUT OF RANGE." and terminate the
program.
4. Fill Matrix with Elements:
o Use nested loops to read elements into the matrix a.
o For each row i, prompt the user to enter the elements of the row.
o Read the elements of the row and store them in the matrix.
5. Print Original Matrix:
o Use nested loops to print the original matrix a.
6. Sort Each Row of the Matrix:
o Use nested loops to perform Bubble Sort on each row of the matrix a.
o For each row i, iterate through the columns and compare adjacent elements.
o Swap the elements if they are in the wrong order.
7. Print Sorted Matrix:
o Use nested loops to print the sorted matrix a.

57 | P a g e
24. A company manufactures packing cartons in four sizes, i.e. cartons to accommodate 6 boxes, 12 boxes,
24 boxes and 48 boxes. Design a program to accept the number of boxes to be packed (N) by the user
(maximum up to 1000 boxes) and display the break-up of the cartons used in descending order of capacity
(i.e. preference should be given to the highest capacity available, and if boxes left are less than 6, an extra
carton of capacity 6 should be used.)
Source Code:
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of boxes (N): ");
int n = in.nextInt();
if (n < 1 || n > 1000) {
System.out.println("INVALID INPUT");
return;
}
int cartonSizes[] = {48, 24, 12, 6};
int total = 0;
int t = n;
for (int i = 0; i < cartonSizes.length; i++) {
int cartonCount = t / cartonSizes[i];
t = t % cartonSizes[i];
total += cartonCount;
if (cartonCount != 0) {
System.out.println(cartonSizes[i] + " * " + cartonCount +
" = " + (cartonSizes[i] * cartonCount));
}
}
if (t != 0) {
System.out.println("Remaining boxes = " + t
+ " * 1 = " + t);
total++;
}
else {
System.out.println("Remaining boxes = 0");
}
System.out.println("Total number of boxes = " + n);
System.out.println("Total number of cartons = " + total);
}
}
Output:
Enter number of boxes (N): 125
48 * 2 = 96
24 * 1 = 24
Remaining boxes = 5 * 1 = 5

58 | P a g e
Total number of boxes = 125
Total number of cartons = 4
Variable Description
 Scanner in: An instance of the Scanner class to read input from the user.
 int n: Number of boxes to be packed.
 int[] cartonSizes: Array containing different sizes of cartons available (48, 24, 12, 6).
 int total: Total number of cartons required to pack the boxes.
 int t: Temporary variable to store the remaining number of boxes after each iteration.
 int cartonCount: Number of cartons of a particular size used in the current iteration.
Algorithm
1. Initialize Variables:
o Create a Scanner object to read input from the user.
o Declare integer n for the number of boxes to be packed.
o Declare an array cartonSizes containing the sizes of available cartons.
o Initialize total to 0 to keep track of the total number of cartons used.
o Copy the value of n to t to use for calculations.
2. Read Number of Boxes:
o Prompt the user to enter the number of boxes (n).
o Read the value of n using the Scanner object.
3. Validate Input:
o Check if n is within the range [1, 1000].
o If n is out of range, print "INVALID INPUT" and terminate the program.
4. Calculate Cartons Needed:
o Use a loop to iterate over the cartonSizes array.
o For each carton size, calculate the number of cartons needed (cartonCount) by dividing t by
the current carton size.
o Update t to the remaining number of boxes after using the current carton size (t %
cartonSizes[i]).
o Add cartonCount to total.
o If cartonCount is not zero, print the carton size, count, and the total boxes packed with that
size.
5. Handle Remaining Boxes:
o If there are any remaining boxes (t is not zero), print the remaining boxes and increment total
by 1.
o If there are no remaining boxes, print "Remaining boxes = 0".
6. Print Total:
o Print the total number of boxes and the total number of cartons used.

59 | P a g e
25. Write a program to accept a sentence which may be terminated by either '.', '?' or '!' only. The words
may be separated by more than one blank space and are in UPPER CASE.
Perform the following tasks:
1. Find the number of words beginning and ending with a vowel.
2. Place the words which begin and end with a vowel at the beginning, followed by the remaining words
as they occur in the sentence.
Source Code:
import java.util.*;
public class Main
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("ENTER THE SENTENCE:");
String ipStr = in.nextLine().trim().toUpperCase();
int len = ipStr.length();
char lastChar = ipStr.charAt(len - 1);
if (lastChar != '.'
&& lastChar != '?'
&& lastChar != '!') {
System.out.println("INVALID INPUT");
return;
}
String str = ipStr.substring(0, len - 1);
StringTokenizer st = new StringTokenizer(str);
StringBuffer sbVowel = new StringBuffer();
StringBuffer sb = new StringBuffer();
int c = 0;
while (st.hasMoreTokens()) {
String word = st.nextToken();
int wordLen = word.length();
if (isVowel(word.charAt(0))
&& isVowel(word.charAt(wordLen - 1))) {
c++;
sbVowel.append(word);
sbVowel.append(" ");
}
else {
sb.append(word);
sb.append(" ");
}
}
String newStr = sbVowel.toString() + sb.toString();
System.out.println("NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = " + c);
System.out.println(newStr);
}
public static boolean isVowel(char ch) {

60 | P a g e
ch = Character.toUpperCase(ch);
boolean ret = false;
if (ch == 'A'
|| ch == 'E'
|| ch == 'I'
|| ch == 'O'
|| ch == 'U')
ret = true;
return ret;
}
}
Output:
ENTER THE SENTENCE:
Enter a sample sentence here.
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 0
Enter sample sentence here
Variable Description
 Scanner in: An instance of the Scanner class to read input from the user.
 String ipStr: The input sentence from the user.
 int len: The length of the input sentence.
 char lastChar: The last character of the input sentence.
 String str: The input sentence without the last punctuation character.
 StringTokenizer st: A StringTokenizer object to split the sentence into words.
 StringBuffer sbVowel: A StringBuffer to store words that begin and end with a vowel.
 StringBuffer sb: A StringBuffer to store other words.
 int c: A counter to count words that begin and end with a vowel.
 String word: A variable to hold each word as it is processed.
 int wordLen: The length of the current word.
 String newStr: The final rearranged sentence with words beginning and ending with vowels placed
first.
Algorithm
1. Initialize Variables:
o Create a Scanner object to read input from the user.
o Declare the necessary variables to store the input string and other intermediate results.
2. Read Input:
o Prompt the user to enter a sentence.
o Read the sentence using the Scanner object and convert it to uppercase.
3. Validate Input:
o Check if the last character of the input string is a valid punctuation mark ('.', '?', '!').
o If not, print "INVALID INPUT" and terminate the program.
4. Remove Punctuation:
o Remove the last character (punctuation mark) from the input string.
5. Tokenize Sentence:
o Use StringTokenizer to split the sentence into individual words.
6. Process Words:

61 | P a g e
o Initialize two StringBuffer objects: sbVowel for words that begin and end with a vowel, and sb
for other words.
o Initialize a counter c to zero.
o Iterate through each word in the sentence:
 Check if the word begins and ends with a vowel using the isVowel method.
 If true, append the word to sbVowel and increment the counter c.
 Otherwise, append the word to sb.
7. Construct New Sentence:
o Concatenate the words from sbVowel and sb to form the rearranged sentence.
8. Print Results:
o Print the number of words that begin and end with a vowel.
o Print the new sentence

62 | P a g e
Conclusion

These Java programs collectively demonstrate


essential programming skills, from basic input/output
operations to complex algorithm implementations.
They serve as practical examples of solving real-world
problems using Java, highlighting its strengths in
mathematical computations, array and string
manipulations, and data processing. By incorporating
improvements and optimizations, these programs can
be further refined for better performance and user
experience.

63 | P a g e
Biblography
Name of the book: I.S.C Compute Science
Name of the author: Vijay Kumar Pandey,Dilip Kumar Sha
Name of the publisher: Avichal Publishing Company
Name of the website: www.google.,wikipedia.org

64 | P a g e

You might also like