[go: up one dir, main page]

0% found this document useful (0 votes)
38 views29 pages

Self Profile

The document contains a self-profile of a student named Delisha Dutta, including her class, roll number, and subject. It outlines multiple programming assignments, including a cashback calculator, a menu-driven program for displaying patterns and calculating series, and a program for calculating areas of different shapes using function overloading. Additionally, it describes a salary calculation program that computes various salary components for an employee.

Uploaded by

duttadelisha09
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)
38 views29 pages

Self Profile

The document contains a self-profile of a student named Delisha Dutta, including her class, roll number, and subject. It outlines multiple programming assignments, including a cashback calculator, a menu-driven program for displaying patterns and calculating series, and a program for calculating areas of different shapes using function overloading. Additionally, it describes a salary calculation program that computes various salary components for an employee.

Uploaded by

duttadelisha09
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/ 29

SELF

PROFILE
NAME: DELISHA DUTTA
CLASS: X. SCIENCE
ROLL NO: 08
SUBJECT:
COMPUTER
APPLICATIONS
1
INDEX
SL NO. TITLE PAGE

1. PROGRAM 1
2. PROGRAM 2
3. PROGRAM 3
4. PROGRAM 4
5. PROGRAM 5
6. PROGRAM 6
7. PROGRAM 7
8. PROGRAM 8
9. PROGRAM 9

2
10. PROGRAM 10

PROGRAM 1:

PROGRAM DEFINITION:

Define a class named Customer with the following description:


Instance variables /Data members:
String cardName — Name of the card holder.
long cardNo — Card Number.
char cardType — Type of card, 'P' for Platinum, 'G' for Gold, 'S' for Silver.
double purchaseAmount — The amount of purchase done on card.
double cashback — The amount of cashback received.
Member methods: Customer(String name, long num, char type, double amt) —
Parameterised constructor to initialize all data members.
void compute() — To compute the cashback based on purchase amount as
follows:
For Silver ('S'), 2% of purchase amount
For Gold ('G'), 5% of purchase amount
For Platinum ('P'), 8% of purchase amount
void display() — To display the details in the below format:
Card Holder Name:
Card Number:
Purchase Amount:
Cashback:
Write a main method to input the card details from the user then create object of
the class and call the member methods with the provided details.

ALGORITHM:

1. Start.
2. Display "Welcome to the Cashback Calculator"
3. Input the cardName (Card Holder's Name)
4. Input the cardNo (Card Number)
5. Input the cardType (P/G/S)
6. Input the purchaseAmount
7. Create an object of the Customer class using the inputs
8. Call the compute() method:
If cardType is 'S' or 's',
cashback = 2% of purchaseAmount

3
If cardType is 'G' or 'g',
cashback = 5% of purchaseAmount
If cardType is 'P' or 'p',
cashback = 8% of purchaseAmount
Else,
cashback = -1 (invalid type)
9. Call the display() method:
Print Card Holder Name, Card Number, and Purchase Amount
If cashback is -1,
Print "Invalid card type entered"
Else,
Print Cashback Earned
1O. End

PROGRAM CODE:

import java.util.*;
class Customer
{
String cardName;
long cardNo;
char cardType;
double purchaseAmount;
double cashback;
// Constructor
void Customer(String name, long num, char type, double amt)
{
cardName = name;
cardNo = num;
cardType = Character.toUpperCase(type); // convert to uppercase for consistency
purchaseAmount = amt;
cashback = 0;
}
// Compute cashback
void compute()
{
switch (cardType)
{
case 'S':
cashback = 2.0 * purchaseAmount / 100.0;
break;
case 'G':
cashback = 5.0 * purchaseAmount / 100.0;
break;
case 'P':
cashback = 8.0 * purchaseAmount / 100.0;

4
break;
default:
cashback = -1; // invalid
}
}
// Display details
void display()
{
System.out.println("\n--- CUSTOMER TRANSACTION DETAILS ---");
System.out.println("Card Holder Name: " + cardName);
System.out.println("Card Number: " + cardNo);
System.out.println("Purchase Amount: ₹" + purchaseAmount);
if (cashback == -1)
{
System.out.println("Invalid card type entered. No cashback calculated.");
}
else
{
System.out.println("Cashback Earned : ₹" + cashback);
}
}
// Main method
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the Cashback Calculator\n");
System.out.print("Enter Card Holder Name: ");
String n = in.nextLine();
System.out.print("Enter Card Number: ");
long no = in.nextLong();
System.out.print("Enter Card Type (P - Platinum, G - Gold, S - Silver): ");
char t = in.next().charAt(0);
System.out.print("Enter Purchase Amount: ₹");
double a = in.nextDouble();
Customer obj = new Customer(n, no, t, a);
obj.compute();
obj.display();
}
}

