Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Compuer Science Project

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)
3 views67 pages

Compuer Science Project

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

COMPUTER SCIENCE

PROJECT
NAME - SHREYANSH GUPTA

CLASS - 12

SECTION – C

ROLL NO. – 53

SESSION – 2024 - 2025


ACKNOWLEDGEMENT
I would like to express my sincere gratitude to all those who
played a significant role in the successful completion of this
Class 12th project.

My deepest appreciation goes to my Computer Science teacher


for their invaluable guidance and support throughout this
project. Their insightful feedback was instrumental in shaping
the direction and quality of my work.
I am grateful to our principal for providing the opportunity to
undertake this project and for the essential resources available
at the school, which significantly aided my research endeavors.

I would also like to extend my thanks to my classmates for


their assistance and encouragement. Their willingness to share
ideas and offer different perspectives proved to be very helpful
throughout the process.

Finally, a special thanks to my family for their unwavering


support and for providing a conducive environment that
allowed me to focus on my work.
INDEX
S.NO TITLE PAGE
1. INTRODUCTION 1

2. ACKNOWLEDGEMENT 2

3 INDEX 3

4 PROGRAMS 4 - 66

5 BIBLIOGRAPHY 67
Question 1:
Write a program to generate Fibonacci series.

Algorithm: Print Fibonacci Series


1. Input: Count of terms to print (count).
2. Initialize: n1 = 0, n2 = 1.
3. Output: Print n1 and n2.
4. Loop: From i = 2 to count - 1.
1. Compute next term: n3 = n1 + n2.
2. Output n3.
3. Update n1 to n2, and n2 to n3.
5. End Loop.

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
}
}

// Main class to test Fibonacci series generation


public class Main {
public static void main(String[] args) {
Fibonacci fib = new Fibonacci(); // Creating object of Fibonacci class
fib.printFibonacci(10); // Calling method to print first 10 terms
}
}

Output:
0 1 1 2 3 5 8 13 21 34

QUESTION 2:
Write a program to check if it is palindrome or not.

Algorithm: Check if Number is Palindrome


1. Input: Number to check (number).
2. Initialize: original = number, reverse = 0.
3. Loop: While number is not 0.
1. Get last digit: digit = number % 10.
2. Update reverse: reverse = reverse * 10 + digit.
3.Remove last digit from number: number = number / 10.
4. End Loop.
5. Check: If reverse is equal to original.
1. If true, output that number is a palindrome.
2. If false, output that number is not a palindrome.

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
}
}

// Main class to test palindrome check


public class Main {
public static void main(String[] args) {
Palindrome palindrome = new Palindrome(); // Creating object of
Palindrome class
int number = 121; // Example number to check
// Checking if number is palindrome and printing result
if (palindrome.isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}
}

// 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
}
}

// Main class to test Armstrong number check


public class Main {
public static void main(String[] args) {
Armstrong armstrong = new Armstrong(); // Creating object of Armstrong
class
int number = 153; // Example number to check
// Checking if number is Armstrong and printing result
if (armstrong.isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
}
QUESTION 3:
Write a program to check if it is palindrome or not.

Algorithm: Check if Number is Armstrong


1. Input: Number to check (number).
2. Initialize: original = number, sum = 0.
3. Calculate: Number of digits (digits) in number.
4. Loop: While number is not 0.
1. Get last digit: digit = number % 10.
2. Update sum: sum = sum + digit^digits.
3. Remove last digit from number: number = number / 10.
5. End Loop.
6. Check: If sum is equal to original.
1. If true, output that number is an Armstrong number.
2. If false, output that number is not an Armstrong number.

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
}
}

// Main class to test Armstrong number check


public class Main {
public static void main(String[] args) {
Armstrong armstrong = new Armstrong(); // Creating object of Armstrong
class
int number = 153; // Example number to check
// Checking if number is Armstrong and printing result
if (armstrong.isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
}
Question 4:
Write a program to check if a number is prime.

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");
}}}

Three Sample Outputs:


Enter a number:
5
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");
}}}

Three Sample Outputs:


Enter a number:
121
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");
}}}

Three Sample Outputs:


Enter a number:
153
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);
}}

Three Sample Outputs:


Enter two numbers:
12 18
HCF: 6
LCM: 36

Enter two numbers:


7 13
HCF: 1
LCM: 91

Enter two numbers:


15 20
HCF: 5
LCM: 60

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);
}}

Three Sample Outputs:


Enter a number:
5
Factorial: 120

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;

System.out.print("Fibonacci Series: " + first + " " + second);


for (int i = 3; i <= n; i++) {
int next = first + second;
System.out.print(" " + next);
first = second;
second = next;
}
System.out.println();
}}

Three Sample Outputs:


Enter the number of terms:
5
Fibonacci Series: 0 1 1 2 3

Enter the number of terms:


8
Fibonacci Series: 0 1 1 2 3 5 8 13

Enter the number of terms:


10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

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);
}}

Three Sample Outputs:


Enter a binary number:
1010
Decimal: 10

Enter a binary number:


1111
Decimal: 15

Enter a binary number:


1001
Decimal: 9
Question 12:
Write a program to convert a decimal number to binary.

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

Enter a decimal number:


15
Binary: 1111

Enter a decimal number:


9
Binary: 1001

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();
}}

Three Sample Outputs:


Enter the size of the array:
5
Enter the elements of the array:
64 25 12 22 11
Sorted array:
11 12 22 25 64

Enter the size of the array:


4
Enter the elements of the array:
34 7 23 32
Sorted array:
7 23 32 34

Enter the size of the array:


6
Enter the elements of the array:
90 40 20 50 30 10
Sorted array:
10 20 30 40 50 90

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();
}}

Three Sample Outputs:


Enter the size of the array:
5
Enter the elements of the array:
64 25 12 22 11
Sorted array:
11 12 22 25 64
Enter the size of the array:
4
Enter the elements of the array:
34 7 23 32
Sorted array:
7 23 32 34

Enter the size of the array:


6
Enter the elements of the array:
90 40 20 50 30 10
Sorted array:
10 20 30 40 50 90

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);
}}

Three sample outputs


Enter a string:
the quick brown fox jumps over the lazy dog a an the
Frequency of 'a': 1
Frequency of 'an': 1
Frequency of 'the': 3

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);
}}

Three Sample Outputs:


Enter the size of the array:
5
Enter the elements of the array:
35728
Maximum element: 8

Enter the size of the array:


4
Enter the elements of the array:
10 20 5 30
Maximum element: 30

Enter the size of the array:


3
Enter the elements of the array:
123
Maximum element: 3

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];
}}

System.out.println("Minimum element: " + min);


}}

Three Sample Outputs:


Enter the size of the array:
5
Enter the elements of the array:
35728
Minimum element: 2

Enter the size of the array:


4
Enter the elements of the array:
10 20 5 30
Minimum element: 5

Enter the size of the array:


3
Enter the elements of the array:
123
Minimum element: 1

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);
}}

Three Sample Outputs:


Enter a string:
Hello World
Number of vowels: 3

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);
}}

Three Sample Outputs:


Enter a string:
Hello
Reversed string: olleH

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.");
}}

Three Sample Outputs:


Enter a string:
madam
The string is 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]);
}}}}

Three Sample Outputs:


Register reg = new Register(3);
reg.push("Alice");
reg.push("Bob");
reg.push("Charlie");
reg.display();
Alice
Bob
Charlie

Register reg = new Register(2);


reg.push("Alice");
reg.push("Bob");
reg.push("Charlie");
OVERFLOW

Register reg = new Register(2);


reg.push("Alice");
reg.pop();
reg.display();
Register is empty

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

Class name: Sales


Data members;
billno, qty: integer to store bill number and quantity
price, psales: doubletype to store price and previous sales amount
pname: string variable to store name of product
Member functions:
void readdetails(int b, int q, double p, double s, string pr): to assign ‘b’ to billno,
‘q’ to qty, ‘p’ to price, ‘s’ to psales and ‘pr’to pname
double calculate (): to calculate and return total sales using formula
p*qty+sales
void show(): to display values of pname, billno, qty, price, and sales and total
sales by invoking suitable function
You need not create main () function.

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());
}}

Three Sample Outputs:


Salesman Name: Arindam Sen
Address: 15 Park Street, Kolkata
Product Name: Laptop
Bill Number: 101
Quantity: 2
Price: 750.0
Previous Sales: 500.0
Total Sales: 2000.0

Salesman Name: Priya Banerjee


Address: 24 Ballygunge, Kolkata
Product Name: Mobile Phone
Bill Number: 102
Quantity: 5
Price: 200.0
Previous Sales: 1000.0
Total Sales: 2000.0
Salesman Name: Anil Chatterjee
Address: 78 Salt Lake, Kolkata
Product Name: Tablet
Bill Number: 103
Quantity: 3
Price: 300.0
Previous Sales: 600.0
Total Sales: 1500.0

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]);
}}

Three Sample Outputs:


Name = Salesman1 Sale = 345.23
Name = Salesman2 Sale = 567.89
...
Name = Salesman30 Sale = 432.12
Highest sale by: Salesman2 Sale = 567.89

Name = Salesman1 Sale = 123.45


Name = Salesman2 Sale = 678.90
...
Name = Salesman30 Sale = 543.21
Highest sale by: Salesman2 Sale = 678.90

Name = Salesman1 Sale = 234.56


Name = Salesman2 Sale = 789.01
...
Name = Salesman30 Sale = 654.32
Highest sale by: Salesman2 Sale = 789.01
Question 23:
Write a program to reverse the element of stack.
ALGORITHM

Algorithm (Traverse Stack)


Create an empty stack

Push elements onto the stack

For each element in the stack

Print element

End Algorithm

import java.util.Stack;

