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

Java Programs for Class 10 ICSE

The document contains six Java programs that demonstrate various programming concepts. Program 1 checks if a number is a spy number, Program 2 sorts an array of words using selection sort, Program 3 finds the largest and smallest numbers in an array and calculates their sum, Program 4 overloads a function to count character frequency and display vowels, Program 5 implements a menu-driven program for series calculations, and Program 6 calculates an electric bill based on consumption. Each program includes user input and output functionalities.
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 views7 pages

Java Programs for Class 10 ICSE

The document contains six Java programs that demonstrate various programming concepts. Program 1 checks if a number is a spy number, Program 2 sorts an array of words using selection sort, Program 3 finds the largest and smallest numbers in an array and calculates their sum, Program 4 overloads a function to count character frequency and display vowels, Program 5 implements a menu-driven program for series calculations, and Program 6 calculates an electric bill based on consumption. Each program includes user input and output functionalities.
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

Program 1

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 * 1 * 2 * 4 = 8

import [Link];

class SpyNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number:");
int n = [Link]();
int m = n;
int sum=0, prod=1;
while(n>0){
int r = n % 10;
sum = sum + r;
prod = prod * r;
n = n / 10;
}
if(sum == prod){
[Link](m+" is a spy number");
}
else{
[Link](m+" is not a spy number");
}
}
}

Program 2
Write a program to input forty words in an array. Arrange these words in descending order of
alphabets, using selection sort technique. Print the sorted array.
import [Link];

public class SelectionSort{


public static void main(String args[]) {
Scanner in = new Scanner([Link]);
String names[] = new String[40];
int n = [Link];

[Link]("Enter 40 Names: ");


for (int i = 0; i < n; i++) {
names[i] = [Link]();
}

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


int max = i;
for (int j = i + 1; j < n; j++) {
if (names[j].compareTo(names[max]) < 0) {
max = j;
}
}
String t = names[max];
names[max] = names[i];
names[i] = t;
}

[Link]("Sorted Names");
for (int i = 0; i < n; i++) {
[Link](names[i]);
}
}
}

Program 3
Write a program to input integer elements into an array of size 20 and perform the following
operations:
(i) Display largest number from the array.
(ii) Display smallest number from the array.
(iii) Display sum of all the elements of the array.

import [Link];

public class LargestSmallestSum{


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);

int a[] = new int[20];


int n = [Link];

[Link]("Enter 20 integers:");
for(int i=0; i<n; i++){
a[i] = [Link]();
}

int sum=0, min=a[0], max=a[0];

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


if(a[i]<min){
min = a[i];
}
if(a[i]>max){
max = a[i];
}
sum = sum + a[i];
}

[Link]("Largest = "+max);
[Link]("Smallest = "+min);
[Link]("Sum = "+sum);
}
}

Program 4
Design a class to overload a function check( ) as follows:
(i) void check (String str , char ch ) - to find and print the frequency of a character in a
string.
Example : Input: str = "success" ch = 's'
Output: number of s present is =3
(ii) void check(String s1) - to display only vowels from string s1, after converting it to
lower case.
Example : Input: s1 ="computer"
Output : o u e

class Overload{
public void check(String str, char ch){
int n = 0;
for(int i=0; i<[Link](); i++){
if([Link](i) == ch){
n++;
}
}
[Link]("Number of "+ch+
" present is = "+n);
}
public void check(String s1){
s1 = [Link]();
for(int i=0; i<[Link](); i++){
char c = [Link](i);
if(c=='a' || c=='e' || c=='i' ||
c=='o' || c=='u'){
[Link](c+" ");
}
}
}

public static void main(String args[]){


Overload ob = new Overload();
[Link]("success", 's');
[Link]("computer");
}
}
Program 5
Using switch statement, write a menu driven program for the following:
(i) To find and display the sum of the series given below:
𝑆 = 𝑥1 − 𝑥2 + 𝑥3 − 𝑥4 + 𝑥5 … − 𝑥20 (where x = 2)
(ii) To display the following series:
1 11 111 1111 11111
For an incorrect option, an appropriate error message should be displayed.

import [Link];

class SwitchDemo{
public static void main(String args[]){
Scanner sc = new Scanner([Link]);

[Link]("1. Sum of series\n"+


"2. Display series\n"+
"Enter your choice (1-2):");
int ch = [Link]();

switch(ch){
case 1:
double sum=0, x=2;
for(int i=1; i<=3; i++){
sum = sum + [Link](-1, i+1)*[Link](x, i);
}
[Link]("Sum = "+sum);
break;
case 2:
for(int i=1; i<=5; i++){
for(int j=1; j<=i; j++){
[Link]("1");
}
[Link](" ");
}
break;
default:
[Link]("Invalid choice:"+ch);
}
}
}

Program 6
Define a class ElectricBill with the following specifications:
class : ElectricBill
Instance variables / data member:
String n – to store the name of the customer
int units – to store the number of units consumed
double bill – to store the amount to be paid
Member methods:
void accept( ) – to accept the name of the customer and number of units consumed
void calculate( ) – to calculate the bill as per the following tariff:
Number of units Rate per unit
First 100 units Rs.2.00
Next 200 units Rs.3.00
Above 300 units Rs.5.00
A surcharge of 2.5% charged if the number of units consumed is above 300 units.
void print ( ) - To print the details as follows:
Name of the customer: ………………………
Number of units consumed: ………………………
Bill amount: ………………………
Write a main method to create an object of the class and call the above member methods.