5
VARIABLE TYPE PURPOSE SCOPE
NAME
cardName String To store the name of the Class-level
cardholder (instance
variable)
cardNo long To store the credit/debit card Class-level
number (instance
variable)
cardType char To store the type of the card Class-level
('S', 'G', 'P') (instance
variable)
purchaseAmoun double To store the total purchase Class-level
t amount made by the (instance
customer variable)
cashback double To store the calculated Class-level
cashback based on the card (instance
type variable)
n String To temporarily store the user Local variable in
input for card holder name main()
no long To temporarily store the user Local variable in
input for card number main()
t char To temporarily store the user Local variable in
input for card type main()
a double To temporarily store the user Local variable in
input for purchase amount main()
obj Customer To create an object of the Local variable in
class main()
in Scanner To read user inputs from the Local variable in
keyboard main()

METHOD RETURN PARAMETER PURPOSE


NAME TYPE
Customer Constructor String name, long Initializes the object with
num, char type, cardholder name, card number,
double amt card type, and purchase amount
compute void - Calculates cashback based on
the card type
display void - Displays the customer details

6
main static void - Takes input from the user,
creates a Customer object,
computes cashback, and
displays the details.

PROGRAM 2:

PROGRAM DEFINITION:

Using switch-case statement write a menu driven program for the following:
1. To display the pattern given below:
A
BC
DEF
GHIJ
KLMNO
2. To display the sum of the series given below:
1/1! + 3/3! + 5/5! + ..... + n/n!

ALGORITHM:

1. Start
2. Display Menu:
"1. Display Alphabet Pattern"
"2. Calculate Series (1/1! + 3/3! + 5/5! + ...)"
Prompt user to enter their choice
3. Input choice
4. Switch based on the value of choice:
Case 1 – Display Alphabet Pattern
5. Initialize ch = 'A'
6. Repeat for i = 1 to 5:
Repeat for j = 1 to i:
Print character ch followed by a space
Increment ch to next alphabet
Print a newline
7. End Case 1
Case 2 – Calculate Series
8. Prompt user to enter an odd number n
9. Input n
10. Initialize sum = 0
11. Repeat for i = 1 to n in steps of 2 (i.e., 1, 3, 5, ...):
 Initialize fact = 1
 Calculate factorial of i:
Repeat for j = 1 to i:
fact = fact * j

7
 Add i / fact to sum
12. Display "Sum of the series = " followed by sum
13. End Case 2
Default Case
14. If choice is neither 1 nor 2:
 Display "Invalid choice. Please select 1 or 2."
15.Close input scanner
16.End

PROGRAM CODE:

import java.util.*;
class MenuProgram {
public static void main() {
Scanner in = new Scanner(System.in);

System.out.println("1. Display Alphabet Pattern");


System.out.println("2. Calculate Series (1/1! + 3/3! + 5/5! + ...)");
System.out.print("Enter your choice (1 or 2): ");
int choice = in.nextInt();
switch (choice) {
case 1:
char ch = 'A';
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(ch + " ");
ch++;
}
System.out.println();
}
break;
case 2:
System.out.print("Enter an odd number n: ");
int n = in.nextInt();
double sum = 0;
for (int i = 1; i <= n; i += 2) {
double fact = 1;
for (int j = 1; j <= i; j++) {
fact *= j;
}
sum += i / fact;
}
System.out.println("Sum of the series = " + sum);
break;
default:
System.out.println("Invalid choice. Please select 1 or 2.");

8
}
}
}

