0% found this document useful (0 votes)
6 views38 pages

Computer projectX

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
6 views38 pages

Computer projectX

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 38

Name :

Class : X-B

Subject : Computer

SUBMITTED TO-
Acknowledgement :

I would like to express my heartfelt gratitude to my

computer teacher, Resham Ma'am, for her invaluable

guidance and support throughout the development of this

project. Her expertise and encouragement have played a

significant role in enhancing my understanding of Java

programming concepts.

I would also like to thank ChatGPT for providing me with

helpful resources and programming examples that

facilitated my learning and contributed to the successful

completion of this project.

Thank you to all who supported me in this endeavor.


1.Programs depicting the concept of static and non- static methods.
Program 1:Static Methods:
class StaticMethodExample {
public static int square(int number) {
return number * number;
}
public static void main(String[] args) {
int num = 5;
int result = StaticMethodExample.square(num);
System.out.println("The square of " + num + " is: " + result);
} Output of Program 1:
} The square of 5 is: 25

Program 2:Non-Static Methods:

class NonStaticMethodExample {
public int cube(int number) {
return number * number * number;
}
public static void main(String[] args) {
NonStaticMethodExample example = new NonStaticMethodExample();
int num = 4;
int result = example.cube(num);
System.out.println("The cube of " + num + " is: " + result);
}
} Output of Program 2:
The cube of 4 is: 64
2. Design a class with the following specifications:Class name: Student
Member variables:
name — name of studentage — age of studentmks — marks obtainedstream
— stream allocated
(Declare the variables using appropriate data types)Member methods:void
accept() — Accept name, age and marks using methods of Scanner
class.void allocation() — Allocate the stream as per following criteria:mks,
stream
>= 300, Science and Computer
>= 200 and < 300, Commerce and Computer
>= 75 and < 200, Arts and Animation
< 75, Try Again

import java.util.*;

public class Student

String name;

int age;

int mks;

String stream;

public void accept()

Scanner sc = new Scanner(System.in);

System.out.print("Enter student name: ");

name = sc.nextLine();

System.out.print("Enter student age: ");

age = sc.nextInt();

System.out.print("Enter marks obtained: ");

mks = sc.nextInt();