import [Link];

class ElectricBill{
private String n;
private int units;
private double bill;

public void accept() {


Scanner in = new Scanner([Link]);
[Link]("Enter customer name: ");
n = [Link]();
[Link]("Enter units consumed: ");
units = [Link]();
}

public void calculate() {


if (units <= 100)
bill = units * 2;
else if (units <= 300)
bill = 200 + (units - 100) * 3;
else {
double amt = 200 + 600 + (units - 300) * 5;
double surcharge = (amt * 2.5) / 100.0;
bill = amt + surcharge;
}
}

public void print() {


[Link]("Name of the customer:" + n);
[Link]("Number of units consumed: " + units);
[Link]("Bill amount:" + bill);
}

public static void main(String args[]) {


ElectricBill ob = new ElectricBill();
[Link]();
[Link]();
[Link]();
}
}

Common questions

Powered by AI

The programs utilize Java features like Scanner class for user input, allowing interactive communication. This class makes input processing efficient by providing methods to manipulate data types directly, thus simplifying user interaction. The use of classes encapsulates behavior and state, promoting object-oriented design principles. Additionally, method overloading facilitates program functionality by reusing method names for similar operations with different signature parameters, enhancing code legibility and maintainability. Java's robust error handling ensures graceful exits from potentially incorrect input, enhancing user experience through meaningful feedback .

The ElectricBill program calculates billing rates based on predefined usage thresholds with different costs per unit: Rs.2.00 for the first 100 units, Rs.3.00 for the next 200 units, and Rs.5.00 for units above 300, plus a surcharge if applicable. This tiered approach reflects real-world billing scenarios but requires careful handling to ensure computational accuracy. Potential pitfalls include ensuring correct boundary condition handling, correctly applying surcharges, and accommodating future tariff adjustments without necessitating major code changes. The use of straightforward conditional logic ensures clarity, although it can become cumbersome if tariffs become more complex .

The iterative process for determining the smallest, largest, and sum of elements in an array is effective for arrays of moderate size due to its linear time complexity, O(n). By traversing the array a single time, these values can be computed efficiently with minimal additional space, making it practical for many common applications such as data analytics or simple statistics computations. However, for very large datasets, this approach could become less efficient, particularly if repeated often, and more sophisticated algorithms or parallel processing might be required to optimize performance .

The ElectricBill class illustrates encapsulation by using private instance variables to hide details from outside interference, ensuring interaction only through defined public methods. It demonstrates modularity by organizing the acceptance of input, calculation of bill based on a defined tariff, and printing of output into separate, manageable methods. This separation of concerns aids in simplifying debugging and allows for easy updates to individual components (like tariff changes) without affecting other parts of the class. The use of encapsulation and modularity enhances the robustness and maintainability of the program .

String processing operations, such as frequency counting or extracting specific characters, can introduce significant computational overhead, especially with large strings. Each operation, such as iterating over the string to count characters, runs in O(n) time complexity, where n is the string's length. If additional operations like converting to lowercase are involved, this can double the time complexity per operation. Frequent memory allocation, like during string manipulation or creation of new substrings, further increases overhead. Efficient coding, such as minimizing operations and using optimal data structures for storage and computation, can help mitigate these overheads .

Method overloading allows similar operations to be abstracted in a single class with different parameter lists, which enhances code readability and organization. For example, one method can be used to find a character's frequency and another to extract vowels from a string, based on the input parameters. This reduces redundancy and makes the class easier to maintain. However, it can lead to confusion if too many overloaded methods are used with only slight differences in their signatures, potentially increasing the complexity of understanding which method is invoked for a given call .

Selection sort is not efficient for large lists as it runs in O(n^2) time complexity, making it slower than other sorting algorithms like quicksort or mergesort. The technique repeatedly selects the smallest (or largest, depending on sorting order) element from the unsorted sublist and swaps it with the first unsorted element. The program minimizes additional space usage by sorting in-place, and despite its inefficiency for larger datasets, its simplicity makes it useful for smaller lists or when resource constraints are minimal .

Switch statements provide a clear and efficient way to handle a fixed number of distinct choices, such as menu options. They enhance readability by clearly delineating each case and are typically faster than a series of if-else statements when the number of potential choices is large. For a menu-driven program where users select options to execute specific tasks, such as summing a series or displaying preformatted patterns, the use of switch statements allows the program to quickly branch to the defined operations without unnecessary evaluations. This approach is well-suited to handling multiple, mutually exclusive options with simplicity .

Calculating the sum of alternating powers of a number involves both computational complexity and numeric challenges. The alternating series requires signs to be adjusted based on position, which introduces the need for modulus or conditional calculations. Additionally, computing powers iteratively imposes an O(n) complexity, each requiring additional computational resources as n grows. In the given problem, managing large values of powers can lead to overflow or precision issues, depending on the range of x and the computational capabilities of the program's operational environment .

A spy number is defined as a number where the sum of its digits equals the product of its digits. This concept tests a program's ability to perform arithmetic operations by summing and multiplying digits, and logical operations by comparing the results of these two calculations to determine equality. Through an iterative process, each digit is extracted using modulo and division operations, accumulated for the sum, and multiplied for the product. The logical comparison then evaluates the success of the arithmetic operations to verify the condition of a spy number .

You might also like