VARIABL TYPE PURPOSE SCOPE


E NAME
In Scanner To read user input from the Local variable
console
Choice int Stores the user’s menu choice Local variable
Ch char Stores and prints alphabets Local variable
starting from 'A'
I int Loop counter for rows and Local variable
series iteration
J int Loop counter for columns and Local variable
factorial calculation
N int User input for the odd number Local variable
till which series is calculated
Sum double Accumulates the sum of the Local variable
series
Fact double Stores factorial value for each Local variable
term in the series

PROGRAM 3:

PROGRAM DEFINITION:

Write a class with the name Area using function overloading that computes the
area of a parallelogram, a rhombus and a trapezium.
Formula: Area of a parallelogram (pg) = base * ht
Area of a rhombus (rh) = (1/2) * d1 * d2 (where, d1 and d2 are the diagonals)
Area of a trapezium (tr) = (1/2) * ( a + b) * h (where a and b are the parallel sides, h
is the perpendicular distance between the parallel sides)
Write a main method to create an object and invoke the above methods.

ALGORITHM:

1. Start
2. Create an object of class Area
Parallelogram Area Calculation
3. Input base of the parallelogram → base
4. Input height of the parallelogram → height

9
5. Calculate area of parallelogram
→ area = base × height
6. Display the area of the parallelogram
Rhombus Area Calculation
7. Input first diagonal of the rhombus → d1
8. Input second diagonal of the rhombus → d2
9. Calculate area of rhombus
→ area = 0.5 × d1 × d2
10. Display the area of the rhombus
Trapezium Area Calculation
11. Input first parallel side of the trapezium → a
12. Input second parallel side of the trapezium → b
13. Input height of the trapezium → h
14. Calculate area of trapezium
→ area = 0.5 × (a + b) × h
15. Display the area of the trapezium
16. Close the input scanner
17. End

PROGRAM CODE:

import java.util.*;
class Area {
// Area of parallelogram: base * height
double areaParallelogram(double base, double height) {
return base * height;
}
// Area of rhombus: 0.5 * d1 * d2
double areaRhombus(double d1, double d2) {
return 0.5 * d1 * d2;
}
// Area of trapezium: 0.5 * (a + b) * h
double areaTrapezium(double a, double b, double height) {
return 0.5 * (a + b) * height;
}
public static void main() {
Scanner in = new Scanner(System.in);
Area obj = new Area();
// Parallelogram
System.out.print("Enter base of parallelogram: ");
double base = in.nextDouble();
System.out.print("Enter height of parallelogram: ");
double height = in.nextDouble();
System.out.println("Area of Parallelogram = " + obj.areaParallelogram(base,
height));

10
// Rhombus
System.out.print("\nEnter first diagonal of rhombus: ");
double d1 = in.nextDouble();
System.out.print("Enter second diagonal of rhombus: ");
double d2 = in.nextDouble();
System.out.println("Area of Rhombus = " + obj.areaRhombus(d1, d2));
// Trapezium
System.out.print("\nEnter first parallel side of trapezium: ");
double a = in.nextDouble();
System.out.print("Enter second parallel side of trapezium: ");
double b = in.nextDouble();
System.out.print("Enter height of trapezium: ");
double h = in.nextDouble();
System.out.println("Area of Trapezium = " + obj.areaTrapezium(a, b, h));
}
}

VARIABLE NAME TYPE PURPOSE SCOPE


In Scanner To take user input from the Local variable
console
Obj Area Object of class Area to call Local variable
instance methods
Base double Stores base length of the Local variable
parallelogram
Height double Stores height of the Local variable
parallelogram
d1 double Stores first diagonal of the Local variable
rhombus
d2 double Stores second diagonal of Local variable
the rhombus
A double Stores first parallel side of Local variable
the trapezium
B double Stores second parallel side Local variable
of the trapezium
H double Stores height of the Local variable
trapezium

