Compuer Science Project
Compuer Science Project
PROJECT
NAME - SHREYANSH GUPTA
CLASS - 12
SECTION – C
ROLL NO. – 53
2. ACKNOWLEDGEMENT 2
3 INDEX 3
4 PROGRAMS 4 - 66
5 BIBLIOGRAPHY 67
Question 1:
Write a program to generate Fibonacci series.
PROGRAM
// Class to generate Fibonacci series
class Fibonacci {
// Method to print Fibonacci series up to a given count
void printFibonacci(int count) {
int n1 = 0, n2 = 1, n3; // Initializing first two terms
System.out.print(n1 + " " + n2); // Printing the first two terms
// Loop to generate the rest of the Fibonacci series
for (int i = 2; i < count; ++i) {
n3 = n1 + n2; // Calculating next term
System.out.print(" " + n3); // Printing next term
n1 = n2; // Updating n1 and n2
n2 = n3;
}
System.out.println(); // New line after series
}
}
Output:
0 1 1 2 3 5 8 13 21 34
QUESTION 2:
Write a program to check if it is palindrome or not.
Output-
121 is a palindrome.
454 is a palindrome.
123 is not a palindrome.
PROGRAM
// Class to check if a number is palindrome
class Palindrome {
// Method to check if given number is palindrome
boolean isPalindrome(int number) {
int original = number; // Storing original number
int reverse = 0; // Variable to store reversed number
// Loop to reverse the number
while (number != 0) {
int digit = number % 10; // Extracting last digit
reverse = reverse * 10 + digit; // Adding digit to reversed number
number /= 10; // Removing last digit
}
return original == reverse; // Checking if original and reversed numbers
are same
}
}
Output-
370 is a Armstrong number.
150 is not a Armstrong number.
153 is a Armstrong number.
PROGRAM
// Class to check if a number is Armstrong number
class Armstrong {
// Method to check if given number is Armstrong number
boolean isArmstrong(int number) {
int original = number; // Storing original number
int sum = 0; // Variable to store sum of powers of digits
int digits = Integer.toString(number).length(); // Calculating number of
digits
// Loop to calculate sum of powers of digits
while (number != 0) {
int digit = number % 10; // Extracting last digit
sum += Math.pow(digit, digits); // Adding power of digit to sum
number /= 10; // Removing last digit
}
return sum == original; // Checking if sum is equal to original number
}
}
Algorithm:
1. Input integer ‘n’ from user.
2. If ‘n’ is less than 2, print "Not prime" and stop.
3. Initialize a counter ‘c’ to 0.
4. Start a for loop ‘i’ from 1 to ‘n’:
5. If ‘n’ is divisible by ‘i’, increment counter ‘c’ by 1.
6. If ‘c’ is 2, print "Prime".
7. Otherwise, print "Not prime".
Program:
import java.util.*;
class PrimeNumber{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int n = sc.nextInt();
if (n < 2) {
System.out.println("Not prime");
}
int c = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c++;
} }
if (c = = 2) {
System.out.println("Prime");
} else {
System.out.println("Not prime");
}}}
Enter a number:
10
Not prime
Enter a number:
17
Prime
Question 5:
Write a program to check if a number is a palindrome.
Algorithm:
1. Input integer ‘n’ from user.
2. Store the original value of ‘n’ in ‘on’.
3. Initialize ‘rev’ to 0.
4. While ‘n’ is greater than 0:
5. Extract the last digit of ‘n’ and add it to ‘rev’.
6. Remove the last digit from ‘n’.
7. If ‘rev’ is equal to ‘o’, print "Palindrome".
8. Otherwise, print "Not palindrome".
Program:
import java.util.*;
class PalindromeNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int n = sc.nextInt();
int original = n;
int rev = 0;
while (n > 0) {
int r = n % 10;
rev = rev * 10 + digit;
n /= 10; }
if (reverse = = original) {
System.out.println("Palindrome");
} else {
System.out.println("Not palindrome");
}}}
Enter a number:
123
Not palindrome
Enter a number:
1221
Palindrome
Question 6:
Write a program to check if a number is an Armstrong number.
Algorithm:
1. Input integer ‘n’ from user.
2. Store the original value of ‘n’ in ‘original’.
3. Initialize ‘sum’ to 0.
4. Calculate the number of digits in ‘n’ and store in ‘numDigits’.
5. While ‘n’ is greater than 0:
6. Extract the last digit of ‘n’.
7. Raise the digit to the power of ‘numDigits’ and add it to ‘sum’.
8. Remove the last digit from ‘n’.
9. If ‘sum’ is equal to ‘original’, print "Armstrong number".
10.Otherwise, print "Not an Armstrong number".
Program:
import java.util.*;
class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int n = sc.nextInt();
int original = n;
int sum = 0;
int numDigits = 0;
int temp = n;
while (temp != 0) {
temp /= 10;
numDigits++;
}
temp = n;
while (temp != 0) {
int digit = temp % 10;
int power = 1;
for (int i = 0; i < numDigits; i++) {
power *= digit;
}
sum += power;
temp /= 10;
}
if (sum == original) {
System.out.println("Armstrong number");
} else {
System.out.println("Not an Armstrong number");
}}}
Enter a number:
123
Not an Armstrong number
Enter a number:
9474
Armstrong number
Question 7:
Write a program to find the HCF and LCM of two numbers.
Algorithm:
1. Input two integers ‘a’ and ‘b’ from user.
2. Store the original values of ‘a’ and ‘b’ in ‘a1’ and ‘b1’.
3. Use a loop to find the HCF of ‘a’ and ‘b’:
4. While ‘b’ is not zero:
5. Set ‘temp’ to ‘b’.
6. Set ‘b’ to ‘a % b’.
7. Set ‘a’ to ‘temp’.
8. Set ‘hcf’ to ‘a’.
9. Calculate ‘lcm’ as ‘(a1 * b1) / hcf’.
10.Print ‘hcf’ and ‘lcm’.
Program:
import java.util.*;
class Hcflcm {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = sc.nextInt();
int b = sc.nextInt();
int a1 = a;
int b1 = b;
while (b! = 0) {
int temp = b;
b = a % b;
a = temp;
}
int hcf = a;
int lcm = (a1 * b1) / hcf;
System.out.println("HCF: " + hcf);
System.out.println("LCM: " + lcm);
}}
Question 8:
Write a program to find the factorial of a number.
Algorithm:
1. Input integer ‘n’ from user.
2. Initialize ‘factorial’ to 1.
3. For ‘i’ from 1 to ‘n’, multiply ‘factorial’ by ‘i’.
4. Print ‘factorial’.
Program:
import java.util.*;
class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int n = sc.nextInt();
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial: " + factorial);
}}
Enter a number:
0
Factorial: 1
Enter a number:
7
Factorial: 5040
Question 9:
Write a program to print the Fibonacci series up to ‘n’ terms.
Algorithm:
1. Input integer ‘n’ from user.
2. Initialize first and second terms as 0 and 1.
3. Print the first two terms.
4. Start a loop from 3 to ‘n’:
5. Calculate the next term as the sum of the previous two terms.
6. Print the next term.
7. Update the previous terms.
Program:
import java.util.*;
class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of terms:");
int n = sc.nextInt();
int first = 0, second = 1;
Question 7:
Design a class Perfect to check if a given number is a perfect number or not. [A
number is said to be perfect if sum of the factors of the number excluding itself
is equal to the original number]
Example: 6 = 1 + 2 + 3 (where 1, 2 and 3 are factors of 6, excluding itself) [10]
Some of the members of the class are given below:
Class name: Perfect
Data members/instance variables:
num: to store the number
Member functions:
Perfect (int nn): parameterized constructor to initialize the data member
num=nn
int sum_of_factors(int i): returns the sum of the factors of the number(num),
excluding itself, using a recursive technique
void check(): checks whether the given number is perfect by invoking the
function sum_of_factors() and displays the result with an appropriate message
Specify the class Perfect giving details of the constructor(), int
sum_of_factors(int) and void check().
Define a main() function to create an object and call the functions accordingly
to enable the task.
Algorithm
1. Define the Perfect class with num as the instance variable.
2. Initialize num using the parameterized constructor Perfect(int nn).
3. Define the sum_of_factors(int i) method to calculate the sum of factors
of num, excluding itself, recursively.
o If i is greater than num/2, return 0 (base case).
o If num is divisible by i, add i to the recursive call of
sum_of_factors(i + 1).
o Otherwise, recursively call sum_of_factors(i + 1) without adding.
4. Define the check() method to verify if the number is perfect:
o Calculate the sum of factors using sum_of_factors(1).
o Print if the number is perfect or not based on the result.
5. Create a main method to test the program with user input.
Program:
import java.util.*;
class Perfect {
int num;
Perfect(int nn) {
num = nn;
}
int sum_of_factors(int i) {
if (i > num / 2) return 0;
if (num % i == 0) return i + sum_of_factors(i + 1);
return sum_of_factors(i + 1);
}
void check() {
int sum = sum_of_factors(1);
if (sum == num) {
System.out.println(num + " is a Perfect Number.");
} else {
System.out.println(num + " is not a Perfect Number.");
}}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
Perfect obj = new Perfect(n);
obj.check();
}}
Three Sample Outputs;
Enter a number: 6
6 is a Perfect Number.
Enter a number: 28
28 is a Perfect Number.
Enter a number: 12
12 is not a Perfect Number.
Question 11:
Write a program to convert a binary number to decimal.
Algorithm:
1. Input a binary number as a string.
2. Initialize ‘decimal’ to 0.
3. Loop through each digit in the binary string from left to right:
4. Multiply the current ‘decimal’ by 2 and add the current digit.
5. Print the decimal value.
Program:
import java.util.*;
class BinaryToDecimal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a binary number:");
String binary = sc.next();
int decimal = 0;
for (int i = 0; i < binary.length(); i++) {
decimal = decimal * 2 + (binary.charAt(i) - '0');
}
System.out.println("Decimal: " + decimal);
}}
Algorithm:
1. Input an integer ‘n’ from user.
2. Initialize an empty string for binary.
3. While ‘n’ is greater than 0:
4. Prepend the remainder of ‘n’ divided by 2 to the binary string.
5. Divide ‘n’ by 2.
6. Print the binary string.
Program:
import java.util.*;
class DecimalToBinary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a decimal number:");
int n = sc.nextInt();
String binary = "";
while (n > 0) {
binary = (n % 2) + binary;
n /= 2;
}
System.out.println("Binary: " + binary);
}}
Three Sample Outputs:
Enter a decimal number:
10
Binary: 1010
Question 13:
Write a program to sort an array using Selection Sort.
Algorithm:
1. Input the size of the array and the elements.
2. For each index ‘i’ from 0 to size-1:
3. Set ‘minIndex’ to ‘i’.
4. For each index ‘j’ from ‘i + 1’ to size:
5. If the element at ‘j’ is less than the element at ‘minIndex’, update
‘minIndex’.
6. Swap the elements at ‘i’ and ‘minIndex’.
7. Print the sorted array.
Program:
import java.util.*;
class SelectionSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}}
Question 11:
Write a program to sort an array using Bubble Sort.
Algorithm:
1. Input the size of the array and the elements.
2. For each index ‘i’ from 0 to size-1:
3. For each index ‘j’ from 0 to size-i-2:
4. If the element at ‘j’ is greater than the element at ‘j+1’, swap them.
5. Print the sorted array.
Program:
import java.util.*;
class BubbleSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}}}
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}}
Question 14:
Define a class Articles that has data members
String str;
int freqa to count total "a" articles,
int freqan: to count total "an" article
int freqthe: to count total "the" articles,
Member functions
Articles()- To initialize str, freqa, freqan and freqthe as 0
void readstring()- to input a string
void count ()- to count total "a" "an" and "the" artices of string
Void display () to display frequency of each article
Algorithm
1. Initialize Class:
o Define a class Articles with the following data members: str, freqa,
freqan, freqthe.
o Initialize str to an empty string, and freqa, freqan, freqthe to 0 in
the constructor.
2. Input Method:
o Define the readstring() method to input a string from the user and
assign it to str.
3. Count Method:
o Define the count() method to:
Split the string str into words.
Iterate through each word and increment the respective
counters (freqa, freqan, freqthe) based on whether the
word is "a", "an", or "the".
4. Display Method:
o Define the display() method to print the frequencies of "a", "an",
and "the".
Program:
import. java.util*;
class Articles {
String str;
int freqa;
int freqan;
int freqthe;
Articles() {
str = "";
freqa = 0;
freqan = 0;
freqthe = 0;
}
void readstring() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
str = sc.nextLine();
}
void count() {
String[] words = str.split("\\s+");
for (String word : words) {
if (word.equals("a")) {
freqa++;
} else if (word.equals("an")) {
freqan++;
} else if (word.equals("the")) {
freqthe++;
}}}
void display() {
System.out.println("Frequency of 'a': " + freqa);
System.out.println("Frequency of 'an': " + freqan);
System.out.println("Frequency of 'the': " + freqthe);
}}
Enter a string:
a cat and an apple sat on the mat
Frequency of 'a': 1
Frequency of 'an': 1
Frequency of 'the': 1
Enter a string:
the sun rises in the east and sets in the west
Frequency of 'a': 0
Frequency of 'an': 0
Frequency of 'the': 3
Question 15:
Write a program to find the maximum element in an array.
Algorithm:
1. Input the size of the array and the elements.
2. Initialize ‘max’ to the first element.
3. Loop through each element of the array:
4. If the current element is greater than ‘max’, update ‘max’.
5. Print ‘max’.
Program:
import java.util.*;
class Max {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}}
System.out.println("Maximum element: " + max);
}}
Question 16:
Write a program to find the minimum element in an array.
Algorithm:
1. Input the size of the array and the elements.
2. Initialize ‘min’ to the first element.
3. Loop through each element of the array:
4. If the current element is less than ‘min’, update ‘min’.
5. Print ‘min’.
Program:
import java.util.*;
class Min {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
int min = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}}
Question 17:
Write a program to count the number of vowels in a string.
Algorithm:
1. Input a string from user.
2. Initialize a counter count to 0.
3. Loop through each character of the string:
4. If the character is a vowel (a, e, i, o, u), increment count.
5. Print the count of vowels.
Program:
import java.util.*;
class Count {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str = sc.nextLine();
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}}
System.out.println("Number of vowels: " + count);
}}
Enter a string:
Programming
Number of vowels: 3
Enter a string:
Count the vowels
Number of vowels: 6
Question 18:
Write a program to reverse a string.
Algorithm:
1. Input a string from user.
2. Initialize an empty string for reversed.
3. Loop through each character of the string in reverse order:
4. Append each character to the reversed string.
5. Print the reversed string.
Program:
import java.util.*;
class Reverse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str = sc.nextLine();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed string: " + reversed);
}}
Enter a string:
Java Programming
Reversed string: gnimmargorP avaJ
Enter a string:
Count
Reversed string: tnuoC
Question 19:
Write a program to check if a string is a palindrome.
Algorithm:
1. Input a string from user.
2. Initialize an empty string for reversed.
3. Loop through each character of the string in reverse order:
4. Append each character to the reversed string.
5. If the original string equals the reversed string, it’s a palindrome.
6. Print the result.
Program:
import java.util.*;
class Palindrome{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str = sc.nextLine();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
if (str.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}}
Enter a string:
hello
The string is not a palindrome.
Enter a string:
racecar
The string is a palindrome.
Question 20:
A register is an entity which can hold a maximum of 100 names. The register
enables the user to add and remove names from the topmost end only.
Define a class Register with the following details:
Class name: Register
Data members:
stud[]: array to store the names of the students
cap: stores the maximum capacity of the array to point the index of the top end
top: to point the index of the top end
Member functions:
Register (int max): constructor to initialize the data member cap = max, top = -1
and create the string array
void push(String n): to add names in the register at the top location if possible,
otherwise display the message “OVERFLOW” String pop(): removes and returns
the names from the topmost location of the register if any, else returns “$$”
void display (): displays all the names in the register
Specify the class Register giving details of the functions void push(String) and
String pop().
Assume that the other functions have been defined.
Algorithm
1. Initialize the Register
o Define a class Register with data members: stud[] (an array to hold
names), cap (capacity), and top (index of the top element).
o In the constructor, set cap = max, top = -1, and initialize stud with
cap size.
2. Add a Name (push)
o Check if the top is at the maximum limit (cap - 1):
If yes, print "OVERFLOW".
Otherwise, increment top and set stud[top] to the given
name.
3. Remove a Name (pop)
o Check if top is -1 (indicating an empty register):
If yes, return "$$".
Otherwise, store stud[top] in a variable, decrement top, and
return the stored name.
4. Display Names (display)
o If top is -1, print "Register is empty".
o Otherwise, iterate from 0 to top and print each name in stud.
Program:
class Register {
String[] stud;
int cap;
int top;
Register(int max) {
cap = max;
top = -1;
stud = new String[cap];
}
void push(String n) {
if (top == cap - 1) {
System.out.println("OVERFLOW");
} else {
top++;
stud[top] = n;
}}
String pop() {
if (top == -1) {
return "$$";
} else {
String removedName = stud[top];
top--;
return removedName;
}}
void display() {
if (top == -1) {
System.out.println("Register is empty");
} else {
for (int i = 0; i <= top; i++) {
System.out.println(stud[i]);
}}}}
Question 21:
A class salesman defines personal data of a salesman, while another class sales
defines the bill number, name of the item, number of items sold and price of
the item. The details of the class are:
Class Name: Salesman
Data Members:
name: string variable to store name of salesman
address: string variable to store address
Member functions:
Salesman (): constructor to assign null (“”) to name and address
void readdetails (string n, string ad): to assign ‘n’ to name and ‘ad’ to address
void show (): to print values of name and address using suitable headings
Algorithm:
1. Define a class Salesman with data members name and address.
2. Implement a constructor to initialize name and address to empty strings.
3. Define readdetails(String n, String ad) to set name and address.
4. Define show() to display name and address.
5. Define a class Sales extending Salesman with data members billno, qty,
price, psales, and pname.
6. Define readdetails(int b, int q, double p, double s, String pr) to set sales
details.
7. Define calculate() to compute total sales as price * qty + psales.
8. Override show() to display sales details along with salesman details.
Program:
import java.util.*;
Class Salesman {
String name, address;
Salesman () {
name = “ ”;
address = “ ”;
}
void readdetails (String n, String ad) {
name= n;
address= ad;
}
void show(){
System.out.println(“Salesman Name” +name);
System.out.println(Address:” +address);
}}
class Sales extends Salesman {
int billno, qty;
double price, psales;
String pname;
void readdetails (int b, int q, double p, double s, String pr){
billno=b;
qty=q;
price=p;
psales=s;
pname=pr;
}
double calculate (){
return price*qty+psales;
}
void show(){
super.show(){
System.out.println(“Product Name” +pname);
System.out.println(“Bill Number” +billno);
System.out.println(“Quantity” +qty);
System.out.println(“Price” +price);
System.out.println(“Previous Sales” +psales);
System.out.println(“Total Sales” +calculate());
}}
Question 22:
Write a program to calculate the highest and lowest sales and print it.
Program:
import java.util.*;
class Data{
String name[];
double sale[];
Data(){
name=new String [30];
sale=new double [30];
}
void read(){
for(int i=0; i<=30;i++)
{
name[i]= “Salesman”+(i+1);
sale[i]= Math.randon()+100=;
}}
void show(){
for(int i=0; i<30;i++){
System.out.println("Name="+name[i]+ “Sale=”+ sale[i]);
}}}
class Highest extends Data{
int subscript;
Highest(){
super();
subscript=-1;
}
void maximum(){
double maxsale=sale[0];
subscript=0;
for (int i=1; i<30; i++){
if (sale[i]>maxsale){
maxsale=sale[i};
subscript=i;
}}}
void show(){
super.show();
System.out.println("Highest sale by:" name[subscript]+ “Sale=”
+sale[subscript]);
}}
Print element
End Algorithm
import java.util.Stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("Stack elements:");
System.out.println(element);
}
}
Question 24
Write a program to implement a stack with push and pop operation.
ALGORITHM
Algorithm ImplementStack
End Algorithm
Program
import java.util.Stack;
// Push operation
stack.push(10);
stack.push(20);
stack.push(30);
// Pop operation
stack.pop();
Question 25
Write a program to implement a queue with inversion and deletion.
ALGORITHM
Algorithm ImplementQueue
Program
import java.util.LinkedList;
import java.util.Queue;
// Insertion (Enqueue)
queue.add(10);
queue.add(20);
queue.add(30);
// Deletion (Dequeue)
queue.poll();
}
}
Question 26
Write a program to traverse the element of a linked list in reverse direction.
ALGORITHM
Algorithm TraverseLinkedListReverse
Program
import java.util.LinkedList;
import java.util.ListIterator;
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
Question 27
Write a program to implement linked list as queue.
ALGORITHM
Algorithm ImplementLinkedListAsQueue
End Algorithm
Program
import java.util.LinkedList;
import java.util.ListIterator;
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
Question 28
Write a program to Concatenate a String.
Algorithm
Algorithm: Concatenate Two Strings
Program
// Class to concatenate strings
class StringConcatenator {
// Method to concatenate two strings
String concatenate(String str1, String str2) {
return str1 + str2;
}
}
Output
Result 1:
Str1 = hello
Str2 = world
Output = helloworld
Result 2:
Str1 = sch
Str2 = ool
Output = school
Result 3
Str1 = frie
Str2 = nds
Output = friends
Question 29:
Write a program to reverse each word in a string.
Algorithm
1. Input: String input
2. Process:
1. Split input into an array of words.
2. Initialize an empty string result.
3. Loop through each word in the array:
1. Reverse the word.
2. Append the reversed word to result.
4. Trim trailing spaces from result.
3. Output: result
Program
// Class to reverse each word in a string
class WordReverser {
// Method to reverse each word in a given string
String reverseWords(String input) {
String[] words = input.split("\\s+"); // Splitting string into words
StringBuilder result = new StringBuilder();
// Loop to reverse each word
for (String word : words) {
result.append(new StringBuilder(word).reverse().toString()).append(" ");
}
return result.toString().trim(); // Returning result with reversed words
}
}
Output
Output : olleH dlroW
Question 30
Write a program
Program
// Class to convert string case
class CaseConverter {
// Method to convert string to lowercase
String toLowerCase(String input) {
return input.toLowerCase();
}
Output
Result 1:
Result 2:
Lowercase: edward
Uppercase: EDWARD
Result: 3
Lowercase: universe
Uppercase: UNIVERSE
BILBIOGRAPHY
For completing this project I took helps from the
following books and sites:
1. www.comknowledge.com
2. www.programing.com
3. www.Bluej.com
4. www.java.com
I also like to Thank my respected teachers and dear
friends who helped me in completing this project.