public void allocation() {


if (mks >= 300) {

stream = "Science and Computer";

} else if (mks >= 200 && mks < 300) {

stream = "Commerce and Computer";

} else if (mks >= 75 && mks < 200) {

stream = "Arts and Animation";

} else {

stream = "Try Again";

public void print() {

System.out.println("Student Name: " + name);

System.out.println("Student Age: " + age);

System.out.println("Marks Obtained: " + mks);

System.out.println("Stream Allocated: " + stream);

public static void main(String[] args) {

Student student = new Student();

student.accept();

student.allocation();

student.print();

Output:-
Variable Data
Enter student name: John Doe Description
Name Type
Enter student age: 18
name String Holds the name of the student.
Enter marks obtained: 250
age int Stores the age of the student.
Student Name: John Doe
Stores the marks obtained by the
mks int
Student Age: 18 student.

Marks Obtained: 250 Stores the stream allocated based


stream String
on the marks.
Stream Allocated: Commerce and Computer

4. Define a class to accept a String and print the number of digits,


alphabets and special characters in the string.Example:
S = "KAPILDEV@83"
Output:
Number of digits – 2
Number of Alphabets – 8
Number of Special characters – 1

import java.util.Scanner;
public class StringAnalysis {
// Member variables to store the counts
private String inputString;
private int digitsCount;
private int alphabetsCount;
private int specialCharsCount;
public void accept() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
inputString = sc.nextLine();
}
public void analyze() {
digitsCount = 0;
alphabetsCount = 0;
specialCharsCount = 0;
for (int i = 0; i < inputString.length(); i++) {
char ch = inputString.charAt(i);
if (Character.isDigit(ch)) {
digitsCount++;
}
else if (Character.isLetter(ch)) {
alphabetsCount++;
}
else {
specialCharsCount++;
}
}
}
public void print() {
System.out.println("Number of digits: " + digitsCount);
System.out.println("Number of Alphabets: " + alphabetsCount);
System.out.println("Number of Special characters: " +
specialCharsCount);
}

public static void main(String[] args) {


StringAnalysis sa = new StringAnalysis();
sa.accept();
sa.analyze();
sa.print();
}
}

Output :
Enter a string: Hello@123!
Number of digits: 3
Number of Alphabets: 5
Number of Special characters: 2
Data
Variable Name Description
Type

inputString String Stores the input string provided by the user.

digitsCount int Stores the number of digits in the input string.

alphabetsCou Stores the number of alphabetic characters in the input


int
nt string.
7. Write a program in Java to accept a string in lower case and change the first
letter of every word to upper case. Display the new string.
Sample input: we are in cyber world
Sample output: We Are In Cyber World

import java.util.Scanner;

public class CapitalizeWords

public String convertToTitleCase(String inputString) {

String[] words = inputString.split(" ");

StringBuilder result = new StringBuilder();

for (String word : words) {

if (word.length() > 0) {

String capitalizedWord = word.substring(0, 1).toUpperCase()

word.substring(1);

result.append(capitalizedWord).append(" ");

return result.toString().trim();

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a string in lowercase: ");

String inputString = sc.nextLine();

CapitalizeWords capitalize = new CapitalizeWords();

String result = capitalize.convertToTitleCase(inputString);

System.out.println("Converted String: " + result);

}
For The Input: Enter a string in lowercase: we are in cyber world
The Output Will Be : Converted String: We Are In Cyber World

Variable Description:

Variable Name Data Type Description

inputString String Stores the input string entered by the user in lowercase.

An array of strings, each element being a word from the


words String[]
input string.

Used to accumulate the capitalized words and construct


result StringBuilder
the final output string.

capitalizedWord String Holds each word after capitalizing the first letter.

Object of the CapitalizeWords class used to call the


capitalize CapitalizeWords
convertToTitleCase method.

sc Scanner Object used to accept user input from the console.

9.Write a program to accept a number and check and display whether it is a spy
number or not. (A number is spy if the sum of its digits equals the product of its
digits.)Example: consider the number 1124.
Sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1 x 1 x 2 x 4 = 8

import java.util.Scanner;
public class SpyNumber {
public static boolean isSpyNumber(int number) {
int sum = 0;
int product = 1;
while (number > 0) {E
int digit = number % 10;
sum += digit; // Add the digit to sum
product *= digit; // Multiply the digit to product
number /= 10; // Remove the last digit
}
return sum == product;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
if (isSpyNumber(number)) {
System.out.println(number + " is a Spy Number.");
} else
{
System.out.println(number + " is not a Spy Number.");
}
}
}

For the input:

Enter a number: 1124


The Output:
1124 is a Spy Number.
Variable Description:

Variable Data
Description
Name Type

number int The input number provided by the user.

sum int Stores the sum of the digits of the number.

product int Stores the product of the digits of the


Variable Data
Description
Name Type

number.

Represents each digit extracted from the


digit int
number during iteration.

Object used to accept user input from the


sc Scanner
console.

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


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

import java.util.Scanner;

public class AreaCalculator {


public double area(double a, double b, double c) {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public double area(int a, int b, int height) {
return 0.5 * height * (a + b);
}
public double area(double diagonal1, double diagonal2) {
return 0.5 * diagonal1 * diagonal2;
}
public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sides of the scalene triangle (a, b, c): ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
System.out.printf("Area of the scalene triangle: %.2f%n", calculator.area(a, b, c));
System.out.println("Enter the lengths of the parallel sides (a, b) and height: ");
int sideA = sc.nextInt();
int sideB = sc.nextInt();
int height = sc.nextInt();
System.out.println("Area of the trapezium: %.2f%n", calculator.area(sideA, sideB,
height));
System.out.println("Enter the diagonals of the rhombus (diagonal1, diagonal2): ");
double diagonal1 = sc.nextDouble();
double diagonal2 = sc.nextDouble();
System.out.println("Area of the rhombus: %.2f%n", calculator.area(diagonal1,
diagonal2));
}
}

For the triangle sides:


Enter the sides of the scalene triangle (a, b, c):
3.0
4.0
5.0
Output:
Area of the scalene triangle: 6.00
13. Write a program to print a string in reverse order.

import java.util.Scanner;
public class ReverseString
{
public static String reverse(String input) {
StringBuilder reversed = new StringBuilder(input);
return reversed.reverse().toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
String reversedString = reverse(inputString);
System.out.println("Reversed string: " + reversedString);
}
}

Input :
Enter a string: Hello World
The output will be:
Reversed string: dlroW olleH

Variable Description:
Variable Name Data Type Description
inputString String Stores the input string provided by the user.
reversedString String Stores the reversed version of the input string.
sc ScannerObject used to accept user input from the console.
reversedStringBuilder Used to manipulate and reverse the input string
efficiently.
19. Write a program to search for an element in an array using linear search.

import java.util.Scanner;
public class LinearSearch {
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = sc.nextInt();
int[] array = new int[size];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
array[i] = sc.nextInt();
}
System.out.print("Enter the element to search for: ");
int target = sc.nextInnt();
int resultIndex = linearSearch(array, target);
if (resultIndex != -1) { System.out.println("Element " + target + " found at index: " +
resultIndex);
}
else { System.out.println("Element " + target + " not found in the array.");
}}}
For the input:
Enter the size of the array: 5
Enter the elements of the array:
1
3
5
7
9
Enter the element to search for: 5

The output will be:


Element 5 found at index: 2

Variable Description:

Variable Name Data Type Description

size int The size of the array entered by the user.

array int[] An array of integers to store the elements entered by the user.

target int The element that the user wants to search for in the array.

resultIndex int The index of the target element if found, or -1 if not found.

sc Scanner An object to read user input from the console.

23.Write a menu driven program to display the pattern as per user’s choice.
Pattern 1
ABCDE
ABCD
ABC
AB
A
Pattern 2
B
LL
UUU
EEEE

import java.util.Scanner;

public class PatternDisplay {


public static void pattern1() {
for (char i = 'A'; i <= 'E'; i++) {
for (char j = 'A'; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
public static void pattern2() {
char[] characters = {'B', 'L', 'U', 'E'}; // Corresponding characters for Pattern 2
int[] counts = {1, 2, 3, 4}; // Number of times each character is printed

for (int i = 0; i < characters.length; i++) {


for (int j = 0; j < counts[i]; j++) {
System.out.print(characters[i]);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("Menu:");
System.out.println("1. Display Pattern 1");
System.out.println("2. Display Pattern 2");
System.out.println("3. Exit");
System.out.print("Enter your choice (1-3): ");
choice = sc.nextInt();

switch (choice) {
case 1:
System.out.println("Pattern 1:");
pattern1();
break;
case 2:
System.out.println("Pattern 2:");
pattern2();
break;
case 3:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please choose again.");
}
System.out.println();
} while (choice != 3);
}
}

If the user selects Pattern 1:


Menu:
1. Display Pattern 1
2. Display Pattern 2
3. Exit
Enter your choice (1-3): 1
Pattern 1:
ABCDE
ABCD
ABC
AB
A

If the user selects Pattern 2:


Menu:
1. Display Pattern 1
2. Display Pattern 2
3. Exit
Enter your choice (1-3): 2
Pattern 2:
B
LL
UUU
EEEE

Variable Description:
Variable Name Data Type Description
choice int Stores the user's menu choice.
sc Scanner An object to read user input from the console.
24. Write a program to accept a number and check and display whether it is a
Niven number or not.
(Niven number is that number which is divisible by its sum of digits.).
Example:
Consider the number 126. The sum of its digits is 1 + 2 + 6 = 9 and
126 is divisible by 9.

import java.util.Scanner;

public class NivenNumberChecker {

public static int sumOfDigits(int number) {


int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
int sum = sumOfDigits(number);
if (number % sum == 0) {
System.out.println(number + " is a Niven number.");
} else {
System.out.println(number + " is not a Niven number.");
}
}
}

For the input: Variable Description:


Enter a number: 126 Variable Data
Description
Name Type
The output will be:
number int The input number provided by the user.
126 is a Niven number. sum int The sum of the digits of the number.
Object used to accept user input from the
sc Scanner
console.
16. Write a program to input a string. Calculate the total number of characters
and vowels present in the string and also reverse the string.

import java.util.Scanner;

public class StringAnalysis {


public static int countVowels(String str) {
int vowelCount = 0;
str = str.toLowerCase();
for (char c : str.toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
return vowelCount;
}
public static String reverseString(String str) {
StringBuilder reversed = new StringBuilder(str);
return reversed.reverse().toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = sc.nextLine();
int totalCharacters = inputString.length();
int totalVowels = countVowels(inputString);
String reversedString = reverseString(inputString);
System.out.println("Total number of characters: " + totalCharacters);
System.out.println("Total number of vowels: " + totalVowels);
System.out.println("Reversed string: " + reversedString);
}
}
The output will be:
For the input: Total number of characters: 11
Enter a string: Hello World Total number of vowels: 3
Reversed string: dlroW olleH

Variable Description:

Variable Name Data Type Description


inputString String Stores the input string provided by the user.
Stores the total number of characters in the input
totalCharacters int
string.
Stores the total number of vowels in the input
totalVowels int
string.
reversedString String Stores the reversed version of the input string.
sc Scanner An object used to read user input from the console.

6. Write a program to input a number and check and print whether it is a Pronic
number or not. (Pronic number is the number which is the product of two
consecutive integers)Examples:12 = 3 x 420 = 4 x 542 = 6 x 7

import java.util.Scanner;

public class PronicNumberChecker {


public static boolean isPronic(int number) {
for (int i = 0; i * (i + 1) <= number; i++) {
if (i * (i + 1) == number) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
if (isPronic(number)) {
System.out.println(number + " is a Pronic number.");
} else {
System.out.println(number + " is not a Pronic number.");
}
}
}

For the input: The output will be:


Enter a number: 12 12 is a Pronic number.

.
Variable Description:
Variable Name Data Type Description
number int The input number provided by the user.
A loop variable used to check for consecutive
i int
integers.
sc Scanner An object used to read user input from the console.

8.Design a class to overload a function volume() as follows:double volume


(double R) – with radius (R) as an argument, returns the volume of sphere using
the formula.V = 4/3 x 22/7 x R3double volume (double H, double R) – with
height(H) and radius(R) as the arguments, returns the volume of a cylinder
using the formula.V = 22/7 x R2 x Hdouble volume (double L, double B,
double H) – with length(L), breadth(B) and Height(H) as the arguments, returns
the volume of a
cuboid using the formula.
V=LxBxH

public class VolumeCalculator {


public double volume(double R) {
return (4.0 / 3) * (22.0 / 7) * Math.pow(R, 3); // Volume of a sphere
} public double volume(double H, double R) {
return (22.0 / 7) * Math.pow(R, 2) * H; // Volume of a cylinder
}
public double volume(double L, double B, double H) {
return L * B * H; // Volume of a cuboid
}
public static void main(String[] args) {
VolumeCalculator calculator = new VolumeCalculator();
double sphereRadius = 5.0;
double sphereVolume = calculator.volume(sphereRadius);
System.out.printf("Volume of the sphere with radius %.2f is %.2f\n", sphereRadius,
sphereVolume);
double cylinderHeight = 10.0;
double cylinderRadius = 3.0;
double cylinderVolume = calculator.volume(cylinderHeight, cylinderRadius);
System.out.printf("Volume of the cylinder with height %.2f and radius %.2f is %.2f\n",
cylinderHeight, cylinderRadius, cylinderVolume);
double cuboidLength = 4.0;
double cuboidBreadth = 5.0;
double cuboidHeight = 6.0;
double cuboidVolume = calculator.volume(cuboidLength, cuboidBreadth, cuboidHeight);
System.out.printf("Volume of the cuboid with length %.2f, breadth %.2f, and height %.2f
is %.2f\n", cuboidLength, cuboidBreadth, cuboidHeight, cuboidVolume);
}
}

Output :
Volume of the sphere with radius 5.00 is 523.81
Volume of the cylinder with height 10.00 and radius 3.00 is 188.57
Volume of the cuboid with length 4.00, breadth 5.00, and height 6.00 is 120.00

17. Write a program to input a sentence from the user and count the number of
letters and spaces present in it.

import java.util.Scanner;
public class SentenceAnalysis {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();

int letterCount = 0; // To count letters


int spaceCount = 0; // To count spaces
for (char ch : sentence.toCharArray()) {
if (Character.isLetter(ch)) {
letterCount++; // Count letters
} else if (Character.isWhitespace(ch)) {
spaceCount++; // Count spaces
}
}
System.out.println("Number of letters: " + letterCount);
System.out.println("Number of spaces: " + spaceCount);
}
}

For the input:


The output will be:
Enter a sentence: Hello World!
Number of letters: 10
Number of spaces: 1

Variable Description:
Variable Name Data Type Description
sentence String The input sentence provided by the user.
letterCount int To store the count of letters in the sentence.
spaceCount int To store the count of spaces in the sentence.
sc Scanner An object used to read user input from the console.

18. Write a program to search for an element in an array using binary search

import java.util.Scanner;

public class BinarySearch {


public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Calculate the middle index
if (arr[mid] == target) {
return mid; // Return the index if found
}
if (arr[mid] < target) {
left = mid + 1;
} else { // If the target is smaller, ignore the right half
right = mid - 1;
}
}
return -1; // Return -1 if the target is not found
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = sc.nextInt();

int[] arr = new int[n];


System.out.println("Enter " + n + " sorted elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Enter the element to search for: ");
int target = sc.nextInt();
int result = binarySearch(arr, target);

if (result == -1) {
System.out.println("Element not found in the array.");
} else {
System.out.println("Element found at index: " + result);
}
}
}

For the input:


Enter the number of elements in the
array: 5 The output will be:
Enter 5 sorted elements: Element found at index: 2
12345
Enter the element to search for: 3

Variable Description:
Variable Data
Description
Name Type
n int The number of elements in the array.
arr int[] The array of sorted integers provided by the user.
The element that the user wants to search for in the
target int
array.
result int The index of the found element (or -1 if not found).
sc Scanner An object used to read user input from the console.
left int The starting index of the current search range.
right int The ending index of the current search range.
mid int The middle index of the current search range.

20. Define a class to accept values in integer array of size 10. Sort them in an
ascending order using selection sort technique. Display the sorted array.

import java.util.Scanner;
public class SelectionSort {
private int[] arr = new int[10];
public void acceptValues() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 integers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
}
public void selectionSort() {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i; // Assume the minimum is the first element
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update minIndex if a smaller element is found
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public void displaySortedArray() {
System.out.println("Sorted array in ascending order:");
for (int value : arr) {
System.out.print(value + " ");
}
}
public static void main(String[] args) {
SelectionSort sorter = new SelectionSort();
sorter.acceptValues();
sorter.selectionSort();
sorter.displaySortedArray();
}}

For the input:


Enter 10
integers: The output will be:Sorted array in ascending
order:
34
1 2 5 7 8 23 32 34 45 62
7
23
32
5
62
1
45
2
8

Variable Description:
Variable Data
Description
Name Type
arr int[] An array of integers of size 10 to store the user inputs.
sc Scanner An object used to read user input from the console.
The index of the minimum element found in the
minIndex int
unsorted portion of the array.
A temporary variable used for swapping elements
temp int
during sorting.
i, j int Loop variables used for iterating through the array.

10. Write a program to input integer elements into an array of size 20 and
perform the following operations:Display largest number from the array.Display
smallest number from the array.Display sum of all the elements of the array.
import java.util.Scanner;
public class ArrayOperations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[20]; // Array of size 20
System.out.println("Enter 20 integer elements:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt(); // Store user input in the array
}
int largest = arr[0]; // Initialize largest with the first element
int smallest = arr[0]; // Initialize smallest with the first element
int sum = 0; // Initialize sum to 0
for (int num : arr) {
if (num > largest) {
largest = num
}
if (num < smallest) {
smallest = num;
}
sum += num;
}
System.out.println("Largest number: " + largest);
System.out.println("Smallest number: " + smallest);
System.out.println("Sum of all elements: " + sum);
}
}
For the input: The output will be:
Enter 20 integer elements: Largest number: 90
12 Smallest number: 0
5 Sum of all elements:
480
23
34
56
2
89
45
90
1
76
34
22
8
19
0
11
27
49
38

Variable Description:
Variable
Data Type Description
Name
An array of integers of size 20 to store the user
arr int[]
inputs.
Variable
Data Type Description
Name
Variable to store the largest number found in the
largest int
array.
Variable to store the smallest number found in the
smallest int
array.
sum int Variable to store the sum of all elements in the array.
sc Scanner An object used to read user input from the console.
num int Loop variable used to iterate through the array.

12. Write a program to perform binary search on a list of integers given below,
to search for an element input by the user. If it is found display the element
along with its position, otherwise display the message "Search element not
found".5, 7, 9, 11, 15, 20, 30, 45, 89, 97.

import java.util.Scanner;

public class BinarySearchExample {


public static void main(String[] args) {
int[] arr = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97};
Scanner sc = new Scanner(System.in);
System.out.print("Enter the element to search for: ");
int target = sc.nextInt(); // Accept the element to search for
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("Element " + target + " found at position: " + result);
} else {
System.out.println("Search element not found.");
}
}
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Calculate the middle index
if (arr[mid] == target) {
return mid; // Return the index if found
}
if (arr[mid] < target) {
left = mid + 1;
} else { // If the target is smaller, ignore the right half
right = mid - 1;
}
}
return -1; // Return -1 if the target is not found
}
}

For the input:


The output will be:
Enter the element to search for:
Element 15 found at position: 4
15

Variable Description:
Variable Data
Description
Name Type
A predefined array of sorted integers for binary
arr int[]
search.
The element that the user wants to search for in the
target int
array.
result int The index of the found element (or -1 if not found).
sc Scanner An object used to read user input from the console.
Variable Data
Description
Name Type
left int The starting index of the current search range.
right int The ending index of the current search range.
mid int The middle index of the current search range.

14. Define a class named FruitJuice with the following description:instance


variables/Data Membersint product_code: stores the product code number
String flavour: stores the flavour of the juice (e.g., orange, apple, etc.)
String pack_type: stores the type of packaging (e.g., tera-pack, PET bottle,
etc.)int pack_size: stores package size (e.g., 200 mL, 400 mL, etc.)int
product_price: stores the price of the product
Member Methods, Purpose
FruitJuice(): constructor to initialize integer data members to 0 and string data
members to " "void input (): to input and store the product code, flavour, pack
type, pack size and product pricevoid discount (): to reduce the product price by
10
void display (): to display the product code, flavour, pack type, pack size and
product price.

import java.util.Scanner;
class FruitJuice {
int product_code;
String flavour;
String pack_type;
int pack_size;
int product_price;
public FruitJuice()
this.product_code = 0;
this.flavour = " ";
this.pack_type = " ";
this.pack_size = 0;
this.product_price = 0;
}
// Method to input and store the product details
public void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter product code: ");
product_code = sc.nextInt();
sc.nextLine();
System.out.print("Enter flavour of the juice: ");
flavour = sc.nextLine();
System.out.print("Enter pack type: ");
pack_type = sc.nextLine();
System.out.print("Enter pack size (in mL): ");
pack_size = sc.nextInt();
System.out.print("Enter product price: ");
product_price = sc.nextInt();
}
public void discount() {
product_price -= 10;
}
public void display() {
System.out.println("Product Code: " + product_code);
System.out.println("Flavour: " + flavour);
System.out.println("Pack Type: " + pack_type);
System.out.println("Pack Size: " + pack_size + " mL");
System.out.println("Product Price: " + product_price);
}
public static void main(String[] args) {
FruitJuice juice = new FruitJuice();
juice.input();
juice.discount();
juice.display();
}
}