METHOD RETUR PARAMETER PURPOSE


N TYPE
areaParallelogram double double base, Calculates and returns area
double height of a parallelogram using
formula
areaRhombus double double d1, double Calculates and returns area

11
d2 of a rhombus using formula
areaTrapezium double double a, double b, Calculates and returns area
double height of a trapezium using
formula
Main static - Takes input from user, calls
void above methods to compute
and display areas

PROGRAM 4:

PROGRAM DEFINITION:

Define a class named Pay with the following description:


Instance variables /Data members:
String name — To store the name of the employee
double salary — To store the salary of the employee
double da — To store Dearness Allowance
double hra — To store House Rent Allowance
double pf — To store Provident Fund
double grossSal — To store Gross Salary
double netSal — To store Net Salary
Member methods: Pay(String n, double s) — Parameterized constructor to
initialize the data members.
void calculate() — To calculate the following salary components:
Dearness Allowance = 15% of salary
House Rent Allowance = 10% of salary
Provident Fund = 12% of salary
Gross Salary = Salary + Dearness Allowance + House Rent Allowance
Net Salary = Gross Salary - Provident Fund
void display() — To display the employee name, salary and all salary
components.
Write a main method to create object of the class and call the member methods.

ALGORITHM:
1. Start
2. Input the employee's name → name
3. Input the employee's basic salary → salary
4. Create an object of the Pay class using name and salary
5. Initialize da, hra, pf, grossSal, and netSal to 0
Salary Calculation

12
6. Calculate Dearness Allowance (DA):
→ da = 15% of salary
→ da = salary × 15 / 100
7. Calculate House Rent Allowance (HRA):
→ hra = 10% of salary
→ hra = salary × 10 / 100
8. Calculate Provident Fund (PF):
→ pf = 12% of salary
→ pf = salary × 12 / 100
9. Calculate Gross Salary:
→ grossSal = salary + da + hra
10. Calculate Net Salary:
→ netSal = grossSal - pf
Display Output
11. Display employee name
12. Display basic salary
13. Display DA, HRA, PF
14. Display Gross Salary and Net Salary
15. End

PROGRAM CODE:

import java.util.*;
class Pay
{
String name;
double salary;
double da;
double hra;
double pf;
double grossSal;
double netSal;
void Pay(String n, double s) {
name = n;
salary = s;
da = 0;
hra = 0;
pf = 0;
grossSal = 0;
netSal = 0;
}
void calculate() {
da = salary * 15.0 / 100;
hra = salary * 10.0 / 100;
pf = salary * 12.0 / 100;
grossSal = salary + da + hra;

13
netSal = grossSal - pf;
}
void display() {
System.out.println("Employee Name: " + name);
System.out.println("Salary: " + salary);
System.out.println("Dearness Allowance: " + da);
System.out.println("House Rent Allowance: " + hra);
System.out.println("Provident Fund: " + pf);
System.out.println("Gross Salary: " + grossSal);
System.out.println("Net Salary: " + netSal);
}
public static void main() {
Scanner in = new Scanner(System.in);
System.out.print("Enter Employee Name: ");
String empName = in.nextLine();
System.out.print("Enter Salary: ");
double empSal = in.nextDouble();
Pay obj = new Pay(empName, empSal);
obj.calculate();
obj.display();
}
}

VARIABLE TYPE PURPOSE SCOPE


NAME
name String Stores the employee’s name Instance variable
salary double Stores the employee’s basic Instance variable
salary
da double Dearness Allowance Instance variable
hra double House Rent Allowance Instance variable
pf double Provident Fund deduction Instance variable
grossSal double Gross salary = salary + da + Instance variable
hra
netSal double Net salary = gross salary - pf Instance variable
in Scanner To take user input Local variable
empName String Temporarily stores employee Local variable
name input
empSal double Temporarily stores employee Local variable
salary input
obj Pay Object of Pay class to access Local variable
instance methods