public class StackTraversal {

public static void main(String[] args) {

Stack<Integer> stack = new Stack<>();

stack.push(1);

stack.push(2);

stack.push(3);

stack.push(4);

stack.push(5);

// Traversing the stack

System.out.println("Stack elements:");

for (Integer element : stack) {

System.out.println(element);

}
}

Question 24
Write a program to implement a stack with push and pop operation.

ALGORITHM
Algorithm ImplementStack

Create an empty stack

Push elements onto the stack

Print the stack

Pop an element from the stack

Print the stack

End Algorithm

Program
import java.util.Stack;

public class StackImplementation {

public static void main(String[] args) {

Stack<Integer> stack = new Stack<>();

// Push operation

stack.push(10);

stack.push(20);

stack.push(30);

System.out.println("Stack after pushes: " + stack);

// Pop operation

stack.pop();

System.out.println("Stack after one pop: " + stack);


}

Question 25
Write a program to implement a queue with inversion and deletion.

ALGORITHM
Algorithm ImplementQueue

Create an empty queue

Insert elements into the queue

Print the queue

Remove an element from the queue

Program
import java.util.LinkedList;

import java.util.Queue;

public class QueueImplementation {

public static void main(String[] args) {

Queue<Integer> queue = new LinkedList<>();

// Insertion (Enqueue)

queue.add(10);

queue.add(20);

queue.add(30);

System.out.println("Queue after insertion: " + queue);

// Deletion (Dequeue)

queue.poll();

System.out.println("Queue after one deletion: " + queue);

}
}

Question 26
Write a program to traverse the element of a linked list in reverse direction.

ALGORITHM
Algorithm TraverseLinkedListReverse

Create an empty linked list

Add elements to the linked list

Get a list iterator starting from the end of the list

While iterator has previous elements

Print the previous element

Program
import java.util.LinkedList;

import java.util.ListIterator;

public class LinkedListReverseTraversal {

public static void main(String[] args) {

LinkedList<Integer> list = new LinkedList<>();

list.add(1);

list.add(2);

list.add(3);

list.add(4);

list.add(5);

// Traverse in reverse direction

ListIterator<Integer> iterator = list.listIterator(list.size());

System.out.println("Linked List in reverse:");

while (iterator.hasPrevious()) {
System.out.println(iterator.previous());

Question 27
Write a program to implement linked list as queue.

ALGORITHM
Algorithm ImplementLinkedListAsQueue

Create an empty linked list

Add elements to the end of the linked list

Print the linked list

Remove the first element from the linked list

Print the linked list

End Algorithm

Program
import java.util.LinkedList;

import java.util.ListIterator;

public class LinkedListReverseTraversal {

public static void main(String[] args) {

LinkedList<Integer> list = new LinkedList<>();

list.add(1);

list.add(2);

list.add(3);

list.add(4);

list.add(5);

// Traverse in reverse direction

ListIterator<Integer> iterator = list.listIterator(list.size());


System.out.println("Linked List in reverse:");

while (iterator.hasPrevious()) {

System.out.println(iterator.previous());

Question 28
Write a program to Concatenate a String.

Algorithm
Algorithm: Concatenate Two Strings

1. Input: String str1, String str2


2. Process:
1. Concatenate str1 and str2.
3. Output: Concatenated string

Program
// Class to concatenate strings
class StringConcatenator {
// Method to concatenate two strings
String concatenate(String str1, String str2) {
return str1 + str2;
}
}

// Main class to test concatenating strings


public class Main {
public static void main(String[] args) {
StringConcatenator concatenator = new StringConcatenator(); // Creating
object of StringConcatenator class
String str1 = "Hello ";
String str2 = "World";
// Concatenating strings and printing result
System.out.println("Concatenated String: " +
concatenator.concatenate(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
}
}

// Main class to test reversing each word in a string


public class Main {
public static void main(String[] args) {
WordReverser reverser = new WordReverser(); // Creating object of
WordReverser class
String input = "Hello World";
// Reversing each word in the string and printing result
System.out.println("Original: " + input);
System.out.println("Reversed: " + reverser.reverseWords(input));
}
}

Output
Output : olleH dlroW

Question 30
Write a program

Algorithm: Convert String Case


1. Input: String input, String caseType ("lower" or "upper")
2. Process:
1. If caseType is "lower":
1. Convert input to lowercase.
2. Else if caseType is "upper":
1. Convert input to uppercase.
3. Output: Modified string

Program
// Class to convert string case
class CaseConverter {
// Method to convert string to lowercase
String toLowerCase(String input) {
return input.toLowerCase();
}

// Method to convert string to uppercase


String toUpperCase(String input) {
return input.toUpperCase();
}
}

// Main class to test string case conversion


public class Main {
public static void main(String[] args) {
CaseConverter converter = new CaseConverter(); // Creating object of
CaseConverter class
String input = "Hello World!";
// Converting string to lowercase and printing result
System.out.println("Lowercase: " + converter.toLowerCase(input));
// Converting string to uppercase and printing result
System.out.println("Uppercase: " + converter.toUpperCase(input));
}
}

Output
Result 1:

Lowercase: hello world!

Uppercase: HELLO WORLD!

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.

You might also like