For the input: The output will be:


Enter product code: 101 Product Code: 101
Enter flavour of the juice: Orange Flavour: Orange
Enter pack type: Tetra-Pack Pack Type: Tetra-Pack
Enter pack size (in mL): 200 Pack Size: 200 mL
Enter product price: 50 Product Price: 40

3. Define a class to overload the function print as follows:void print() - to print


the following format
1111
2222
3333
4444
5555
void print(int n) - To check whether the number is a lead number. A lead number
is the one whose sum of even digits are equal to sum of odd digits.e.g. 3669odd
digits sum = 3 + 9 = 12even digits sum = 6 + 6 = 12
3669 is a lead number.

class PrintOverloading {
void print() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 4; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
void print(int n) {
int oddSum = 0;
int evenSum = 0;
int originalNumber = n;
while (n > 0) {
int digit = n % 10; // Extract the last digit
if (digit % 2 == 0) {
evenSum += digit; // Sum of even digits
} else {
oddSum += digit; // Sum of odd digits
}
n /= 10; // Remove the last digit
}
if (oddSum == evenSum) {
System.out.println(originalNumber + " is a lead number.");
} else {
System.out.println(originalNumber + " is not a lead number.");
}
}

public static void main(String[] args) {


PrintOverloading po = new PrintOverloading();
po.print();

Output: int numberToCheck = 3669;

1111 po.print(numberToCheck);

2222 }}

3333
4444
5555
3669 is a lead number.
Variable Description:
Variable Name Data Type Description
oddSum int Stores the sum of odd digits of the number.
evenSum int Stores the sum of even digits of the number.
Holds the last digit extracted from the
digit int
number during iteration.
Stores the original value of the input number
originalNumber int
for display.
The number passed to check if it is a lead
n int
number.
An instance of the PrintOverloading class
po PrintOverloading
used to call the methods.
Bibliography :

You might also like