14
METHO RETURN PARAMETERS PURPOSE
D TYPE
Pay Constructor String n, double s Initializes the employee name and
salary; sets other variables
calculate void - Calculates da, hra, pf, gross
salary, and net salary
display void - Displays all details
main static void - Takes employee name and salary
as input, creates Pay object, calls
calculate() and display() methods

PROGRAM 5:

PROGRAM DEFINITION:

A Dudeney number is a positive integer that is a perfect cube such that the sum
of its digits is equal to the cube root of the number.
Write a program to input a number and check and print whether it is a Dudeney
number or not.
Example: Consider the number 512.
Sum of digits = 5 + 1 + 2 = 8
Cube root of 512 = 8
As Sum of digits = Cube root of Number
hence 512 is a Dudeney number.

ALGORITHM:

1. Start
2. Input a positive number → num
3. Calculate the cube root of num
→ cubeRoot = integer part of cube root of num
4. Check if cubeRoot³ == num
If not,
→ Display "Not a perfect cube, so not a Dudeney number"
→ End
5. Initialize sum = 0, temp = num
6. Repeat until temp > 0:
Extract last digit: digit = temp % 10
Add digit to sum

Update temp = temp / 10


7. Compare sum with cubeRoot

15
If sum == cubeRoot,
→ Display "num is a Dudeney number"
Else,
→ Display "num is not a Dudeney number"
8. End

PROGRAM CODE:

import java.util.*;
public class DudeneyNumber {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive number: ");
int num = sc.nextInt();
int cubeRoot = (int) Math.cbrt(num);
if (cubeRoot * cubeRoot * cubeRoot != num) {
System.out.println("Not a perfect cube, so not a Dudeney number.");
} else {
int sum = 0, temp = num;
while (temp > 0) {
sum += temp % 10;
temp /= 10;
}
if (sum == cubeRoot) {
System.out.println(num + " is a Dudeney number!");
} else {
System.out.println(num + " is not a Dudeney number.");
}
}
}
}

VARIABLE TYPE PURPOSE SCOPE


NAME
sc Scanner To take input from the Inside main()
user
num int Stores the number input Inside main()
by the user
cubeRoot int Stores the cube root of Inside main()
the number
sum int Stores the sum of digits Inside main()
of the number
temp int Temporary variable used Inside main()
to extract digits of num

16
PROGRAM 6:

PROGRAM DEFINITION:

Design a class to overload a method Number() as follows:


(i) void Number(int num, int d) — To count and display the frequency of a digit in
a number. Example:
num = 2565685
d=5
Frequency of digit 5 = 3
(ii) void Number(int n1) — To find and display the sum of even digits of a number.
Example:
n1 = 29865
Sum of even digits = 2 + 8 + 6 = 16
Write a main method to create an object and invoke the above methods.

ALGORITHM:

1. Start
2. Take input num (the number to be searched) and d (the digit to count).
3. Initialize a counter f = 0.
4. Repeat while num is not equal to 0:
Extract the last digit using num % 10 and store in x.
If x == d, increment f by 1.
Remove the last digit using num = num / 10.
5. After the loop ends, print f (the frequency of digit d).
6. End

PROGRAM CODE:

class Overload
{
void Number(int num, int d) {
int f = 0;

17
while (num != 0) {
int x = num % 10;
if (x == d) {
f++;
}
num /= 10;
}
System.out.println("Frequency of digit " + d + " = " + f);
}
void Number(int n1) {
int s = 0;
while (n1 != 0) {
int x = n1 % 10;
if (x % 2 == 0) {
s = s + x;
}
n1 /= 10;
}
System.out.println("Sum of even digits = " + s);
}
public static void main() {
Overload obj = new Overload();
obj.Number(2565685, 5);
obj.Number(29865);
}
}

VARIABLE TYPE PURPOSE SCOPE


NAME
num int Stores the number whose Parameter of Number(int
digit frequency is to be num, int d)
checked
d int Digit whose frequency in Parameter of Number(int
num is to be counted num, int d)
f int Counter to count the Inside Number(int num,
frequency of digit d int d)
x int To extract each digit from Inside both Number()
the number methods
n1 int Stores the number whose Parameter of Number(int
even digits are to be n1)
summed
s int To store the sum of even Inside Number(int n1)
digits
obj Overload Object to call overloaded Inside main()
methods

18
METHOD RETURN TYPE PARAMETER PURPOSE
Number(int void int num, int d Counts and displays how
num, int d) many times digit d appears in
num
Number(int n1) void int n1 Calculates and displays the
sum of even digits in the
number n1
main() void - Creates an object of Overload
class and calls both
overloaded Number methods

PROGRAM 7:

PROGRAM DEFINITION:

Design a class overloading a function calculate() as follows: 1. void calculate(int


m, char ch) with one integer argument and one character argument. It checks
whether the integer argument is divisible by 7 or not, if ch is 's', otherwise, it
checks whether the last digit of the integer argument is 7 or not. 2. void
calculate(int a, int b, char ch) with two integer arguments and one character
argument. It displays the greater of integer arguments if ch is 'g' otherwise, it
displays the smaller of integer arguments.

ALGORITHM:

1. Start
2. Create a Scanner object to take input from the user.
3. Create an object of the class Calculate.
4. Prompt the user:
"Enter a number:"
Store the input in variable n1.
5. Call the method calculate(n1, 's'):
Check if n1 is divisible by 7.
If yes, print: "It is divisible by 7"
Else, print: "It is not divisible by 7"
6. Call the method calculate(n1, 't'):
Check if the last digit of n1 is 7 (i.e., n1 % 10 == 7).
If yes, print: "Last digit is 7"
Else, print: "Last digit is not 7"

19
7. Prompt the user:
"Enter first number:"
Store input in n1
"Enter second number:"
Store input in n2
8. Call the method calculate(n1, n2, 'g'):
If 'g', print the greater of the two numbers.
9. Call the method calculate(n1, n2, 'k'):
If not 'g', treat it as 'k' and print the smaller of the two numbers.
10. End

PROGRAM CODE:

import java.util.*;
class Calculate
{
void calculate(int m, char ch) {
if (ch == 's') {
if (m % 7 == 0)
System.out.println("It is divisible by 7");
else
System.out.println("It is not divisible by 7");
}
else {
if (m % 10 == 7)
System.out.println("Last digit is 7");
else
System.out.println("Last digit is not 7");
}
}
void calculate(int a, int b, char ch) {
if (ch == 'g')
System.out.println(a > b ? a : b);
else
System.out.println(a < b ? a : b);
}
public static void main() {
Scanner in = new Scanner(System.in);
Calculate obj = new Calculate();
System.out.print("Enter a number: ");
int n1 = in.nextInt();
obj.calculate(n1, 's');
obj.calculate(n1, 't');

System.out.print("Enter first number: ");


n1 = in.nextInt();

20
System.out.print("Enter second number: ");
int n2 = in.nextInt();
obj.calculate(n1, n2, 'g');
obj.calculate(n1, n2, 'k');
}
}

VARIABLE TYPE PURPOSE SCOPE


NAME
n1 Int Local Stores the number input by the user
n2 Int Local Stores the second number for
comparison
ch Char Parameter Determines which condition to
evaluate
obj Calculate Local Object to invoke non-static methods
in Scanner Local Used for input from user

METHOD RETURN TYPE DESCRIPTION


void calculate(int m, char ch) void Checks divisibility by 7 or if
last digit is 7 based on ch.
void calculate(int a, int b, char void Prints greater or smaller of
ch) two numbers
public static void main() void Entry point of program;
performs method calls using
user input.

PROGRAM 8:

PROGRAM DEFINITION:

Write a program by using a class with the following specifications:


Class name — Hcflcm
Data members/instance variables: 1. int a 2. int b
Member functions:
1. Hcflcm(int x, int y) — constructor to initialize a=x and b=y.
2. void calculate( ) — to find and print hcf and lcm of both the numbers.

ALGORITHM:

21
1. Start
2. Input two integers x and y from the user.
3. Create an object obj of class Hcflcm using the inputs x and y.
4. Inside the constructor:
Store x in instance variable a.
Store y in instance variable b.
5. Call the method calculate() using the object.
6. Assign:
x=a
y=b
7. Find HCF using Euclidean Algorithm:
Repeat while y ≠ 0:
Store y in temporary variable t
Update y = x % y
Update x = t
8. After loop ends:
x holds the HCF
Store it in variable hcf
9. Calculate LCM using formula:
lcm = (a × b) / hcf
10. Display the results:
Print "HCF = " followed by the value of hcf
Print "LCM = " followed by the value of lcm
11. End

PROGRAM CODE:

import java.util.*;
class Hcflcm
{
private int a;
private int b;
public Hcflcm(int x, int y) {
a = x;
b = y;
}
void calculate() {
int x = a, y = b;
while (y != 0) {
int t = y;
y = x % y;
x = t;
}
int hcf = x;
int lcm = (a * b) / hcf;

22
System.out.println("HCF = " + hcf);
System.out.println("LCM = " + lcm);
}
public static void main() {
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
int x = in.nextInt();
System.out.print("Enter second number: ");
int y = in.nextInt();
Hcflcm obj = new Hcflcm(x,y);
obj.calculate();
}
}

VARIABLE NAME DATA TYPE PURPOSE


a int To store the first number
b int To store the second number
x int Temporary variable used for
HCF calculation
y int Temporary variable used for
HCF calculation
t int Temporary variable used in
swapping values
hcf int Stores the calculated Highest
Common Factor
lcm int Stores the calculated Least
Common Multiple

METHOD ACCESS RETURN TYPE DESCRIPTION


SIGNATURE
public Hcflcm(int public Constructor Initializes object with two
x, int y) integers a and b
void calculate() default void Calculates and prints HCF
and LCM of a and b
public static void public void Accepts input and calls
main() methods to perform
calculation

23
PROGRAM 9:

PROGRAM DEFINITION:

A class Sort contains an array of 50 integers. Some of the member functions/data


members are given below:
Class name : Sort
Data members
arr[ ] : integers
item : number to be searched for in the array
Member Functions/methods:
void inpdata( ) : to input 50 integers (no duplicate numbers are to be entered).
void bubsort( ) : to sort the array in ascending order using the bubble sort
technique and to display the sorted list.
void binsearch( ) : to input item and search for it using the binary search
technique; if found to print the item searched and its position in the sorted list,
otherwise to print an appropriate message.
Specify the class Sort giving the details of the functions void inpdata( ), void
bubsort( ) and void binsearch( ). Write main function to accomplish the above
tasks.

ALGORITHM:

1. Start
2. Declare the class Sort
Declare an integer array arr[50]
Declare an integer item to store the number to search
3. Function: inpdata()
Loop from i = 0 to 49
Repeat:
Ask the user to input a number
Check if that number already exists in arr[0] to arr[i-1]
If yes, ask for another number
If no, store it in arr[i]
4. Function: bubsort()
Use bubble sort to sort arr in ascending order:
Loop through the array using two nested loops:
Outer loop i from 0 to 48
Inner loop j from 0 to 48-i

24
If arr[j] > arr[j+1], swap them
After sorting, display the array
5. Function: binsearch()
Ask the user to input item (the number to search)
Set low = 0, high = 49
Use a while loop: while low <= high
Calculate mid = (low + high) / 2
If arr[mid] == item, print "Item found at position mid + 1", stop
Else if arr[mid] > item, set high = mid - 1
Else set low = mid + 1
If loop ends without finding, print "Item not found"
6. Main Function
Create an object of Sort
Call the functions:
inpdata()
bubsort()
binsearch()
7. End

PROGRAM CODE:

import java.util.*;
class Sort {
int[] arr = new int[50];
int item;
// Function to input 50 unique integers
void inpdata() {
Scanner in = new Scanner(System.in);
System.out.println("Enter 50 unique integers:");
for (int i = 0; i < 50; ) {
int num = in.nextInt();
boolean isDuplicate = false;
// Check for duplicates
for (int j = 0; j < i; j++) {
if (arr[j] == num) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
arr[i] = num;
i++;
} else {
System.out.println("Duplicate! Enter a different number:");
}
}

25
}
// Function to sort using bubble sort
void bubsort() {
for (int i = 0; i < 49; i++) {
for (int j = 0; j < 49 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display sorted array
System.out.println("Sorted Array:");
for (int i = 0; i < 50; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Function to search using binary search
void binsearch() {
Scanner in = new Scanner(System.in);
System.out.print("Enter item to search: ");
item = in.nextInt();
int low = 0;
int high = 49;
boolean found = false;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == item) {
System.out.println("Item " + item + " found at position " + (mid + 1));
found = true;
break;
} else if (item < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
if (!found) {
System.out.println("Item " + item + " not found in the list.");
}
}
// Main function
public static void main() {

26
Sort obj = new Sort();
obj.inpdata(); // input 50 integers
obj.bubsort(); // sort and display the list
obj.binsearch(); // search for a number
}
}

VARIABLE TYPE PURPOSE


arr int[] Array to store 50 unique integers
item int The number to be searched
num int Temporarily holds user input
isDuplicate boolean Flag to check if the entered number
already exists
i int Loop control variable
j int Loop control variable
temp int Used for swapping elements
low Int Lower bound
high Int Upper bound
mid Int Midpoint index
found boolean Flag to indicate whether the item was
found or not
in Scanner Scanner object to take user input
obj Sort Object of the Sort class

METHOD RETURN TYPE PARAMETERS PURPOSE


inpdata() Void - To input 50 unique integers
into the array
bubsort() Void - To sort the array using the
bubble sort technique
binsearch() Void - To search for an item in the
array using binary search
main() Void - To drive the program by
calling input, sort and search

27
PROGRAM 10:

PROGRAM DEFINITION:

Write a program to accept 20 integer numbers in a single Dimensional Array. Find


and Display the following:
i. Number of even numbers.
ii. Number of odd numbers.
iii. Number of multiples of 4.

ALGORITHM:

1. Start
2. Create an array a of size 20 to store 20 integers.
3. Initialize counters:
c1 for even numbers = 0
c2 for odd numbers = 0
c3 for multiples of 4 = 0
4. Prompt the user to enter 20 numbers.
5. Using a loop from i = 0 to i < 20, do:
Read number from user and store it in a[i]
6. Using another loop from i = 0 to i < 20, do:
If a[i] % 2 == 0, increment c1 by 1 (it's even)
If a[i] % 2 != 0, increment c2 by 1 (it's odd)
If a[i] % 4 == 0, increment c3 by 1 (it's a multiple of 4)
7. Print the values of c1, c2, and c3:
Total even numbers
Total odd numbers
Total multiples of 4
8. End

PROGRAM CODE:

import java.util.*;
class Numbers
{
public static void main()
{
Scanner in = new Scanner(System.in);
int i,j,c1=0,c2=0,c3=0;
int a[] = new int[20];

28
System.out.println("Enter 20 numbers");
for(i=0;i<20;i++)
{
a[i] = in.nextInt();
}
for( i=0;i<20;i++)
{
if(a[i]%2 == 0)
c1++;
if(a[i]%2 !=0)
c2++;
if(a[i]%4 ==0)
c3++;
}
System.out.println("Number of even numbers "+c1);
System.out.println("Number of odd numbers "+c2);
System.out.println("Number of multiple of 4 "+c3);
}
}

VARIABLE TYPE PURPOSE


in Scanner Scanner object used to take input
i Int Loop control variables used for iteration
j Int Loop control variables used for iteration
c1 Int Counter to count the number of even
numbers
c2 Int Counter to count the number of odd
numbers
c3 Int Counter to count the number of numbers
that are multiples of 4
a int[] Integer array of size 20 to store the
numbers

29

You might also like