Frank Computer Book ICSE - 621f7d0b C42a 4325 Ade8 f2cf517c7cdd
Frank Computer Book ICSE - 621f7d0b C42a 4325 Ade8 f2cf517c7cdd
Solution
(ICSE)
Chapter 1: Concept of Objects
Practice Questions
------------------------------>Objective-Type Questions<-----------------------------
A. Choose the correct answer:
1. An object is represented by two attributes, out of which one is characteristics and the other
one is ___________.
a) Behaviour b) Situation c) Abstraction d) Encapsulation
Ans. a) Behaviour
2. Name the programming technique that implements programs as an organized collection of
interactive objects.
a) Procedural Programming b) Modular Programming
c) Object-Oriented Programming d) None of these
Ans. c) Object-Oriented Programming
3. Name the characteristics of Object-Oriented Programming that hides the complexity and
provides a simple interface.
a) Encapsulation b) Polymorphism c) Abstraction d) Inheritance
Ans. c) Abstraction
4. What is the behaviour aspect of an object represented by?
a) Functions b) Data Members c) Both a and b d) None of these
Ans. a) Functions
5. What is the ability of an object to have many methods which functions differently but have the
same name?
a) Polymorphism b) Encapsulation c) Abstraction d) Inheritance
Ans. a) Polymorphism
6. Name the object-oriented technique that encompasses the parent class state and behaviours
into its child.
a) Polymorphism b) Encapsulation c) Abstraction d) Inheritance
Ans. d) Inheritance
7. Name the art of implementing encapsulation in Object-Oriented Programming.
a) Polymorphism b) Encapsulation c) Abstraction d) Class
Ans. d) class
8. What is meant by state of an object?
a) Functions of the object b) Data members of the object
c) Content of an object d) All of these
Ans. c) Content of an object
9. Name the term used to express the ability of objects to interact with each other.
a) Message Passing b) Instantiation c) Logical construct d) All of these
Ans. a) Message Passing
B. Fill in the blanks:
1. An object is an identity with certain characteristics and behaviour.
2. The values/attributes of the characteristics of an object are called the state of an object.
3. All the complexities of a program should be hidden in such a way that abstraction is obtained.
4. Class is a mechanism to implement encapsulation.
5. Objects interact with each other with the help of Message Passing.
6. A huge program divided into several individual segments is called functions/methods.
7. The objects methods/functions are said to access data.
8. A class is a logical construct and an object is a physical reality.
9. All objects have identity and are distinguishable even if the constituent components are same.
----------------------------->Subjective-Type Questions<-----------------------------
Answer the following questions:
1. Give two examples of real-world objects. Also specify their characteristics and
behaviour.
Ans. Real Life Objects
Example1:
Behaviour:
Example 2:
Behaviour:
1) Barking
2) Wagging its tail
3) Running speed
i) Abstraction
ii) Encapsulation
iii) Polymorphism
iv) Inheritance
11. Explain briefly:
a) Abstraction b) Inheritance c) Polymorphism
Ans. a) Abstraction: Abstraction refers to the art of hiding the complexities and giving a simple
interface. For example in a car, for a layman, it is good enough to know driving. Hardly will he
know the intricacies of movement of the engine, the working of the electrical and electronic
components; what he will know or will be interested with is the steering for turning, the accelerator
for speed and the switches. This is because he has been given a simple interface and the complexity
of the car engine movement has been kept completely hidden from him. Thus he doesn’t bother
about the intricacies of the car’s engine movement, but concentrates only on driving.
b) Inheritance: Inheritance is the ability to inherit characteristics from another object. In more
concrete terms, an object is able to pass on its state and behaviours to its children. For inheritance
to work, the objects need to have characteristics in common with each other. It is basically a term
that is used to represent hierarchical relationship of generalization.
c) Polymorphism: The term Polymorphism is actually a combination of two terms
Poly and Morphism. Here the term Poly means many and Morphism means forms. It is the ability of
objects to have many methods of the same name, but each one responds to different types of specific
behaviour as they have different forms.
12. How does class acts as a blueprint for an object?
Ans. A class acts as a blueprint or template that defines certain characteristics and behaviour and an
object is an instance or copy of a class.
13. How does encapsulation acts as a protective layer for an object?
Ans. Encapsulation is a technique that binds together function and the data into a single unit. You can
imagine it to be as a protective wrapper that prevents the code and data from being accessed by other
codes defined outside the wrapper.
14. How does modularity helps in reducing the complexity of a program?
Ans. Modularity helps in breaking a huge task into smaller units called functions for easy
maintainability and reusability thus reducing the complexity of the task at large.
15. What do you understand by data abstraction? Explain with an example. [ICSE 2006 & 2010]
Ans. Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting the
data.
Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the
volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know
its internal details, that is, you do not know how it receives signals over the air or through a cable, how it
translates them, and finally displays them on the screen.
16. Give a real world explanation about abstraction.
Ans. A switch board is an example of abstraction. Imagine if the concept of switchboard did not exist.
You would find a great number of wires hanging round your room. To start with an appliance, you
needed to join two wires. But essentially you need to know which group of wires should be joined to
start an appliance. Moreover, more the number of wires, more will it be confusing to identify the wires
to start an appliance. Thus joining of wires is not only confusing but may also prove fatal as far as safety
is concerned. Thus, the electrician installs a switchboard that connects each of the wires to a switch.
Hence, it is just enough to know for the user to switch on that switch that starts an appliance.
17. Why is abstraction often referred to be as relative?
Ans. Abstraction is often referred to as relative because abstraction is the selective examination of
certain aspects of a problem. The goal of abstraction is to isolate those aspects that are important for
some purpose and suppress or hide those aspects that are unimportant. Abstraction must always be for
some purpose, because the purpose determines what is important and what is not. Many different
abstractions of the same thing are possible, depending on the purpose for which they are made.
Chapter 2: The Java Phenomenon
Practice Questions
------------------------------->Objective-Type Questions<---------------------------
A. Choose the correct answer:
1. What was Java initially called?
a) Oak b) C c) C++ d) None of these
Ans. a) Oak
2. What is Java Programming Language?
a) A run-time system b) A set of development tools
c) An Application Programming Interface (API) d) All of these
Ans. d) All of these
3. Name the process that converts source code to bytecode.
a) Interpretation b) Compilation c) Both a and b d) None of these
Ans. b) Compilation
4. A Virtual Processor that is implemented in software and runs using the capabilities provided
by your operating system and computer hardware.
a) Byte Code b) Compiler c) Interpreter d) Java Virtual Machine (JVM)
Ans. d) Java Virtual Machine (JVM)
5. Name the hardware or software environment in which a program executes.
a) Operating System b) Platform c) Software d) Program
Ans. b) Platform
6. Name the programs that can be developed in such a way that it remains embedded in a web
page and runs on the viewer’s machine in a secured manner by Java-compatible browsers.
a) Applets b) Applications c) Servlets d) Enterprise Java Beans (EJB)
Ans. a) Applets
7. Name the Application program that is written and compiled which may then be executed in
any machine provided it contains the JVM.
a) Applets b) Applications c) Servlets d) Enterprise Java Beans (EJB)
Ans. b) Applications
8. What is the type of Java program that allows development and deployment of transactional,
distributed object application-based, server-side software components?
a) Applets b) Applications c) Servlets d) Enterprise Java Beans (EJB)
Ans. d) Enterprise Java Beans (EJB)
9. Choose from among the following which is not the characteristics of a Java program.
a) It is platform-independent.
b) It helps in developing any kind of applications.
c) It does not support interactive content on web pages.
d) It is ideal to make Distributed networking applications.
Ans. c) It does not support interactive content on web pages.
10. What is a set of pseudo-machine language instructions that are understood by the Java
Virtual Machine and are independent of the underlying hardware called?
a) JVM b) Source Code c) Compilation d) Bytecode
Ans. d) Bytecode
B. Fill in the blanks:
1. Java made Web interesting as it makes it Interactive
.
2. Java was formerly known as Oak.
3. Bytecode is a set of pseudo-machine language instructions that are understood by the JVM.
7. Applets are small programs that remain embedded in a web page and runs on the viewer’s
machine in a secured manner.
----------------------------->Subjective-Type Questions<-----------------------------
Answer the following questions:
1. What is the significance of WWW?
Ans. WWW or World Wide Web allows a huge pool of information (as web pages) to shared by multiple
users over a World Wide Network (Internet) and the introduction of Java makes the web pages dynamic
and interactive in a secured manner.
2. What is Browsing?
Ans. Browsing over the internet allows surfing through the internet, thus enabling the users to see
information in different pages and interact with it.
3. Name two types of Java programs.
Ans. The two types of Java programs are Applications and Applets.
4. Why is Java choice for the Web?
Ans. The introduction of active web pages makes Java an attractive addition to the web page. When we
click on a web page containing a Java applet, it is not that we just read it, listen to it, or watch it– we can
interact with it. The dynamic, interactive content to the web was brought about by Java: So much so
web applications made in Java runs as if it is a computer program installed in the local computer.
5. What is Java API?
Ans. An application programming interface (API), in the context of Java, is a collection of prewritten
packages and classes. Similar to a user interface, which facilitates interaction between humans and
computers, an API serves as a software program interface facilitating interaction.
In Java, most basic programming tasks are performed by the API’s classes and packages, which
are helpful in minimizing the number of lines written within pieces of code.
6. Define the term Bytecode.
Ans. Bytecode is a set of pseudo-machine language instructions that are understood and
executed by the Java Virtual Machine and are independent of the underlying hardware.
7. What is JVM? Explain its relationship with bytecode.
Ans. The Java Virtual Machine (JVM) is a microprocessor that is implemented in software and
runs using the capabilities provided by your operating system and computer hardware. Since the
Java virtual machine is not a real microprocessor, the Java bytecode is interpreted, rather than
executed, directly in the native machine instructions of the host computer.
8. What is a platform? How does it differ from a Java platform?
Ans. A platform is the hardware or software environment in which a program remains. Most
platforms may be described as a combination of the operating systems (like Windows 2000/XP,
Linux, Solaris, MacOS, etc.) and hardware.
The Java platform differs from most other platforms in that it is a software-only platform that runs
on top of other hardware-based platforms. The Java platform has two components:
1. Java Virtual Machine (JVM)
2. Java Application Programming Interface (API)
9. Why is Java suited for distributed networking applications?
Ans. Java is ideal to make distributed networking applications because of its built-in networking
support and the runtime system’s capability to dynamically load Java bytecode across the network.
10. What makes Java suitable to create secured applications?
Ans. It was designed with multiple layers of security countermeasures embedded in the compiler, run-
time system, and in browsers that support Java, known as Java-enabled browsers. These
countermeasures make Java inherently more secure for developing any type of trusted application
software.
11. What are the features in Java that were added, but wasn’t present in C++?
What were the features that were discarded?
Ans. The features that were added to Java which were not present in C++ are:
1) Java Virtual Machine (JVM)
2) Java Application Programming Interface (API)
The features that were dropped are Pointers and Operator Overloading.
12. What is the Green Project?
Ans. Patrick Naughton, on December 5th, 1990, started the Green Project, which he defined as an
effort to “do fewer things better”.
13. State the events occurring from the year 1994 onwards with respect to Java.
Ans. In the year 1994 the Web emerged, Oak was renamed Java and was used as the basis for a
Web browser, called Web Runner. In 1995 Java, along with its documentation, compiler and run-
time engine were made available over the Web, as an alpha version. Initially Java was hosted on
SPARC Solaris, and then on Windows NT. In the summer of 1995, Java was ported to Windows
95 and Linux.
In the fall of 1995 the Java Beta 1 version was released through Sun Microsystems Website, and
Java support was introduced in the Netscape 2.0 browser. During those days it was a fairly
popular browser.
14.State the areas in which Java can be used.
Ans. Java applications areas are Enterprise Software, Secured Network Applications and
interactive web pages.
15. What is Java platform? In this respect also discuss why Java is called a
programming language and a platform.
Ans. The Java platform is a software-only platform that runs on top of other hardware-based
platforms. It has two major components:
1. Java Virtual Machine (JVM)
2. Java Application Programming Interface (API)
Java is not just a programming language that is used to develop applications but it also provides a
runtime environment that simulates a hardware and software called platform.
16. State the characteristics of Java.
Ans. Characteristics of Java:
c) Security
d) Built-in Graphics
f) Supports Multimedia
g) Platform Independent
h) Open Product
17. What are the different types of programs that can be used in Java?
Ans. The different type of programs that can be used using Java technology are:
a) Applets
b) Applications
c) Servlets
{
static void example( )
{
System.out.print(“Hello”);
System.out.print(“from”);
System.out.print(“BlueJ”);
}
}
Ans. HellofromBlueJ
{
static void example( )
{
System.out.print(“Hello”);
System.out.println(“from”);
System.out.print(“BlueJ”);
}
}
Ans. Hellofrom
BlueJ
{
static void example( )
{
System.out.println(27+36);
System.out.println(12*19);
System.out.println(57%12);
}
}
Ans. 63
228
6.84
}
}
Ans. Calculation=780
C. Find the errors in the following programs:
1. public Class Trial
{
static void example ( )
{
System.out.printlin("Systemetic");
System.out.println("Programming")
System.out.println("In Java");
}
2. public class Trial
{
Static void example( );
{
system.out.println("Systemetic");
system.out.println("Programming");
System.out.println("In Java");
};
}
Ans. Find the errors in the following programs: (All corrections are underlined)
1. public class Trial
{
static void example ( )
{
System.out.println("Systemetic");
System.out.println("Programming");
System.out.println("In Java");
}
}
Lab Exercises
1. Write a program to display your name and your friend’s name using
System.out.println( ) in different lines.
Ans. public class Question1
{
static void main()
{
System.out.println("Devashis Chakraborty");
System.out.println("Amit Mishra");
}
}
2. Write a program to display the names of five fruits using System.out.print( ) 5
times in the same line.
Ans. public class Question2
{
static void main()
{
System.out.print("Apple ");
System.out.print("Guava ");
System.out.print("Orange ");
System.out.print("Grapes ");
System.out.print("Mango");
}
}
3. Write a program to find the add 5 and 6 and multiply it with 7. (Hint : (5+6)*7)
Ans. public class Question3
{
static void main()
{
System.out.println((5+6)*7);
}
}
7. Write a program to add 56 and the last digit of 768 [Hint whenever you divide a
no. by 10 the remainder is always the last digit.]
---------------------------->Objective-Type Questions<-------------------------------
Fill in the blanks:
1. Java uses Unicode character set.
2. Unicode is a two bytes character set.
3. Character Set is a set of valid characters that a language can recognize.
4. The smallest individual unit in a program is a token.
5. Identifiers are fundamental building blocks that give names to different parts of a program.
6. Escape sequences/Non graphic characters are characters that cannot be typed directly from
the keyboard.
7. Variables represent named storage locations whose values can be manipulated during
program execution.
8. Operators that act upon two operands are referred to as Binary operators.
9. The process of converting one predefined type into another is called Type Conversion.
10. The new operator is used to allocate memory for objects and arrays.
----------------------------->Subjective-Type Questions<-----------------------------
Answer the following questions:
1. What is Character Set?
Ans. Character set is a collection of all the characters that can be used in a Java program. A character
represents any letter (whether capital or small), digits (0 to 9) or any symbol (%, &, ^, @, $, |, etc).
2. What is bytecode?
Ans. Bytecode is an intermediate language which is received upon compilation of source code and
interpreted by the JVM (Java Virtual Machine).
3. What is indentation in a Java program?
Ans. Indentations are whitespaces that are given by programmers to increase the readability of a
source code.
4. What are keywords?
Ans. Keywords are reserved words in Java and thus provide a special meaning to the Java compiler.
5. What are Identifiers? State the rules while using Identifiers.
Ans. Identifiers are the names given to different parts or elements of a program to identify it.
The rules that you should keep in mind to use identifiers are:
a) It can have any alphabet (capital or small), digits, underscore and dollar sign
characters.
b) It should not begin with digits or should not contain any special character.
c) It cannot have a space in between.
d) It must not be a keyword.
e) It can be of any length.
f) Since Java is case-sensitive, it treats capital (upper-case) and small
(lower-case) characters differently.
6. What is a literal? What are the different types of literals available in Java?
Ans. Literals are tokens that are used to represent constants that may be assigned to a variable.
Integer literal or Fixed point literal, Floating point literal, Boolean literal, Character literal, String
literal, Null literal and Class literal are the literals that are used in Java.
7. State the difference between a Boolean literal and a character literal.
Ans. A character literal is used to enclose a character within single quotes and boolean literal
refer to two states i.e. true (to represent success) and false (to represent failure).
8. How are Decimal, Octal and Hexadecimal integer literals represented in Java?
Ans. Decimal Integer Literals use digits from 0 to 9 (i.e. 10 digits)
Octal Integer Literals use digits from 0 to 7 (i.e. 8 digits) and should be prefixed with 0.
Hexadecimal Integer Literals use digits from 0 to 9 and alphabets from A (or a) to F (or f)
representing 10 to 15 (i.e. 16 numbers) altogether and should be prefixed with 0x or 0X.
9. What are the escape sequences available in Java?
Ans. The escape sequences available in Java are:
Escape Sequences Meaning
'\b' Backspace
'\f' Form feed
'\n' New line
'\r' Carriage return
'\t' Horizontal Tab
'\' Single quote
"\" Double quote
'\\' Backslash
'\0n' Octal number, where n is the number
'\xHn' Hexadecimal number, where n is the number
'\uHn' Unicode character represented through its hexadecimal code n
10. What are the different punctuators available in Java?
Ans. There are 9 punctuators available in Java. They are: ( ) { } [ ] ; , .
11. What are Tokens?
Ans. Token is the smallest fundamental unit in a program. They are the valid characters or
symbols that can be used in a Java program.
12. State the difference between token and identifier.
Ans. Token is the smallest fundamental unit in a program, whereas identifier is a token which is
used to give names to different parts or elements of a program to identify it.
13. State the two kinds of data types.
Ans. The two data types are:
a) Fundamental Data Type
b) Composite Data Type
14. State the size of integer data types in Java.
Ans. The size of integer data types are:
a) byte – 8 bits
b) short – 16 bits
c) int – 32 bits
d) long – 64 bits
15. How are floating point numbers represented in Java?
Ans. Floating point numbers are used to represent fractional numbers (with decimal point). Java
provides two ways of representing fractional numbers viz. float and double. Float type numbers
are suffixed with F or f and double type numbers are suffixed with D or d, however suffixing
with D or d for double data type is optional.
16. What are variables? How are variables initialized?
Ans. Variable is a name given to memory location where data is stored or needs to be stored.
The general format of variable declaration is as follows:
<data-type><variable-name>;
For initialization of variables use the general syntax :
<data-type> <variable-name>=<constant>;
Lab Exercises
A. Write the following programs:
1. Write a program to initialize two integer variables a and b with 5 and 6 respectively and
interchange them. Thus after interchanging a and b will be 6 and 5 respectively.
Ans. public class Question1
int a=5,b=6,t;
t=a;
a=b;
b=t;
2. Write a program to display the names of five fruits with a single System.out.println( );
statement, but in different lines.
Ans. public class Question2
{
static void main()
{
System.out.println("Apple\nOrange\nGuava\nMango\nGrapes");
}
}
3. Write a program using float type variables to find the area and perimeter of a square
whose side is 12 cm.
Ans. public class Question3
{
static void main()
{
float s=12,a;
a=s*s;
System.out.println("Area of the square="+a+" square cm");
}
}
4. Write a program using int variables to find the sum of three numbers, say 15, 36 and
45, and subtract the result from 100.
Ans. public class Question4
{
static void main()
{
int a=15,b=36,c=45,d=100,e,f;
e=a+b+c;
f=d-e;
System.out.println("Sum="+e);
System.out.println("Difference="+f);
}
}
5. Write a program using int variables to find the area and perimeter of a rectangle of
length 12 cm and breadth 8 cm.
Ans. public class Question5
{
static void main()
{
int length=12,breadth=8,area,perimeter;
area=length*breadth;
perimeter=2*(length+breadth);
System.out.println("Area="+area);
System.out.println("Perimeter="+perimeter);
}
}
6. Write a program using variables to find the profit and profit per cent of a certain
transaction where S.P.= Rs.10000 and C.P.= Rs.7000.
Ans. public class Question6
{
static void main()
{
int SP=10000,CP=7000;
double profit,profitPercentage;
profit=SP-CP;
profitPercentage=(double)profit/CP*100;
System.out.println("Profit="+profit);
System.out.println("Perimeter="+profitPercentage);
}
}
7. Write a program using variables to find the cost of 17 pencils if the cost of one pencil=
Rs.2.50. Output should be:
Cost of 1 pencil= Rs.2.5
Cost of 17 pencils= Rs.42.5
Ans. public class Question7
{
static void main()
{
float rate=2.50f, cost;
int pencils=17;
cost=pencils*rate;
System.out.println("Cost of 1 pencil= Rs "+rate);
System.out.println("Cost of 17 pencils= Rs "+cost);
}
}
8. Write a program to initialize three int variables a, b and c with 234, 456 and 712 and
store the sum of the last digits of the variables into d and display it.
Ans. public class Question8
{
static void main()
{
int a=234, b=456, c=712, d;
d=a%10+b%10+c%10;
System.out.println("Sum of last digits="+d);
}
}
9. Write a program to initialize an int variable a with 76498 and from it extract the first
digit and store it in f and extract the last digit in l and display both these digits.
Ans. public class Question9
{
static void main()
{
int a=76498,f,l;
f=a/10000;
l=a%10;
System.out.println("First digit="+f);
System.out.println("Last digit="+l);
}
}
10. Write a program using variables to find the average of 35, 43 and 97.
Ans. public class Question10
{
static void main()
int a=35,b=43,c=97;
float avg;
avg=(float)(a+b+c)/3;
System.out.println("Average of the numbers="+avg);
}
}
B. Short-answer-type questions:
1. Write the corresponding expressions for the following mathematical operations:
i) a2 + b2
ii) z = x3 + y3 – xy /z
Ans. i) a*a + b*b
ii) z=x*3 + y*3 – x*y/z
2. What will be the output for the following program segment?
int a = 0, b = 30, c = 40;
a = − −b + c++ + b;
System.out.println("a =" + a);
Ans. a =99
3. if m = 5 and n = 2 output the values of m and n after execution in (i) and (ii):
i) m − = n;
ii) n = m + m/n;
Ans. i) m=3 and n=2
ii) m=5 and n=7
4. What will be the output of the following, if x = 5 initially?
i) 5 *++x
ii) 5*x++
Ans. i) 30
ii) 25
5. Evaluate the following expressions, if the values of the variables are a = 2, b=3 and c=9
i) a − (b++) * (− −c)
ii) a * (++b) % c
Ans. i) -22
ii) 8
6. If a = 5, b = 9 calculate the value of :
a+ = a++ – ++b + a
Ans. a=6 and b=10
7. What is the result stored in x, after evaluating the following expression
int x = 5;
x = x++ *2 + 3 * –x;
Ans. -8
8. Assign the value of pi (i.e. 3.142) to a variable with requisite data type.
Ans. double pi=3.142;
5
Chapter 5: Programming in Java
Practice Questions
----------------------------->Objective-Type Questions<------------------------------
State whether True or False:
1. A statement missing a semicolon is an example of logical error. [False]
2. You can input only integers using parameterized inputs. [False]
3. Using nextInt( ) member function of the Scanner class, you can input a string. [False]
4. While you input numbers of float data type using Scanner, succeed the number with f?[False]
5. Parameterised input for String requires you to enter data within quotes. [True]
----------------------------->Subjective-Type Questions<-----------------------------
Answer the following questions:
1. Rewrite the following program after removing the errors in the program, if any:
class Myclass
{
import java.util.Scanner;
static void function( )
{
int a;
a=sc.nextInt( );
Scanner sc=new Scanner(System.in);
System.out.println(a);
}
Ans. All corrections made are underlined:
import java.util.Scanner;
class Myclass
{
static void function( )
{
int a;
System.out.println(“Enter an integer:”);
a=sc.nextInt( );
System.out.println(a);
}
}
Lab Exercises
Write the following programs:
1. Write a program to input two integers using parameters and find their sum and
product.
Ans. public class Question1
{
static void main(int a,int b)
{
int s,p;
s=a+b;
p=a*b;
System.out.println("Sum="+s);
System.out.println("Product="+p);
}
}
2. Write a program to input 5 integers and find their average.
Ans. public class Question2
{
static void main(int a,int b,int c,int d,int e)
{
float avg;
avg=(a+b+c+d+e)/5;
System.out.println("Average="+avg);
}
}
3. Write a program to input two integers using Scanner and find the product of
their sum and difference.
Ans. import java.util.*;
public class Question3
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,s,d,p;
System.out.println("Enter two integers:");
a=sc.nextInt();
b=sc.nextInt();
s=a+b;
d=a-b;
p=s*d;
System.out.println("Sum="+s);
System.out.println("Difference="+d);
System.out.println("Product of Sum and Difference="+p);
}
}
4. Write a program to input three integers and find the difference between their
sum and their average.
Ans. import java.util.*;
public class Question4
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,sum;
float avg,diff;
System.out.println("Enter three integers:");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
sum=a+b+c;
avg=(float)sum/3;
diff=sum-avg;
System.out.println("Difference="+diff);
}
}
5. Write a program to input the Principal, Rate and Time for a certain amount of
money and print the Simple Interest.
(𝑷𝒓𝒊𝒏𝒄𝒊𝒑𝒍𝒆 ∗𝑹𝒂𝒕𝒆∗𝑻𝒊𝒎𝒆)
Note: Simple Interest =
𝟏𝟎𝟎
Ans. import java.util.*;
public class Question5
{
static void main()
{
Scanner sc=new Scanner(System.in);
float principal,rate,time,SI;
System.out.println("Enter Principal, Rate and Time:");
principal=sc.nextFloat();
rate=sc.nextFloat();
time=sc.nextFloat();
SI=(principal*rate*time)/3;
System.out.println("Simple Interest="+SI);
}
}
6. Write a program to input the length and breadth of a rectangle and find its area and
perimeter.
Note: Area of a rectangle=length*breadth
Perimeter of a rectangle=2*(length + breadth)
Ans. import java.util.*;
public class Question6
{
static void main()
{
Scanner sc=new Scanner(System.in);
float length,breadth,area,perimeter;
System.out.println("Enter length and breadth of a rectangle:");
length=sc.nextFloat();
breadth=sc.nextFloat();
area=length*breadth;
perimeter=2*(length+breadth);
System.out.println("Area="+area);
System.out.println("Perimeter="+perimeter);
}
}
7. Write a program to input the radius of a circle and find its area and circumference.
Note: Area of a circle=22/7 * radius2
Circumference of a circle= 2 * 22/7 * radius
Ans. import java.util.*;
public class Question7
{
static void main()
{
Scanner sc=new Scanner(System.in);
float radius,area,circumference;
System.out.println("Enter radius of a circle:");
radius=sc.nextFloat();
area=(float)22/7*radius*radius;
circumference=2*(float)22/7*radius;
System.out.println("Area="+area);
System.out.println("Circumference="+circumference);
}
}
8. Write a program to input the length, breadth and height of a cuboid and find its Volume
and Total Surface Area.
Note: Volume of a cuboid= length*breadth*height
Total Surface Area=2*(length*breadth+breadth*height+height*length)
Ans. import java.util.*;
public class Question8
{
static void main()
{
Scanner sc=new Scanner(System.in);
float length,breadth,height,vol,area;
System.out.println("Enter length, breadth and height of a cuboid:");
length=sc.nextFloat();
breadth=sc.nextFloat();
height=sc.nextFloat();
vol=length*breadth*height;
area=2*(length*breadth+breadth*height+height*length);
System.out.println("Volume of cuboid="+vol);
System.out.println("Total Surface Area="+area);
}
}
9. Write a program to input the radius and height of a cylinder and find its volume and
total surface area.
Note: Total Surface Area=2πr2 + 2πrh
Volume= πr2h
Ans. import java.util.*;
public class Question9
{
static void main()
{
Scanner sc=new Scanner(System.in);
float radius,height,vol,area;
System.out.println("Enter radius and height of a cylinder:");
radius=sc.nextFloat();
height=sc.nextFloat();
vol=(float)22/7*radius*radius*height;
area=2*(float)22/7*radius*(radius+height);
System.out.println("Volume of cylinder="+vol);
System.out.println("Total Surface Area="+area);
}
}
10. Write a program to input three integers and find the sum of the last digit of the
numbers.
For example, if the inputs are: 12
26
35
Output:
Sum of the last digit of the integers are: 13
Ans. import java.util.*;
public class Question10
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,s;
System.out.println("Enter three integers:");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
s=a%10+b%10+c%10;
System.out.println("Sum of the last digit of the integers are:"+s);
}
}
11. Write a program to input the temperature in Fahrenheit and change it to Celsius.
Note: The relation between Fahrenheit and Celsius is given by the formula:
𝑪 𝐅 − 𝟑𝟐
=
𝟓 𝟗
Where C=Celsius and F=Fahrenheit
Ans. import java.util.*;
public class Question11
{
static void main()
{
Scanner sc=new Scanner(System.in);
float f,c;
System.out.println("Enter temperature in fahrenheit:");
f=sc.nextInt();
c=(f-32)*5/9;
System.out.println("Temperature in Celcius:"+c);
}
}
12. Write a program to input time in seconds and display the time broken up as hours,
minutes and seconds.
For Example:
INPUT: Enter Time in Seconds: 4326
OUTPUT:
Time in hours:1
Time in minutes:12
Time in seconds:6
Ans. import java.util.*;
public class Question12
{
static void main()
{
Scanner sc=new Scanner(System.in);
int s,h,m,ss;
System.out.println("Enter temperature in seconds:");
s=sc.nextInt();
h=s/3600;
m=(s%3600)/60;
ss=(s%3600)%60;
System.out.println("Time in hours:"+h);
System.out.println("Time in minutes:"+m);
System.out.println("Time in seconds:"+ss);
}
}
13. Write a program to input a floating point number and round it off to the nearest
integer.
For Example:
INPUT: Enter a floating point number: 12.3
OUTPUT: Rounded off to nearest integer:12
INPUT: Enter a floating point number: 14.5
OUTPUT: Rounded off to nearest integer:15
Ans. import java.util.*;
public class Question13
{
static void main()
{
Scanner sc=new Scanner(System.in);
float f;
int n;
System.out.println("Enter a floating point number:");
f=sc.nextFloat();
n=(int)(f+0.5);
System.out.println("Rounded off to nearest integer:"+n);
}
}
14. Write a program to input a floating point number and round it off to two places of
decimal.
For Example:
INPUT: Enter a floating point number: 12.367
OUTPUT: Rounded off to two places of decimal:12.37
INPUT: Enter a floating point number: 14.563
OUTPUT: Rounded off to two places of decimal:14.56
Ans. import java.util.*;
public class Question14
{
static void main()
{
Scanner sc=new Scanner(System.in);
float f,n;
int h;
System.out.println("Enter a floating point number:");
f=sc.nextFloat();
h=(int)((f*100)+0.5);
n=(float)h/100;
System.out.println("Rounded off to two places of decimal:"+n);
}
}
15. Write a program to input two integers (say a and b) and interchange their values and
display the result.
For Example:
INPUT: Enter two integers: 15 36
OUTPUT:
Before interchange: a=15 and b=36
After interchange: a=36 and b=15
Please note that you can take just one variable other than a and b for interchanging.
Ans. import java.util.*;
public class Question15
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println("Enter two integers:");
a=sc.nextInt();
b=sc.nextInt();
System.out.println("Before interchange: a="+a+" and b="+b);
c=a;
a=b;
b=c;
System.out.println("After interchange: a="+a+" and b="+b);
}
}
16. Write a program to input the time in hours, minutes and seconds and print it in
seconds.
For Example:
INPUT: Enter time in hours:
1
Enter time in minutes:
12
Enter time in seconds:
6
OUTPUT:
Time in seconds:43261
Ans. import java.util.*;
public class Question16
{
static void main()
{
Scanner sc=new Scanner(System.in);
int h,m,s,ss;
System.out.println("Enter time in hours:");
h=sc.nextInt();
System.out.println("Enter time in minutes:");
m=sc.nextInt();
System.out.println("Enter time in seconds:");
s=sc.nextInt();
ss=h*3600+m*60+s;
System.out.println("Time in seconds:"+ss);
}
}
21
17. Write a program to input three integers and find their sum, without using the
mathematical operator +.
Ans. import java.util.*;
public class Question17
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,s;
System.out.println("Enter three integers:");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
s=a-(-b)-(-c);
System.out.println("Sum:"+s);
}
}
18. Write a program to enter the perimeter of a square and find its perimeter.
For Example,
INPUT:
Enter the perimeter of a square: 64
OUTPUT:
Area of the square is: 256
Ans. import java.util.*;
public class Question18
{
static void main()
{
Scanner sc=new Scanner(System.in);
float p,s,a;
System.out.println("Enter the perimeter of a square:");
p=sc.nextInt();
s=p/4;
a=s*s;
System.out.println("Area of the square:"+a);
}
}
19. Write a program to enter the length and area of a rectangle and find its perimeter.
For Example,
INPUT:
Enter the length of the rectangle:12
Enter the area of the rectangle: 72
OUTPUT:
Perimeter of the rectangle:36.0
Ans. import java.util.*;
public class Question19
{
static void main()
{
Scanner sc=new Scanner(System.in);
float l,b,a,p;
System.out.println("Enter the length of the rectangle:");
l=sc.nextInt();
System.out.println("Enter the area of the rectangle:");
a=sc.nextInt();
b=a/l;
p=2*(l+b);
System.out.println("Perimeter of the rectangle:"+p);
}
}
20. Write a program to input the basic pay of an employee and find the gross pay of the
employee for the following allowances and deductions:
Dearness Allowance = 25% of Basic Pay
House Rent Allowance=15% of Basic Pay
Provident Fund=8.33% of Basic Pay
Net Pay=Basic Pay + Dearness Allowance + House Rent Allowance
Gross Pay= Net Pay – Provident Fund
Ans. import java.util.*;
public class Question20
{
static void main()
{
Scanner sc=new Scanner(System.in);
float basic,da,hra,pf,np,gp;
System.out.println("Enter the basic pay of the employee:");
basic=sc.nextFloat();
da=(float)25/100*basic;
hra=(float)15/100*basic;
pf=(float)8.33/100*basic;
np=basic+da+hra;
gp=np-pf;
System.out.println("Gross Pay:"+gp);
}
}
21. Write a program to input the dimensions of a rectangle and find the area of
that square whose perimeter is equal to the perimeter of the rectangle.
Ans. import java.util.*;
public class Question21
{
static void main()
{
Scanner sc=new Scanner(System.in);
float l,b,p,s,a;
System.out.println("Enter the length & breadth of the rectangle:");
l=sc.nextFloat();
b=sc.nextFloat();
p=2*(l+b); //perimeter of the rectangle
s=p/4; /*side of the square whose perimeter is equal
to the perimeter of the rectangle*/
a=s*s; //area of the square
System.out.println("Area of the Square:"+a);
}
}
22. Write a program to input an integer and if positive change it to negative and if
negative change it to positive.
INPUT: Enter an integer: 12
OUTPUT: Sign changed: –12
INPUT: Enter an integer: –14
OUTPUT: Sign changed: 14
Ans. import java.util.*;
public class Question22
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.print("Enter an integer: ");
a=sc.nextInt();
b=-a;
System.out.println("Sign Changed: "+b);
}
}
23. Write a program to input two integers into two variables (say a and b) and
interchange them by:
i) using a third variable (say c),
ii) without using a third variable.
Ans. (i) import java.util.*;
public class Question23i
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println("Enter two integers: ");
a=sc.nextInt();
b=sc.nextInt();
System.out.println("Before interechange: a="+a+",b="+b);
c=a;
a=b;
b=c;
System.out.println("After interechange: a="+a+",b="+b);
}
}
(ii)import java.util.*;
public class Question23ii
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.println("Enter two integers: ");
a=sc.nextInt();
b=sc.nextInt();
System.out.println("Before interechange: a="+a+",b="+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("After interechange: a="+a+",b="+b);
}
}
24. If the marks obtained by a student in five different subjects are input through
the keyboard, write a program to find out the aggregate marks and percentage
marks obtained by the student. Assume that the maximum marks that can be
obtained by a student in each subject is 100.
Ans. import java.util.*;
public class Question24
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,d,e,agg;
float perc;
System.out.println("Enter marks in 5 subjects: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=sc.nextInt();
e=sc.nextInt();
agg=a+b+c+d+e;
perc=(float)agg/500*100; /*Assuming maximum marks
in each subject is 100*/
System.out.println("Aggregate Marks="+agg);
System.out.println("Percentage Marks="+perc);
}
}
25. If the total selling price of 15 items and the total profit earned on them is input
through the keyboard, write a program to find the cost price of one item.
Ans. import java.util.*;
public class Question25
{
static void main()
{
Scanner sc=new Scanner(System.in);
float sp,profit,cp,cpOfOne;
System.out.println("Enter total Selling Price of 15 items: ");
sp=sc.nextFloat();
System.out.println("Enter total profit of 15 items: ");
profit=sc.nextFloat();
cp=sp-profit; //Total Cost Price
cpOfOne=cp/15; //Cost Price of one item.
System.out.println("Cost Price Of one Item="+cpOfOne);
}
}
26. Write a program to input three integers and find their product without the '*'
operator.
Ans. import java.util.*;
public class Question26
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,p;
float f,e;
System.out.println("Enter 3 integers: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
f=(float)1/b;
e=(float)1/c;
p=(int)(a/f);
p=(int)(p/e);
System.out.println("Product="+p);
}
}
27. Write a program to input an integer and raise it to the power of 2 and display it.
INPUT: Enter an integer: 4
OUTPUT: Power of 2 is: 16
INPUT: Enter an integer: 6
OUTPUT: Power of 2 is: 64
(Hint: use the shift operator)
Ans. import java.util.*;
public class Question27
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.print("Enter an integer: ");
a=sc.nextInt();
b=2<<(a-1);
System.out.println("Power of 2 is:"+b);
}
}
122
6
Chapter 6: Conditional Structures
Practice Questions
Answer the following questions:
1. What are conditional statements? With which commands do you implement
conditional statement in Java?
Ans. Conditional Statements are those statements which contains a test-expression which may either
result to true or false. Depending upon the result a statement or groups of statements are executed.
It is implemented through if-else, if-else if-else, switch-case or using ternary operator (?:).
2. When are braces optional or necessary in conditional statements?
Ans. When there is only one statement to be executed if the result of a test-expression is true or
false, giving braces is optional.
3. What are relational operators?
Ans. Relational operators are used for comparison between two data items or quantities that
are used in a test-expression/ condition.
4. State the difference between = and = =. [ICSE 2007]
Ans. ‘=’ is used to assign a value to a variable, whereas ‘==’ is used for comparison of two
values for equality.
5. What are logical operators? Explain each of them with the help of an example.
Ans. Logical operators are used when there are more than one relational expression needs to
evaluated. It is categorised as AND(&&), OR(||) and NOT(!).
For example:
if(a>10)
b=10;
else
b=15;
using conditional operator may be written as:
b=(a>10)? 10:15;
8. Compare if and ? : .
Ans.
For example,
switch(a)
{
case 1:
System.out.println(“One”);
break;
case 2:
System.out.println(“Two”);
break;
case 3:
System.out.println(“Three”);
break;
default:
System.out.println(“Not 1,2 or 3”);
}
In this code if the value of ‘a’ is neither 1,2 or 3, none of the case blocks gets executed and
therefore the statement in the default block gets executed, which gives the output as:
Not 1,2 or 3
In this code if someone gets 95 the condition marks>=90 gets satisfied and Grade A gets printed. Again
if marks is 85 the marks>=70, marks>=50 and marks>=30 all get satisfied but only marks>=70 will get
executed as this is the first satisfying statement in the elseif adder and therefore Grade B gets executed.
Similarly if marks is 55, Grade C gets printed. Now if marks is 15, none of the above conditions gets
satisfied and therefore the statement in the else part gets executed, which prints Grade E.
B. Do as directed in the following questions:
1. Using the given values of x, y and z evaluate the following (Answer in true / false).
(x>=y) || (!(z==y) && (z<x))
i) x=10, y=5, z=11
ii) x=10, y=10, z=10
iii) x=9, y=10, z=2
Ans. i) True
ii) True
iii) True
2. Using conditional operator write equivalent expressions for the following: [ICSE 2007]
i) F=0.5 if x=30 otherwise 0.
ii) Print "Even" if x is an even number otherwise print "Odd".
iii) if (income < = 10000)
tax = 0 ;
else
tax = 12 ;
Ans. i) F=(x==30)?0.5:0;
ii) System.out.println((x%2==0)? “Even”: “Odd”);
iii) Tax=(income<=10000)?0:12;
3. Find the output of the following program segment, when: [ICSE 2006]
i) val = 500
ii) val = 1600
int val, sum, n = 550;
sum = n + val > l750? 400 : 200;
System.out.println(sum);
Ans. i) 200
ii) 400
4. Write the conditional statement for the following decision-making situation: Provided
the value of x is greater than 9, increase the value of y by 15, otherwise decrease the
value of y by 36.
Ans. (x>9)?y=y+15:y=y-36;
5. Write equivalent Java statements for the following situations:
i) X is greater than equal to Y.
ii) X is not equal to Y.
iii) X is equal to Y.
iv) X is less than Y and X is less than Z.
v) Either X is greater than Y or X is less than Z.
vi) If X has a value greater than 20 then increment the value of J by 1 otherwise
decrement the value by 2.
vii) It is not that X is greater than Y.
Ans. i) X>=Y
ii) X!=Y
iii) X==Y
iv) X<Y && X<Z
v) X>Y || X < Z
vi) (X>20)? J++:J-=2;
vii) (!(X>Y))
switch(code)
{
case 1:
System.out.print("Accountant");
break;
case 5:
case 6:
System.out.print("Grade IV");
break;
case 3:
System.out.print("Financial Advisor");
}
10. Find the syntax error(s), if any, in the following program and rewrite it after
correction:
Class First{
public static void main(String args[]){
int R; W=90;
R=W-50;
Switch(W)
{
20:system.out.print(Lower Range");
30:System.Out.print("Middle Range")
40:System.out.Print("Higher Range);
}
}
Ans. class First{
public static void main(String args[ ]){
int R, W=90;
R=W-50;
switch(W)
{
case 20:
System.out.print("Lower Range");
break;
case 30:
System.out.print("Middle Range");
break;
case 40:
System.out.print("Higher Range");
}
}
12. Given the output of the following code fragment: [ICSE 2008]
when (i) opn='b' (ii) opn='x' (iii) opn='a'
switch(opn)
{
case 'a':
System.out.println("Platform-Independent");
break;
case 'b':
System.out.println("Object-Oriented");
case 'c':
System.out.println("Robust and Secure");
break;
default:
System.out.println("Wrong Input");
}
Ans. i) Object-Oriented
Robust and Secure
ii) Wrong Input
iii) Platform-Independent
13. Write a program to input an integer and check whether it is greater than 100,
or less than 100 or equal to 100. (use if-else if statement)
Ans. import java.util.*;
class Question13
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter an integer:");
n=sc.nextInt();
if(n>100)
System.out.println("Greater than 100");
else if(n<100)
System.out.println("Less than 100");
else
System.out.println("Equal to 100");
}
}
14. Write a program to input the Selling Price and Cost Price of a commodity and find the
Profit or Loss made upon selling the product.
For example,
INPUT:
Enter the Selling Price of the commodity: 456
Enter the Cost Price of the commodity: 400
OUTPUT:
Profit: 56
INPUT:
Enter the Selling Price of the commodity: 300
Enter the Cost Price of the commodity: 310
OUTPUT:
Loss: 10
Ans. import java.util.*;
public class Question14
{
static void main()
{
Scanner sc=new Scanner(System.in);
float sp,cp,profit=0,loss=0;
System.out.print("Enter the Selling Price of the commodity: ");
sp=sc.nextFloat();
System.out.print("Enter the Cost Price of the commodity: ");
cp=sc.nextFloat();
if(sp>cp)
{
profit=sp-cp;
System.out.println("Profit:"+profit);
}
else if(cp>sp)
{
loss=cp-sp;
System.out.println("Profit:"+loss);
}
else
System.out.println("No profit or gain");
}
}
15. Write a program to check whether a int type number taken as input is a
positive, negative or a zero. (Use if-else if statement)
Ans. import java.util.*;
public class Question15
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
System.out.print("Enter an integer: ");
a=sc.nextInt();
if(a>0)
System.out.println("Positive");
else if(a<0)
System.out.println("Negative");
else
System.out.println("Zero");
}
}
16. Write a program to check whether a short type number taken as input is an
even number or an odd number.
Ans. import java.util.*;
public class Question16
{
static void main()
{
Scanner sc=new Scanner(System.in);
short a;
System.out.print("Enter an integer: ");
a=sc.nextShort();
if(a%2==0)
System.out.println("Even Number");
else
System.out.println("Odd Number");
}
}
17. Write a program to accept an int type value as a parameter and print the
square of it, if it is more than 120, otherwise print its cube.
Ans. import java.util.*;
public class Question17
{
static void check(int n)
{
long s;
if(n>120)
s=n*n;
else
s=n*n*n;
System.out.println("Answer="+s);
}
}
18. Write a program to input 5 real numbers (floating point) and find their average.
If the average is greater than 50 print good, otherwise print bad.
Ans. import java.util.*;
public class Question18
{
static void main()
{
Scanner sc=new Scanner(System.in);
float a,b,c,d,e,avg;
System.out.print("Enter 5 real numbers: ");
a=sc.nextFloat();
b=sc.nextFloat();
c=sc.nextFloat();
d=sc.nextFloat();
e=sc.nextFloat();
avg=(a+b+c+d+e)/5;
if(avg>50)
System.out.println("GOOD");
else
System.out.println("BAD");
}
}
19. Write a program to check whether an int type number (taken as input) is a
multiple of 5 or not.
Ans. import java.util.*;
public class Question19
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
System.out.print("Enter an integer: ");
a=sc.nextInt();
if(a%5==0)
System.out.println("Multiple of 5");
else
System.out.println("Not a multiple of 5");
}
}
20. Write a program to check whether an int type number (taken as input) is a 2-
digit number or not.
Ans. import java.util.*;
public class Question20
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
System.out.print("Enter an integer: ");
a=sc.nextInt();
if(a>=10 && a<=99 || a>=-99 && a<=-10)
System.out.println("2-digit number");
else
System.out.println("Not a 2-digit number");
}
}
21. Write a program to check whether an int type number (taken as input) is a 3-
digit number divisible by three or not.
Ans. import java.util.*;
public class Question21
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
System.out.print("Enter an integer: ");
a=sc.nextInt();
if(a>=100 && a<=999 || a>=-999 && a<=-100)
{
if(a%3==0)
System.out.println("3-digit number divisible by 3");
else
System.out.println("3-digit number but not divisible by 3");
}
else
System.out.println("Not a 3-digit number");
}
}
22. Write a program to input an integer and check whether it is a 2-digit or a 3-
digit number or not. In case it is not a 2-digit or a 3-digit number a relevant
message ("Not 2 or 3 digit-number") should be displayed.
Ans. import java.util.*;
public class Question22
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
System.out.print("Enter an integer: ");
a=sc.nextInt();
if(a>=10 && a<=99 || a>=-99 && a<=-10)
System.out.println("2-digit number");
else if(a>=100 && a<=999 || a>=-999 && a<=-100)
System.out.println("3-digit number");
else
System.out.println("Not 2 or 3 digit number");
}
}
23. Write a program to input 2 integers and check whether both the numbers are
multiples of 7 or not.
Ans. import java.util.*;
public class Question23
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.print("Enter 2 integers: ");
a=sc.nextInt();
b=sc.nextInt();
if(a%7==0 && b%7==0)
System.out.println("Both are multiples of 7");
else
System.out.println("Both are not multiples of 7");
}
}
24. Write a program to input three integers and check whether all of them are
unique (different) from each other or not.
Ans. import java.util.*;
public class Question24
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 integers: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a!=b && a!=c && c!=b)
System.out.println("All are unique");
else
System.out.println("All are not unique");
}
}
25. Write a program to pass 2 integer numbers as parameters. If either of the two
numbers is 0, display "invalid entry" and the program should end; if it is valid entry,
divide the larger number with the smaller number and display the result.
Ans. public class Question25
{
static void main(int a,int b)
{
float c;
if(a==0 || b==0)
System.out.println("Invalid Entry");
else
{
if(a>b)
c=(float)a/b;
else
c=(float)b/a;
System.out.println("Result="+c);
}
}
}
26. Write a program to input an integer and check if the number is four-digit long
or longer, the program should give a message that the number is a "large number".
If it is a two-digit long or shorter, then the computer should provide a message that
the number is "too small". Otherwise, print a message WELL DONE, WE THINK
ALIKE.
Ans. import java.util.*;
public class Question26
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
System.out.print("Enter an integer: ");
a=sc.nextInt();
if(a>=1000)
System.out.println("large number");
else if(a<=99)
System.out.println("too small");
else
System.out.println("WELL DONE WE THINK ALIKE");
}
}
27. Write a program to input 3 unique integers and print the smallest among them.
Ans. import java.util.*;
public class Question27
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 integerS: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a<b && a<c)
System.out.println("Smallest number:"+a);
else if(b<a && b<c)
System.out.println("Smallest number:"+b);
else
System.out.println("Smallest number:"+c);
}
}
28. Write a program to input 3 unique integers and print the smallest among them
without using the logical operator && (AND).
Ans. import java.util.*;
public class Question28
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 integerS: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a<b)
{
if(a<c)
System.out.println("Smallest number:"+a);
else
System.out.println("Smallest number:"+c);
}
else
{
if(b<c)
System.out.println("Smallest number:"+b);
else
System.out.println("Smallest number:"+c);
}
}
}
29. Write a program to accept three integer numbers and check whether all of
them are even numbers or not; if they are, it should print "All are even", otherwise
check whether all three are odd or not, if they are it should print "All are odd". If
none of the above conditions are true, it should print "They are mixed".
Ans. import java.util.*;
public class Question29
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 integerS: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a%2==0 && b%2==0 && c%2==0)
System.out.println("All are even");
else if(a%2!=0 && b%2!=0 && c%2!=0)
System.out.println("All are odd");
else
System.out.println("They are mixed");
}
}
30. Write a program to accept 3 integer numbers and check whether the last digit
of every number is 7 or not. If it is, it should print "The last digit of all the
numbers is 7", otherwise it should print, "The last digit is not 7 for every number".
Ans. import java.util.*;
public class Question30
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 integerS: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a%10==7 && b%10==7 && c%10==7)
System.out.println("The last digit of all the numbers is 7");
else
System.out.println("The last digit is not 7 for every number");
}
}
31 Write a program to input a year and check whether it is a leap year or not.
import java.util.*;
public class Question31
{
static void main()
{
Scanner sc=new Scanner(System.in);
int y;
System.out.print("Enter a year: ");
y=sc.nextInt();
if(y%400==0 || (y%4==0 && y%100!=0))
System.out.println("Leap Year");
else
System.out.println("Not a Leap Year");
}
}
32. Write a program to accept three angles of a triangle as parameter and check whether
it can form a triangle or not. If it forms a triangle, check whether it is an acute-angled,
obtuse-angled or right angled triangle.
(Hint: To form a triangle, the sum of the angles should be 180 degrees.
To form an acute angled triangle every angle should be less than 90 degrees.
To form an obtuse angled triangle either of the angle should be more than 90 degrees.
To form a right angled triangle either of the angle should be equal to 90 degrees.)
Ans. public class Question32
{
static void main(int a,int b,int c)
{
if(a+b+c==180)
{
if(a<90 && b<90 && c<90)
System.out.println("Acute angled triangle");
else if(a>90 || b>90 || c>90)
System.out.println("Obtuse angled triangle");
else
System.out.println("Right angled triangle");
}
else
System.out.println("Do not form a triangle");
}
}
33. Write a program to input the three angles of a triangle and check whether it forms a
triangle or not, if it forms a triangle, check whether it is an equilateral, isosceles or a
scalene triangle.
(Hint: To form a triangle, the sum of the angles should be 180 degrees.
To form an equilateral triangle every angle should be equal.
To form an isosceles triangle any two angles should be equal.
To form a scalene triangle all three angles should be different from each other.)
Ans. import java.util.*;
public class Question33
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 angles: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a+b+c==180)
{
if(a==b && b==c)
System.out.println("Equilateral Triangle");
else if(a==b || b==c || c==a)
System.out.println("Isosceles Triangle");
else
System.out.println("Scalene Triangle");
}
else
System.out.println("Do not form a Triangle");
}
}
34. Write a program to input the three sides of a triangle and check whether it forms a
triangle or not, if it forms a triangle, check whether it is an equilateral, isosceles or a
scalene triangle.
(Hint: To form a triangle, each side should be less the sum of the other two sides.
To form an equilateral triangle every side should be equal.
To form an isosceles triangle any two sides should be equal.
To form a scalene triangle all three sides should be different from each other.)
Ans. import java.util.*;
public class Question34
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 sides: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a<b+c && b<c+a && c<a+b)
{
if(a==b && b==c)
System.out.println("Equilateral Triangle");
else if(a==b || b==c || c==a)
System.out.println("Isosceles Triangle");
else
System.out.println("Scalene Triangle");
}
else
System.out.println("Do not form a Triangle");
}
}
35. Write a program to accept three sides of a triangle as parameter and check whether it
can form a triangle or not. If it forms a triangle, check whether it is an acute-angled,
obtuse-angled or right angled triangle.
(Hint: To form a triangle, each side should be less the sum of the other two sides.
To form an acute-angled triangle the square of every side should be less than the sum of
the squares of the other two sides.
To form an obtuse-angled triangle the square of any side should be greater than the sum
of the squares of the other two sides.
To form a right-angled triangle, the square of any side should be equal to the sum of the
squares of the other two sides.)
Ans. import java.util.*;
public class Question35
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.print("Enter 3 sides: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a<b+c && b<c+a && c<a+b)
{
if(a*a<b*b+c*c && b*b<a*a+c*c && c*c<a*a+b*b)
System.out.println("Acute angled Triangle");
else if(a*a>b*b+c*c || b*b>a*a+c*c || c*c>a*a+b*b)
System.out.println("Obtuse angled Triangle");
else
System.out.println("Right angled Triangle");
}
else
System.out.println("Do not form a Triangle");
}
}
36. Write a program to accept a mark obtained by a student in computer science and
print the grades accordingly:
37. A bike shop hires bikes by the day at different rates throughout the year. The
following table shows how the hire charge varies throughout the year:
The proprietor also gives a discount on the number of days a bike is hired for. If
the hire period is greater than 7 days, then a reduction of 25% is made. For every
bike hired a deposit of rupees 50.00 must be paid. Write a program to input the
season and number of days the bike is required for and output the hire charge
including the deposit.
Ans. import java.util.*;
public class Question37
{
static void main()
{
Scanner sc=new Scanner(System.in);
int days;
float rate=0, hireCharge;
String season;
System.out.print("Enter the season: ");
season=sc.nextLine();
System.out.print("Enter the number of days the bike is hired for: ");
days=sc.nextInt();
if(season.equals("Spring")) //equals is used to check equality of strings
rate=13.00f;
else if(season.equals("Summer"))
rate=19.50f;
else if(season.equals("Autumn"))
rate=8.75f;
else if(season.equals("Winter"))
rate=5.00f;
hireCharge=rate*days;
if(days>7)
hireCharge=hireCharge-25/100f*hireCharge;
hireCharge=50+hireCharge;
System.out.println("Hire Charge:"+hireCharge);
}
}
38. A cloth showroom has announced the following festival discounts on the purchase of
items, based on the total cost of the items purchased:
Write a program to input the total cost and compute and display the amount to be
paid by the customer after availing the discount. [ICSE 2006]
Ans. import java.util.*;
public class Question38
{
static void main()
{
Scanner sc=new Scanner(System.in);
int total;
float dis, amt;
System.out.print("Enter the Total Cost: ");
total=sc.nextInt();
if(total<=2000)
dis=5/100f*total;
else if(total>=2001 && total<=5000)
dis=25/100f*total;
else if(total>=5001 && total<=10000)
dis=35/100f*total;
else
dis=50/100f*total;
amt=total-dis;
System.out.println("Amount Payable:"+amt);
}
}
39. An electricity company charges their consumers according to the units consumed
per month according to the given tariff:
In addition to the above, every consumer has to pay Rs.200 as service charge per
month. Write a program to input the amount of units consumed and calculate the
total charges payable (bill) by the consumer.
Ans. import java.util.*;
public class Question39
{
static void main()
{
Scanner sc=new Scanner(System.in);
int units;
float rate, charge;
System.out.print("Enter the Total Cost: ");
units=sc.nextInt();
if(units<=100)
rate=2;
else if(units>100 && units<=200)
rate=1.80f;
else
rate=1.50f;
charge=200+rate*units;
System.out.println("Amount Payable:Rs "+charge);
}
}
40. A library charges a fine for books returned late. Following are the fines:
First five days : 40 paise per day.
Six to ten days : 65 paise per day.
Above ten days : 80 paise per day.
Design a program to calculate the fine assuming that a book is returned n days late.
[ICSE 1996]
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
float fine;
System.out.print("Enter the number of days late: ");
n=sc.nextInt();
if(n<=5)
fine=0.40f*n;
else if(n>=6 && n<=10)
fine=0.65f*n;
else
fine=0.80f*n;
System.out.println("Fine Payable:Rs "+fine);
}
}
41. Write a program to find the result of the following functions:
F(x)=4×x+y if x>0
F(x)= 4×x–y if x<0
Both x and y should be of float data type and should be taken as input.
Ans. import java.util.*;
public class Question41
{
static void main()
{
Scanner sc=new Scanner(System.in);
float x,y,f;
System.out.print("Enter the value of x and y: ");
x=sc.nextFloat();
y=sc.nextFloat();
if(x>0)
f=4*x+y;
else if(x<0)
f=4*x-y;
else
f=0;
System.out.println("Value of the function: "+f);
}
}
42. Write a program to input an integer and check whether it is a 5-digit number or not. If
it is, extract the central digit and print it.
Example:
INPUT: Enter an integer: 76549
OUTPUT: Central digit: 5
INPUT: Enter an integer: 12976
OUTPUT: Central digit: 9
INPUT: Enter an integer: 126
OUTPUT: Not a 5-digit number
Ans. import java.util.*;
public class Question42
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,d;
System.out.print("Enter an integer: ");
n=sc.nextInt();
if(n>=10000 && n<=99999)
{
d=(n/100)%10;
System.out.println("Central digit :"+d);
}
else
System.out.println("Not a 5-digit number");
}
}
43. Write a program to input an integer and check whether it is a 4-digit number or not. If
it is, find the sum of the first and last digit.
Example
INPUT: Enter an integer: 4765
OUTPUT: Sum of the first and last digit: 9
INPUT: Enter an integer: 7839
OUTPUT: Sum of the first and last digit: 16
INPUT: Enter an integer: 126
OUTPUT: Not a 4-digit number
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,f,l,s;
System.out.print("Enter an integer: ");
n=sc.nextInt();
if(n>=1000 && n<=9999)
{
f=n/1000; //first digit
l=n%10; //last digit
s=f+l;
System.out.println("Sum of first and last digit :"+s);
}
else
System.out.println("Not a 4-digit number");
}
}
44. Write a program to input an integer and check whether it is a 3-digit number or not. If
it is check whether the sum of the first and last digit is an even or an odd number.
Example
INPUT: Enter an integer: 476
OUTPUT: Sum of the first and last digit is an even number
INPUT: Enter an integer: 784OUTPUT: Sum of the first and last digit is an odd
number
INPUT: Enter an integer: 12
OUTPUT: Not a 3-digit number
Ans. import java.util.*;
public class Question44
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,f,l,s;
System.out.print("Enter an integer: ");
n=sc.nextInt();
if(n>=100 && n<=999)
{
f=n/100; //first digit
l=n%10; //last digit
s=f+l;
if(s%2==0)
System.out.println("Sum of the first and last digit is an even number");
else
System.out.println("Sum of the first and last digit is an odd number");
}
else
System.out.println("Not a 3-digit number");
}
}
45. Write a program to input an integer and check whether it is a 4-digit number or not. If
it is, divide it into two equal halves and find their sum.
Example
INPUT: Enter an integer: 4762
OUTPUT: Sum of the 2 halves: 109
[Hint: 47+62=109]
INPUT: Enter an integer: 9863
OUTPUT: Sum of the 2 halves: 161
[Hint: 98+63=161]
INPUT: Enter an integer: 12
OUTPUT: Not a 4-digit number
Ans. import java.util.*;
public class Question45
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,f,l,s;
System.out.print("Enter an integer: ");
n=sc.nextInt();
if(n>=1000 && n<=9999)
{
f=n/100; //first 2 digits
l=n%100; //last 2 digits
s=f+l;
System.out.println("Sum of the 2 halves:"+s);
}
else
System.out.println("Not a 4-digit number");
}
}
46. Write a program to input an integer and using ternary operator check whether
it is an even or an odd number.
Ans. import java.util.*;
public class Question46
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.print("Enter an integer: ");
n=sc.nextInt();
System.out.println((n%2==0)?"Even":"Odd");
}
}
47. Write a program to input an integer and using ternary operator check whether
it is a multiple of 5 or not.
Ans. import java.util.*;
public class Question47
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.print("Enter an integer: ");
n=sc.nextInt();
System.out.println((n%5==0)?"Multiple of 5":"Not a multiple of 5");
}
}
48. Write a program to input an integer and using ternary operator check whether
it is a positive number, negative number or a zero or not.
Ans. import java.util.*;
public class Question48
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.print("Enter an integer: ");
n=sc.nextInt();
System.out.println((n>0)?"Positive":(n<0)?"Negative":"Zero");
}
}
49. Write a program to input two integers and using ternary operator print the
larger among the two, in case both are equal it should display "Equal".
Ans. import java.util.*;
public class Question49
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.print("Enter 2 integers: ");
a=sc.nextInt();
b=sc.nextInt();
System.out.println((a>b)?"Largest="+a:(b>a)?"Largest="+b:"Equal");
}
}
50. Write a program to input two integers and if both the numbers are even find
their sum else find their product, using conditional operator only.
Ans. import java.util.*;
public class Question50
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b;
System.out.print("Enter 2 integers: ");
a=sc.nextInt();
b=sc.nextInt();
System.out.println((a%2==0&& b%2==0)?"Sum="+(a+b):"Product="+(a*b));
}
}
51. Write a program to input three integers and print the largest among the three
integers using ternary operator.
Ans. import java.util.*;
public class Question51
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,l;
System.out.print("Enter 3 integers: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
l=(a>b)?(a>c)?a:c:(b>c)?b:c;
System.out.println("Largest="+l);
}
}
53. Write a program to input two numbers and find their sum, difference or
product according to user’s choice (menu-driven).
Ans. import java.util.*;
public class Question53
{
static void main()
{
Scanner sc=new Scanner(System.in);
float a,b,c;
int ch;
System.out.println("Enter 2 numbers:");
a=sc.nextFloat();
b=sc.nextFloat();
System.out.println("MENU");
System.out.println("1. to find the SUM");
System.out.println("2. to find the DIFFERENCE");
System.out.println("3. to find the PRODUCT");
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{
case 1:
c=a+b;
System.out.println("Sum="+c);
break;
case 2:
c=a-b;
System.out.println("Difference="+c);
break;
case 3:
c=a*b;
System.out.println("Product="+c);
break;
default:
System.out.println("Invalid Choice!");
}
}
}
55. Write a menu-driven program to input a day number between 1 and 7 and print
the corresponding weekday, i.e. for 1 display Sunday, for 2 display Monday for 3
display Tuesday, etc. [ICSE 2002]
Ans. import java.util.*;
public class Question55
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter any day number between 1 to 7");
n=sc.nextInt();
switch(n)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid day number");
}
}
}
56. Write a menu driven program to input a month number between 1 and 12 and print the
corresponding month name, i.e. for 1 display January, for 2 display February for 3
display March, etc.
Ans. import java.util.*;
public class Question56
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter any month number between 1 to 12");
n=sc.nextInt();
switch(n)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid day number");
}
}
}
57. Write a program using switch-case to accept an integer number and print the last
digit in words.
For example
60. Write a program to input an integer and check whether it is a magic number or
not. A magic number is such a number whose continuous sum of the digits until
it forms a single digit is 1. For example, [55] =5+5 = [10] = 1+0 = [1], therefore 55 is
a magic number. (Remember no loop is to be used).
Ans. import java.util.*;
public class Question60
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter a number");
n=sc.nextInt();
if(n%9==1)
System.out.println("Magic Number");
else
System.out.println("Not a Magic Number");
}
}
61. Write a program to input 3 integers and using conditional operator print the
largest among them.
Ans. import java.util.*;
public class Question61
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,l;
System.out.print("Enter 3 integers: ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
l=(a>b)?(a>c)?a:c:(b>c)?b:c;
System.out.println("Largest="+l);
}
}
62. Write a program to input an integer and check whether it is a 4-digit, 3-digit, 2-
digit or single-digit positive number or not. Do not use any logical operator in the
program.
Ans. import java.util.*;
public class Question62
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
System.out.print("Enter an integer: ");
a=sc.nextInt();
if(a>=10)
{
if(a<=99)
System.out.print("Two Digit Number");
else if(a<=999)
System.out.print("Three Digit Number");
else if(a<=9999)
System.out.print("Four Digit Number");
else
System.out.print("Not a valid 2-digit, 3-digit or 4-digit Number");
}
else
System.out.print("Not a valid 2-digit, 3-digit or 4-digit Number");
}
}
63. Write a menu-driven program to check whether a number is i) even or odd, ii)
multiple of 17 or not, iii) two-digit number or not.
Ans. import java.util.*;
public class Question63
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a;
int ch;
System.out.println("Enter a number:");
a=sc.nextInt();
System.out.println("MENU");
System.out.println("1. to check EVEN or ODD");
System.out.println("2. to check MULTIPLE OF 17 or not");
System.out.println("3. to check TWO DIGIT NUMBER or not");
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{
case 1:
if(a%2==0)
System.out.println("Even");
else
System.out.println("Odd");
break;
case 2:
if(a%17==0)
System.out.println("Multiple of 17");
else
System.out.println("Not Multiple of 17");
break;
case 3:
if(a>=10 && a<=99 || a>=-99 && a<=-10)
System.out.println("Two digit number");
else
System.out.println("Not a two digit number");
break;
default:
System.out.println("Invalid Choice!");
}
}
}
64. Write a program to input an integer and check whether it is positive, negative
or a zero, using conditional operator only.
Ans. import java.util.*;
public class Question64
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n;
System.out.print("Enter an integer: ");
n=sc.nextInt();
System.out.println((n>0)?"Positive":(n<0)?"Negative":"Zero");
}
}
65. Write a program to input 5 real numbers and print only those numbers which
are less than their average.
Ans. import java.util.*;
public class Question65
{
static void main()
{
Scanner sc=new Scanner(System.in);
float a,b,c,d,e,av;
System.out.print("Enter 5 real numbers: ");
a=sc.nextFloat();
b=sc.nextFloat();
c=sc.nextFloat();
d=sc.nextFloat();
e=sc.nextFloat();
av=(a+b+c+d+e)/5;
if(a<av)
System.out.println(a+" is less than "+av);
if(b<av)
System.out.println(b+" is less than "+av);
if(c<av)
System.out.println(c+" is less than "+av);
if(d<av)
System.out.println(d+" is less than "+av);
if(e<av)
System.out.println(e+" is less than "+av);
}
}
66. Write a program to input three integers and check whether it forms a
Pythagorean triplet or not. A set of three integers is said to be a Pythagoren triplet
if the sum of the squares of any two integers is equal to square of the third integer.
Example, (3, 4, 5), (5, 12, 13), and (7, 24, 25). [ICSE 1994]
Ans. import java.util.*;
public class Question66
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println("Enter 3 numbers:");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a*a==b*b+c*c || b*b==a*a+c*c || c*c==a*a+b*b)
System.out.println("Pythagorean Triplet");
else
System.out.println("Not a Pythagorean Triplet");
}
}
67. Write a program to find the gross salary of an employee for the following allowances
and deductions. Use meaningful variables with the class name Employee and Basic Pay
as an input.
[ICSE 2005]
Ans. //Question 67
import java.util.*;
public class Employee
{
static void main()
{
Scanner sc=new Scanner(System.in);
double basicPay,da,hra,pf,netPay,grossPay;
System.out.println("Enter the Basic Pay:");
basicPay=sc.nextDouble();
da=25/100.0*basicPay;
hra=15/100.0*basicPay;
pf=8.33/100*basicPay;
netPay=basicPay+da+hra;
grossPay=netPay-pf;
System.out.println("Gross Pay="+grossPay);
}
}
68. To foster a sense of water conservation, the water department has an annual water
conservation tax policy. The taxes are based on the water consumption of the consumer.
The tax rates are as follows:
Ans. import java.util.*;
public class Qusetion68
{
static void main()
{
Scanner sc=new Scanner(System.in);
int consumed;
double tax;
System.out.println("Enter water consumed in Gallons:");
consumed=sc.nextInt();
if(consumed<=45)
tax=0;
else if(consumed<=75)
tax=475.00;
else if(consumed<=125)
tax=750.00;
else if(consumed<=200)
tax=1225.00;
else if(consumed<=350)
tax=1650.00;
else
tax=2000.00;
System.out.println("Tax Payable="+tax);
}
}
69. Write a program to input the water consumed annually in gallons and output the tax
payable. [ICSE 2003]
Ans. Do it yourself.
70. Write a program using a function called area( ) to compute the area of a :
i) circle(π*r2) where π = 3.14
ii) square(side*side)
iii) rectangle (length*breadth)
Display the menu to output the area as per User’s choice. [ICSE 2005]
Ans. import java.util.*;
public class Question70
{
static void area()
{
Scanner sc=new Scanner(System.in);
int ch;
float radius,length,breadth,side,area;
System.out.println("MENU");
System.out.println("1.To find the area of a circle");
System.out.println("2.To find the area of a square");
System.out.println("3.To find the area of a rectangle");
System.out.println("Enter your choice");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter the radius of the Circle:");
radius=sc.nextFloat();
area=3.14f*radius*radius;
System.out.println("Area="+area);
break;
case 2:
System.out.println("Enter the side of the Square:");
side=sc.nextFloat();
area=side*side;
System.out.println("Area="+area);
break;
case 3:
System.out.println("Enter the length & breadth of the Rectangle:");
length=sc.nextFloat();
breadth=sc.nextFloat();
area=length*breadth;
System.out.println("Area="+area);
break;
default:
System.out.println("Invalid Choice!");
}
}
}
71. Write a program to input an integer and check whether it is a three-digit number or
not. If it is print the largest digit in the number.
Example
INPUT: Enter an integer: 476
OUTPUT: Largest digit: 7
INPUT: Enter an integer: 986
OUTPUT: Largest digit: 9
INPUT: Enter an integer: 12
OUTPUT: Not a 3 digit-number
Ans. import java.util.*;
public class Question71
{
static void area()
{
Scanner sc=new Scanner(System.in);
int a,first,middle,last;
System.out.println("Enter an integer:");
a=sc.nextInt();
if (a>=100 && a<=999)
{
first=a/100;
middle=(a/10)%10;
last=a%10;
if(first>middle && first>last)
System.out.println("Largest Digit:"+first);
else if(middle>first && middle>last)
System.out.println("Largest Digit:"+middle);
else
System.out.println("Largest Digit:"+last);
}
else
System.out.println("Not a valid 3-digit number");
}
}
Chapter 7: Repetitive Structures
Practice Questions187
A. Answer the following questions:
1. Explain the term loop with an example. [ICSE 2005]
Ans. Loop is a repetitive structure that allows a group of statements to be executed
repeatedly. The loop structure executes as long as the given test-expression is executed.
For example, the following for loop will execute 10 times displaying the first 10 natural
numbers.
int i;
for( i =1 ; i<=10 ; i++)
{
System.out.print(i+" ");
}
The loop starts with the initial value of 1 for ‘i' and iterates every time increasing the value
of ‘i' by 1 as long as the value of ‘i’ is less than or equal to 10. The loop body in the mean
while displays each value of ‘i’ , thus giving the output as:
1 2 3 4 5 6 7 8 9 10
6. Give an example to show how multiple initialization and updation are performed
in a for loop.
Ans. For multiple initialization and multiple updation in a for loop they are separated
by comma (,). The following example shows how multiple initialization and updation is
performed in a for loop.
9. State one similarity and one difference between while and for loops. [ICSE 2009]
Ans. Similarity: The similarity between while and for loop is that, both the loops are
entry-controlled loops..
Difference: The difference between while and for loop is that, initialization in while
loop is outside the loop structure, whereas initialization of for loop is within the loop
structure.
10. What is meant by an infinite loop? Give one example. [ICSE 2008]
Ans. Infinite loop is a loop which executes indefinitely i.e. the given test-expression is
forever evaluated to true. For example,
for(i=1;i>0;i++)
{
System.out.println(i);
}
The loop executes infinitely because the value of ‘i' is always greater than 0.
11. Give the general syntax of a while loop. How do you create infinite loops using a
while loop structure?
Ans. The general syntax of while loop is:
while (condition or test-expression)
{
//body of the loop;
}
The easiest way of creating an infinite loop using while loop is:
while(true)
{
//body of the loop
}
12. Give the general syntax of a do-while loop. How do you create infinite loops
using do-while loop structure?
Ans. The general syntax of do-while loop is:
do
{
//body of the loop;
} while (condition or test-expression)
The easiest way of creating an infinite loop using while loop is:
do
{
//body of the loop
} while(true);
13. Compare loops according to its usage.
Ans. The for loop is appropriate when you know in advance how many times the loop
will be executed i.e. the first and the last limit is already known. The other two loops
while and do-while loops are more suitable in situations when it is not known in advance
when the loop will terminate. The while should be preferred when you may not want to
execute the body-of-the-loop even once (in case the test-expression is false), and the do-
while loop should be preferred when you’re sure you want to execute the body-of-the-
loop at least once.
14. What are nested loops? Give an example of a nested for loop to show its
functionality.
Ans. A loop within a loop is called a nested loop. The following example shows how
nested for loop works:
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println( );
}
The output received for the above program fragment is:
1
12
123
1234
12345
15. Name two jump statements and their use. [ICSE 2010]
Ans. The two jump statements in Java are break and continue. Whereas break
statement is used to exit from the loop or switch block, the continue statement is used to
skip the remaining statements in a loop and force the next iteration.
16. Explain the meaning of break and continue statements. [ICSE 2005, 2008]
Ans. The break statement is used to exit from the loop or switch block, the continue
statement is used to skip the remaining statements in a loop and force the next iteration.
17. Explain how break statement works in a nested loop. Also give an example to
show how continue statement works in a nested loop.
Ans. The break statement is used to exit from the nested loop in a nested loop of which it
is a content.
Example of continue statement:
for(x=1;x<=2;x++)
{
for(y=1; y<=4 ; y++)
{
if(y==3)
continue;
System.out.println(x+" \t "+y);
}
System.out.println("x="+x);
}
The output for the above code fragment would be,
1 1
1 2
1 4
x=1
2 1
2 2
2 4
x=2
As you can see whenever the value of y reaches 3 it skips the statements only within the
inner loop but the execution of the outer loop continues remaining same thus
System.out.println("x="+x); do get executed as it is actually present only within the
outer loop.
2. Analyze the following program segment and determine how many times the body
of loop will be executed (show the working). [ICSE 2009]
x=5; y=50;
while(x<=y)
{
y=y/x;
System.out.println(y);
}
Ans. Working:
x y x<=y y=y/x System.out.println(y)
5 50 true 10 10
5 10 true 2 2
5 2 false --- ---
The loop will iterate for 2 times.
3. Convert the following segment into equivalence for loop. [ICSE 2007]
int i=0;
while(i<=20)
{
System.out.print(i+" ");
i++;
}
Ans. int i;
for(i=0;i<=20;i++)
{
System.out.print(i+" ");
}
9. Write a program to find the sum of all 3-digit even natural numbers.
Ans. public class Question9
{
static void main()
{
int i,s=0;
for(i=100;i<=998;i+=2)
{
s=s+i;
}
System.out.println("Sum of all 3-digit even natural numbers="+s);
}
}
10. Write a program to find the sum of all 3 digit odd natural numbers, which are
multiples of 5.
Ans. public class Question10
{
static void main()
{
int i,s=0;
for(i=101;i<=999;i+=2)
{
if(i%5==0)
s=s+i;
}
System.out.println("Sum="+s);
}
}
11. Write a program to input an integer and find its factorial. Factorial of a number
is the product of b) Write programs to display the following series:
Ans. import java.util.*;
public class Question11
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n;
long f=1;
System.out.print("Enter an integer:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("Factorial ="+f);
}
}
12. Write a program to input an integer and print its factors.
For Example,
INPUT: INPUT:
Enter an integer: 12 Enter an integer:10
OUTPUT: OUTPUT:
Factors: 1 2 3 4 6 12 Factors: 1 2 5 10
Ans. import java.util.*;
public class Question12
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n;
System.out.print("Enter an integer:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(n%i==0)
System.out.print(i+" ");
}
}
}
13. Write a program to input an integer and count the number of factors.
Ans. import java.util.*;
public class Question13
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,c=0;
System.out.print("Enter an integer:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
System.out.print("Number of Factors="+c);
}
}
14. Write a program to input an integer and check whether it is a prime number or
not. (Remember, prime number has 2 factors).
Ans. import java.util.*;
public class Question14
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,c=0;
System.out.print("Enter an integer:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
System.out.print("Prime Number");
else
System.out.print("Not a Prime Number");
}
}
16. Write a program to input 10 integers and find the sum of even numbers only.
Ans. import java.util.*;
public class Question16
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,s=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(n%2==0)
s=s+n;
}
System.out.print("Sum of even numbers="+s);
}
}
17. Write a program to input 10 integers and find the sum of two-digit as well as
three-digit numbers separately.
Ans. import java.util.*;
public class Question17
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,s1=0,s2=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(n>=10 && n<=99)
s1=s1+n;
else if(n>=100 && n<=999)
s2=s2+n;
}
System.out.println("Sum of 2-digit numbers="+s1);
System.out.println("Sum of 3-digit numbers="+s2);
}
}
18. Write a program to input 10 integers and display the largest integer.
Ans. import java.util.*;
public class Question18
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,l=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
l=n;
else if(n>l)
l=n;
}
System.out.println("Largest Number="+l);
}
}
19. Write a program to input 10 integers and display the largest as well as the
smallest integer.
Ans. import java.util.*;
public class Question19
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,l=0,s=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
s=l=n;
if(n>l)
l=n;
if(n<s)
s=n;
}
System.out.println("Largest Number="+l);
System.out.println("Smallest Number="+s);
}
}
20. Write a program to input 10 integers and display the largest even integer. In
case there is no even integer, it should print "No even integer found".
Ans. import java.util.*;
public class Question20
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,l=0,f=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(n%2==0)
{
if(f==0)
l=n;
f=1;
if(n>l)
l=n;
}
}
if(f==1)
System.out.println("Largest Even Number="+l);
else
System.out.println("No even integer found");
}
}
21. Write a program to input 10 integers and display the largest even and smallest
odd integer.
Ans. import java.util.*;
public class Question21
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,l=0,f1=0,f2=0,s=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(n%2==0)
{
if(f1==0)
{
l=n;
f1=1;
}
if(n>l)
l=n;
}
else
{
if(f2==0)
{
s=n;
f2=1;
}
if(n<s)
s=n;
}
}
if(f1==1)
System.out.println("Largest Even Number="+l);
else if(f1==0)
System.out.println("No even integer found");
if(f2==1)
System.out.println("Smallest Odd Number="+s);
else if(f2==0)
System.out.println("No odd integer found");
}
}
22. Write a program to input 10 integers and check whether all the entered numbers
are even numbers or not.
Ans. import java.util.*;
public class Question22
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,f=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(n%2!=0)
f=1;
}
if(f==0)
System.out.println("All are Even Numbers");
else
System.out.println("All are not Even Numbers");
}
}
23. Write a program to input 10 integers and check whether all the entered numbers
are odd numbers or not.
Ans. import java.util.*;
public class Question23
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,f=0;
System.out.println("Enter 10 integers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(n%2==0)
f=1;
}
if(f==0)
System.out.println("All are Odd Numbers");
else
System.out.println("All are not Odd Numbers");
}
}
24. Write a program to input 10 integers and check whether all the entered numbers
are same or not.
For Example,
INPUT:
Enter 10 numbers: 10 12 13 234 45 34 67 78 76 12
OUTPUT:
All numbers are not same.
INPUT:
Enter 10 numbers: 12 12 12 12 12 12 12 12 12 12
OUTPUT:
All numbers are same.
Ans. import java.util.*;
public class Question24
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,f=0,l=0;
System.out.println("Enter 10 numbers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
l=n;
if(n!=l)
f=1;
}
if(f==0)
System.out.println("All numbers are same");
else
System.out.println("All numbers are not same");
}
}
25. Write a program to input 10 integers and check whether the entered numbers
are in ascending order or not.
For Example,
INPUT:
Enter 10 numbers: 10 12 13 25 45 55 67 78 106 122
OUTPUT:
The numbers are in ascending order.
INPUT:
Enter 10 numbers: 25 34 56 67 12 32 43 21 23 111
OUTPUT:
The numbers are not in ascending order.
Ans. import java.util.*;
public class Question25
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,f=0,l=0;
System.out.println("Enter 10 numbers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
l=n;
else
{
if(n<l)
f=1;
l=n;
}
}
if(f==0)
System.out.println("All numbers are in ascending order");
else
System.out.println("All numbers are not in ascending order");
}
}
26. Write a program to calculate and print the sum of odd numbers and the sum of
even numbers for the first n natural numbers. The integer n is to be entered by the
user.
[ICSE-2006]
Ans. import java.util.*;
public class Question26
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,s1=0,s2=0;
System.out.println("Enter a number:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(i%2==0)
s1=s1+i;
else
s2=s2+i;
}
System.out.println("Sum of even numbers="+s1);
System.out.println("Sum of odd numbers="+s2);
}
}
27. Write programs to find the sum of each of the following series:
i) s=1*2+2*3+3*4+…+9*10
ii) s=1*2+3*4+5*6+…+9*10
iii) s=1*3+2*4+3*5+…+9*11
iv) s=1–2+3–4+5–6+…+19–20
v) s= 1+1/2+1/3+1/4+1/5+…+1/10
vi) s= 1/2+2/3+3/4+4/5+…+9/10
vii) s= 1-1/2+1/3-1/4+1/5-…-1/10
Ans. public class Question27
{
static void i()
{
int i,s=0;
for(i=1;i<=9;i++)
{
s=s+i*(i+1);
}
System.out.println("Sum ="+s);
}
static void ii()
{
int i,s=0;
for(i=1;i<=9;i+=2)
{
s=s+i*(i+1);
}
System.out.println("Sum ="+s);
}
static void iii()
{
int i,s=0;
for(i=1;i<=9;i++)
{
s=s+i*(i+2);
}
System.out.println("Sum ="+s);
}
static void iv()
{
int i,s=0;
for(i=1;i<=19;i+=2)
{
s=s+i-(i+1);
}
System.out.println("Sum ="+s);
}
static void v()
{
int i;
float s=0;
for(i=1;i<=10;i++)
{
s=s+(float)1/i;
}
System.out.println("Sum ="+s);
}
static void vi()
{
int i;
float s=0;
for(i=1;i<=9;i++)
{
s=s+(float)i/(i+1);
}
System.out.println("Sum ="+s);
}
static void vii()
{
int i;
float s=0;
for(i=1;i<=9;i++)
{
if(i%2==0)
s=s-(float)i/(i+1);
else
s=s+(float)i/(i+1);
}
System.out.println("Sum ="+s);
}
}
28. Write a program to find the sum of 1st 10 numbers of Fibonacci series, i.e.
1,1,2,3,5, 8,13…. Lucas series is such a series which starting from 1 and 1, and
subsequent numbers are the sum of the previous two numbers.
Ans. public class Question28
{
static void main()
{
int i,a=1,b=0,c;
System.out.println("Fibonacci series =");
for(i=1;i<=10;i++)
{
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}
29. Write a program to print the first 15 numbers of the Pell series. Pell series is
such a series which starts from 1 and 2, and subsequent numbers are the sum of
twice the previous number and the number previous to the previous number. Pell
series: 1, 2, 5, 12, 29, 70, 169, 408, 985, 2378, 5741, 13860, …
Ans. public class Question29
{
static void main()
{
int i,a=1,b=0,c;
System.out.println("Pell series =");
for(i=1;i<=15;i++)
{
c=a+2*b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}
30. Write a program to find the sum of 1st 10 numbers of Lucas series, i.e.
2,1,3,4,7,11, 18,…Lucas series is such a series which starting from 2 and 1, and
subsequent numbers are the sum of the previous two numbers.
Ans. public class Question30
{
static void main()
{
int i,a=2,b=1,c;
System.out.println("Pell series =");
System.out.print(a+" "+b+" ");
for(i=1;i<=8;i++)
{
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}
31. Write a program to input an integer and check whether it is perfect, abundant
or deficient number. If the sum of the factors excluding itself is equal to that
number it is perfect, if greater than that number it is abundant and if less than that
number it is deficient number.
Ans. import java.util.*;
public class Question31
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,s=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
for(i=1;i<n;i++)
{
if(n%i==0)
s+=i;
}
if(s==n)
System.out.println("Perfect Number");
else if(s<n)
System.out.println("Deficient Number");
else
System.out.println("Abundant Number");
}
}
32. Write a program to input two integers and check whether it forms an amicable
pair or not. An amicable pair is such that the sum of the factors excluding itself of
one number is the other number and sum of the factors excluding itself of the other
number is this number.
Example, (220, 284). Since sum of factors excluding itself of:
220= 1+2+4+5+10+11+20+22+ 44+55+110=284
284= 1+ 2+4+71+142=220.1
Ans. import java.util.*;
public class Question32
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,a,b,s1=0,s2=0;
System.out.println("Enter 2 integers:");
a=sc.nextInt();
b=sc.nextInt();
for(i=1;i<a;i++)
{
if(a%i==0)
s1+=i;
}
for(i=1;i<b;i++)
{
if(b%i==0)
s2+=i;
}
if(s1==b && s2==a)
System.out.println("Amicable Pair");
else
System.out.println("Not an amicable pair");
}
}
ass
33. Write a program to pass an integer as argument and find the sum of its digits.
Ans. public class Question33
{
static void main(int n)
{
int d,s=0;
while(n!=0)
{
d=n%10;
s=s+d;
n=n/10;
}
System.out.println("Sum of the digits="+s);
}
}
34. Write a program to pass an integer as argument and find the sum of odd digits
and even digits separately.
Ans. public class Question34
{
static void main(int n)
{
int d,se=0,so=0;
while(n!=0)
{
d=n%10;
if(d%2==0)
se=se+d;
else
so=so+d;
n=n/10;
}
System.out.println("Sum of the even digits="+se);
System.out.println("Sum of the odd digits="+so);
}
}
35. Write a program to pass an integer as argument and find the average of its
digits.
Ans. public class Question35
{
static void main(int n)
{
int d,s=0,c=0;
float av;
while(n!=0)
{
d=n%10;
s=s+d;
c++;
n=n/10;
}
av=(float)s/c;
System.out.println("Average of its digits="+av);
}
}
36. Write a program to pass an integer as argument and print the largest as well as
smallest digit.
Ans. public class Question36
{
static void main(int n)
{
int d,s=0,l=0,f=0;
while(n!=0)
{
d=n%10;
if(f==0)
{
l=s=d;
f=1;
}
if (d>l)
l=d;
if(d<s)
s=d;
n=n/10;
}
System.out.println("Largest digit="+l);
System.out.println("Smallest digit="+s);
}
}
37. Write a program to pass an integer as argument and print the second largest
digit.
Ans. public class Question37
{
static void main(int n)
{
int d,s=0,l=0,f=0,sl=0,t=n;
while(n!=0)
{
d=n%10;
if(f==0)
{
l=d;
f=1;
}
if (d>l)
l=d;
n=n/10;
}
f=0;
while(t!=0)
{
d=t%10;
if(d!=l)
{
if(f==0)
{
sl=d;
f=1;
}
if(d>sl)
sl=d;
}
t=t/10;
}
System.out.println("Second Largest digit="+sl);
}
}
38. Write a program to input an integer and remove all the even digits from it.
Ans. import java.util.*;
public class Question38
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,d,c=0,s=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
while(n!=0)
{
d=n%10;
if(d%2!=0)
s=s+d*(int)Math.pow(10,c++);
n=n/10;
}
System.out.println("New Number="+s);
}
}
39. Write a program to input an integer and remove all the even digits from it.
For Example,
INPUT: Enter an integer: 1234
OUPUT:
13
Ans. Same as question38.
40. Write a program to pass an integer as argument and form a new number by
having the digits arranged in ascending order.
Ans. public class Question40
{
static void main(int n)
{
int d,s=0,c=0,i,t;
for(i=9;i>=0;i--)
{
t=n;
while(t!=0)
{
d=t%10;
if(d==i)
s=s+d*(int)Math.pow(10,c++);
t=t/10;
}
}
System.out.println("Digits in ascending order="+s);
}
}
41. Write a program to input an integer and check whether all digits in it are same
or not.
Ans. import java.util.*;
public class Question41
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,n,last,f=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
last=n%10;
while(n!=0)
{
d=n%10;
if(d!=last)
f=1;
n=n/10;
}
if(f==0)
System.out.println("All digits are same");
else
System.out.println("All digits are not same");
}
}
42. Write a program to input an integer and check whether all digits in it are even
digits or not.
Ans. import java.util.*;
public class Question42
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,n,f=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
while(n!=0)
{
d=n%10;
if(d%2!=0)
f=1;
n=n/10;
}
if(f==0)
System.out.println("All digits are even");
else
System.out.println("All digits are not even");
}
}
43. Write a program to input an integer and check whether all digits are unique or
not.
Ans. import java.util.*;
public class Question43
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d1,d2,n,t,f=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
while(n!=0)
{
d1=n%10;
t=n/10;
while(t!=0)
{
d2=t%10;
if(d1==d2)
f=1;
t=t/10;
}
n=n/10;
}
if(f==0)
System.out.println("All digits are unique");
else
System.out.println("All digits are not unique");
}
}
44. Write a program to input an integer and check whether all are prime digits or
not.
Ans. import java.util.*;
public class Question44
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,n,f=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
while(n!=0)
{
d=n%10;
if(d!=2 && d!=3 && d!=5 && d!=7)
f=1;
n=n/10;
}
if(f==0)
System.out.println("All digits are prime");
else
System.out.println("All digits are not prime");
}
}
45. Write a program to input an integer and check whether al digits are in
ascending order or not.
Ans. import java.util.*;
public class Question45
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d1,d2,n,f=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
while(n>9)
{
d2=n%10;
d1=(n/10)%10;
if(d1>d2)
f=1;
n=n/10;
}
if(f==0)
System.out.println("All digits are in ascending order");
else
System.out.println("All digits are not in ascending order");
}
}
46. Write a program to input an integer and check whether all digits are in
desending order or not.
Ans. import java.util.*;
public class Question46
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d1,d2,n,f=0;
System.out.println("Enter an integer:");
n=sc.nextInt();
while(n>9)
{
d2=n%10;
d1=(n/10)%10;
if(d1<d2)
f=1;
n=n/10;
}
if(f==0)
System.out.println("All digits are in descending order");
else
System.out.println("All digits are not in descending order");
}
}
if((n*n)%(int)Math.pow(10,c)==n)
System.out.println("Automorphic Number");
else if((n*n*n)%(int)Math.pow(10,c)==n)
System.out.println("Trimorphic Number");
else if((3*n*n)%(int)Math.pow(10,c)==n)
System.out.println("Tri-automorphic Number");
}
}
49. Write a program to input an integer and check whether it is a happy number or
not. If you iterate the process of summing the squares of the digits of a number and
if this process terminates in 1, then the original number is called a happy number.
For example 7=> (72) =49=> (42+92) =97=>(92+72)=130 =>(12 +32+02)=10
=>(12+02)=1.
Ans. import java.util.*;
public class Question49
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,s,n;
System.out.println("Enter an integer:");
n=sc.nextInt();
do
{
s=0;
while(n!=0)
{
d=n%10;
s=s+d*d;
n=n/10;
}
n=s;
}while(n>9);
if(n==1)
System.out.println("Happy Number");
else
System.out.println("Not a Happy Number");
}
}
50. Write a program to input an integer and check whether it is a magic number or
not. If you iterate the process of summing the squares of the digits of a number and
if this process terminates in 1, then the original number is called a magic number.
For example 55=> (5+5)=10=>(1+0)=1.
Ans. import java.util.*;
public class Question50
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,s,n;
System.out.println("Enter an integer:");
n=sc.nextInt();
do
{
s=0;
while(n!=0)
{
d=n%10;
s=s+d;
n=n/10;
}
n=s;
}while(n>9);
if(n==1)
System.out.println("Magic Number");
else
System.out.println("Not a Magic Number");
}
}
51. Write a program to input an integer and check whether it is Harshad or Niven
number or not. A number is said to be Harshad if it is divisible by the sum of the
digits of that number, example 126 and 1729.
Ans. import java.util.*;
public class Question51
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,s=0,n,t;
System.out.println("Enter an integer:");
n=sc.nextInt();
t=n;
while(t!=0)
{
d=t%10;
s=s+d;
t=t/10;
}
if(n%s==0)
System.out.println("Harshad Number");
else
System.out.println("Not a Harshad Number");
}
}
52. Write a program to input a number and check whether it is a Kaprekar number
or not. Take a positive whole number n that has d number of digits. Take the square
n and separate the result into two pieces: a right-hand piece that has d digits and a
left-hand piece that has either d or d–1 digits. Add these two pieces together. If the
result is n, then n is a Kaprekar number. Examples are:
9 (92 = 81, 8 + 1 = 9), 45 (452 = 2025, 20 + 25 = 45) and 297 (2972 = 88209, 88 + 209 =
297).
Ans. import java.util.*;
public class Question52
{
static void main()
{
Scanner sc=new Scanner(System.in);
int c=0,n,t,first,last;
System.out.println("Enter an integer:");
n=sc.nextInt();
t=n;
while(t!=0)
{
c++;
t=t/10;
}
first=(n*n)/(int)Math.pow(10,c);
last=(n*n)%(int)Math.pow(10,c);
if(first+last==n)
System.out.println("Kaprekar Number");
else
System.out.println("Not a Kaprekar Number");
}
}
53. Write a program to input two integers and find their Least Common Multiple
(LCM).
For Example,
INPUT:
Enter 2 integers:
12
8
OUTPUT:
LCM = 24
Ans. import java.util.*;
public class Question53
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,a,b;
System.out.println("Enter 2 integers:");
a=sc.nextInt();
b=sc.nextInt();
for(i=a;i<=a*b;i++)
{
if(i%a==0 && i%b==0)
break;
}
System.out.println("L.C.M.="+i);
}
}
54. Write a program to input two integers and find their Highest Common
Factor(HCF).
For Example,
INPUT:
Enter 2 integers:
12
8
OUTPUT:
HCF = 4
Ans. import java.util.*;
public class Question54
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,a,b;
System.out.println("Enter 2 integers:");
a=sc.nextInt();
b=sc.nextInt();
for(i=a;i>=1;i--)
{
if(a%i==0 && b%i==0)
break;
}
System.out.println("H.C.F.="+i);
}
}
56. Write a program to calculate and print the sum of odd numbers and the sum of
even numbers for the first n natural numbers. The integer n is to be entered by the
user.
[ICSE 2006]
Ans. import java.util.*;
public class Question56
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,s1=0,s2=0;
System.out.println("Enter a number:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(i%2==0)
s1=s1+i;
else
s2=s2+i;
}
System.out.println("Sum of even numbers="+s1);
System.out.println("Sum of odd numbers="+s2);
}
}
57. Write a menu-driven class to accept a number from the user and check whether
it is a palindrome or a perfect number. [ICSE 2008]
i) Palindrome number– (a number is palindrome which when read in reverse order
is same as read in the right order). Example: 11, 101, 151, etc.
ii) Perfect number– (a number is called Perfect if it is equal to the sum of its factors
other than the number itself). Example: 6=1+2+3 [ICSE 2009]
Ans. import java.util.*;
public class Question57
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,n,ch,t,s=0,i;
System.out.println("Enter a number:");
n=sc.nextInt();
System.out.println("MENU");
System.out.println("1. to check whether it is a Palindrome Number");
System.out.println("2. to check whether it is a Perfect Number");
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{
case 1:
t=n;
while(t!=0)
{
d=t%10;
s=s*10+d;
t=t/10;
}
if(s==n)
System.out.println("Palindrome Number");
else
System.out.println("Not a Palindrome Number");
break;
case 2:
for(i=1;i<n;i++)
{
if(n%i==0)
s+=i;
}
if(s==n)
System.out.println("Perfect Number");
else
System.out.println("Not a Perfect Number");
break;
default:
System.out.println("Invalid Choice!");
}
}
}
193
58. Write a menu-driven program to accept a number from the user and check
whether it is ‘BUZZ’ number or to accept any two numbers and print the ‘GCD’ of
them. [ICSE 2009]
i) A BUZZ number is the number which either ends with 7 or divisible by 7.
ii) GCD (Greatest Common Divisor) of two integers is calculated by continued
division method.
Divide the larger number by the smaller; the remainder then divides the previous
divisor. The process is repeated till the remainder is zero. The divisor then results
the GCD.
Ans. import java.util.*;
public class Question58
{
static void main()
{
Scanner sc=new Scanner(System.in);
int d,n,ch,r;
System.out.println("MENU");
System.out.println("1. to check for BUZZ Number");
System.out.println("2. to find the GCD of two numbers");
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number:");
n=sc.nextInt();
if(n%10==7 || n%7==0)
System.out.println("BUZZ Number");
else
System.out.println("Not a BUZZ Number");
break;
case 2:
System.out.println("Enter 2 numbers:");
n=sc.nextInt();
d=sc.nextInt();
do
{
r=n%d;
if(r!=0)
{
n=d;
d=r;
}
}while(r!=0);
System.out.println("GCD="+d);
break;
default:
System.out.println("Invalid Choice!");
}
}
}
59. Write a menu-driven program to accept a number and check and display
whether it is a prime number or not OR an automorphic number or not (Use
switch-case statement).
i) Prime number: A number is said to be a prime number if it is divisible only by 1
and itself and not by any other number. Example: 3,5,7,11,13, etc.
ii) Automorphic number: An automorphic number is the number which is
contained in the last digit(s) of its square.
Example: 25 is an automorphic number as its square is 625 and 25 is present as the
last two digits.
Ans. import java.util.*;
public class Question59
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,t,c=0,n,ch,r;
System.out.println("MENU");
System.out.println("1. to check for Prime Number");
System.out.println("2. to check for Automorphic Number");
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
System.out.println("Prime Number");
else
System.out.println("Not a Prime Number");
break;
case 2:
System.out.println("Enter a number:");
n=sc.nextInt();
t=n;
while(t!=0)
{
c++;
t=t/10;
}
if((n*n)%(int)Math.pow(10,c)==n)
System.out.println("Automorphic Number");
else
System.out.println("Not an Automorphic Number");
break;
default:
System.out.println("Invalid Choice!");
}
}
}
60. Write a program to input 10 integers and print the second largest number.
Assume that there is at least one second largest number in the given set of integers.
For example,
INPUT:
Enter 10 integers:
12 35 46 22 34 56 78 89 23 21
OUTPUT:
Second Largest Integer: 78
Ans. import java.util.*;
public class Question60
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,n,l=0,sl=0;
System.out.println("Enter 10 numbers:");
for(i=1;i<=10;i++)
{
n=sc.nextInt();
if(i==1)
l=n;
else
{
if(n>l)
{
sl=l;
l=n;
}
else if(sl==0)
sl=n;
else if(n>sl)
sl=n;
}
}
System.out.println("Second Largest Number="+sl);
}
}
62. Write a program to calculate and print the sum of each of the following series:
i) Sum (S) = 2 – 4 + 6 – 8 + ………. –20
ii) Sum (S) =x/2+x/5+x/8+x/11+…+x/20 where x is to be taken as input.
Ans. import java.util.*;
public class Question62
{
static void sumi()
{
int i,s=0;
for(i=2;i<=20;i+=2)
{
if(i%4==0)
s=s-i;
else
s=s+i;
}
System.out.println("Sum="+s);
}
static void sumii()
{
int i,x;
float s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of x:");
x=sc.nextInt();
for(i=2;i<=20;i+=3)
{
s=s+(float)x/i;
}
System.out.println("Sum="+s);
}
}
63. Write a program to find the sum of series, taking the value of ‘a’ and ‘n’ from
the user.
s= a/2+a/3+a/4+…+a/n
Ans. import java.util.*;
public class Question63
{
static void main()
{
int i,n,a;
float s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of a and n:");
a=sc.nextInt();
n=sc.nextInt();
for(i=2;i<=n;i++)
{
s=s+(float)a/i;
}
System.out.println("Sum="+s);
}
}
64. Write a program to find the sum of series, taking the value of ‘a’ and ‘n’ from
the user.
s= a + 1/2+a + 3/4+a + 5/6+a + 7/8+... up to n terms
Ans. import java.util.*;
public class Question64
{
static void main()
{
int i,n,a,p=1;
float s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of a and n:");
a=sc.nextInt();
n=sc.nextInt();
for(i=1;i<=n;i++)
{
s=s+(float)(a+p)/(p+1);
p=p+2;
}
System.out.println("Sum="+s);
}
}
65. Write a program to find the sum of series, taking the value of ‘n’ from the user.
s= 1 + 2/2 * 3+2 + 3/3 * 4+3 + 4/4 * 5+4 + 5/5 * 6+... up to n terms
Ans. import java.util.*;
public class Question65
{
static void main()
{
int i,n;
float s=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of n:");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
s=s+(float)(i+(i+1))/((i+1)*(i+2));
}
System.out.println("Sum="+s);
}
}
66. Write a program to compute and display the sum of the following series:
[ICSE 2007]
67. Write a program to print the sum of negative numbers, sum of positive even
numbers and sum of positive odd numbers from a list of numbers (N) entered by the
user. The list terminates when the user enters a zero. [ICSE 2005]
68. Shasha Travels Pvt. Ltd. gives the following discount to its customers:
[ICSE 2010]
Write a program to input the name and ticket amount for the customer and
calculate the discount amount and net amount to be paid. Display the output in the
following format for each customer:
SL. NO. Name Ticket mount
(Assume that there are 15 customers, first customer is given the serial no (SL. No.
1), next customer 2 ……… and so on.
69. Using nested loops try producing the following patterns on the screen:
Ans. class Question69
{
static void pattern_i()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_ii()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_iii()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_iv()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_v()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_vi()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
static void pattern_vii()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
static void pattern_viii()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
System.out.print(i);
}
System.out.println();
}
}
static void pattern_ix()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--)
{
System.out.print(i);
}
System.out.println();
}
}
static void pattern_x()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
static void pattern_xi()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
static void pattern_xii()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i==j || i+j==6)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
static void pattern_xiii()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if((i+j)%2!=0)
System.out.print(0);
else
System.out.print(1);
}
System.out.println();
}
}
static void pattern_xiv()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j<=5;j++)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_xv()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i+j>=6)
System.out.print(j);
else
System.out.print(" ");
}
System.out.println();
}
}
static void pattern_xvi()
{
int i,j;
for(i=1;i<=6;i++)
{
for(j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_xvii()
{
int i,j;
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
{
if(i==j || j==1)
System.out.print(1);
else
System.out.print(0);
}
System.out.println();
}
}
static void pattern_xviii()
{
int i,j,a,b,c;
for(i=1;i<=6;i++)
{
a=1;b=0;
for(j=1;j<=i;j++)
{
c=a+b;
System.out.print(c);
a=b;
b=c;
}
System.out.println();
}
}
static void pattern_xix()
{
int i,j;
for(i=1;i<=6;i++)
{
for(j=i;j<=5;j++)
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print(j);
}
for(j=i-1;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_xx()
{
int i,j;
for(i=6;i>=1;i--)
{
for(j=i;j<6;j++)
{
System.out.print(" ");
}
for(j=i;j>=1;j--)
{
System.out.print(j);
}
for(j=2;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
static void pattern_xxi()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(j>=i)
System.out.print(j);
else
System.out.print(" ");
}
System.out.println();
}
}
static void pattern_xxii()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if((j+i)%2==0)
System.out.print(1);
else
System.out.print(0);
}
System.out.println();
}
}
static void pattern_xxiii()
{
int i,j;
for(i=1;i<=9;i+=2)
{
for(j=1;j<=9;j+=2)
{
if(j>=i)
System.out.print(10-i);
else
System.out.print(" ");
}
System.out.println();
}
}
static void pattern_xxiv()
{
int i,j;
for(i=1;i<=9;i+=2)
{
for(j=1;j<=9;j+=2)
{
if(j+i>=10)
System.out.print(i);
else
System.out.print(" ");
}
System.out.println();
}
}
static void pattern_xxv()
{
/*
12345
23451
34512
45123
51234
*/
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j<=5;j++)
{
System.out.print(j);
}
for(j=1;j<=i-1;j++)
{
System.out.print(j);
}
System.out.println();
}
}
70. Write a program to input a number and print all its prime factors using prime
factorization method.
For Example,
INPUT: Enter an integer: 24
OUTPUT: Prime factors using prime factorisation are:
2
2
2
3
Ans. import java.util.*;
public class Question70
{
static void main()
{
int n,p=2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter an integer:");
n=sc.nextInt();
System.out.println("Prime factors using prime factorisation are:");
while(n>1)
{
if(n%p==0)
{
System.out.println(p);
n=n/p;
}
else
p++;
}
}
}
71. Write a program to input a number and check whether it is a Smith number or
not. Smith number is such a number the sum of whose digits equals the sum of the
digits of its prime factors.
Smith number is a composite number in which the sum of its digits is equal to the
sum of the digits of all its prime factors.
For example, 378 is a Smith number as the sum of the digits of 378 are: 3+7+8 = 18.
The prime factors of 378 are: 2, 3, 3, 3, 7 (sum = 2+3+3+3+7 = 18).
Similarly, 22 is a Smith number as the sum of the digits are: 2+2=4. The prime
factors of 22 are: 2 and 11 (sum = 2+(1+1) = 4
Other examples include 27, 58, 85, 94, 121, 166, 202, 265, etc.
Ans. import java.util.*;
public class Question71
{
static void main()
{
int n,d,s1=0,t,t1,s2=0,p=2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter an integer:");
n=sc.nextInt();
t=n;
while(t!=0)
{
d=t%10;
s1=s1+d;
t=t/10;
}
t=n;
while(t>1)
{
if(t%p==0)
{
t1=p;;
while(t1!=0)
{
d=t1%10;
s2=s2+d;
t1=t1/10;
}
t=t/p;
}
else
p++;
}
if(s1==s2)
System.out.println("Smith Number");
else
System.out.println("Not Smith Number");
}
}
Chapter 8: The Math Class
Practice Questions
-------------------------------------->Objective-Type Questions<---------------------------------
State True or False:
1. It is possible to find the square root of a number using the Math.pow( )
function. [True]
2. Math.sqrt( ) function is used to find the square of a number. [True]
3. All trigonometric functions works with angles specified in radians. [True]
4. Math.abs( ) function is used to round off a real number to the nearest
integer. [False]
5. Math. rint(12.5) will return 12.0. [True]
6. Math.ceil( ) and Math.floor( ) are same. [False]
7. NaN stands for Not a Number, which is received when you pass a
negative number to the Math.sqrt( ) function. [True]
8. Math.cosec( ) function is the reciprocal of Math.sin( ) function. [False]
9. Math.cot(x) function is used as a reciprocal of Math.tan(x) function. [False]
10. Math.round( ) function returns an int value if the parameter is float
data type and long value if the parameter is of double data type. [True]
---------------------------------->Subjective-Type Questions--------------------------------------
A. Answer the following questions:
1. Name the class that is used for different mathematical functions. Give an
example of a mathematical function. [ICSE 2007]
Ans. Math class. Math.sqrt( )
2. Give the output of the following expressions: [ICSE 2008]
i) If x = –9.99, calculate Math.abs(x);
ii) If x = 9.0, calculate Math.sqrt(x);
Ans. i) 9.99
ii) 3.0
3. Give the output of the following functions:
a) Math.floor(–126.349) b) Math.max(45.6,17.3) c) Math.min(–0.0,0.0)
d) Math.pow(4,3) e) Math.sqrt(625) f) Math.cbrt(125)
g) Math.log10(1000) h) Math.rint(14.5) i) Math.ceil(–12.56)
j) Math.floor(15.36) k) Math.round(146.5) l) Math.max(11,11)
m) Math.min(14.3,14.3) n) Math.rint(14.562) o) Math.ceil(–14.0)
Ans. a) Math.sqrt(a+b)
b) 1/3.0*a*a*a+1/4.0*b*b*b
c) s=u*t+1/2.0*a*t*t
d) d=Math.sqrt(l*l+b*b)
e) -b+Math.sqrt(b*b-4*a*c)/(2*a)
-b-Math.sqrt(b*b-4*a*c)/(2*a)
f) Math.pow(Math.sin(x),2)+Math.pow(Math.cos(y),2)
g) (Math.tan(a)+Math.tan(b))/(1-Math.tan(a)*Math.tan(b))
h) (1-Math.log10(x))/(1+Math.log10(x))
i) Math.cbrt(5*x*x+Math.sin(y))/Math.pow(Math.cos(x)+11*y*y*y,1/4.0)
j) (Math.asin(x)+Math.acos(y))/Math.sqrt(Math.log(Math.cos(x)*Math.cos
(x)))
k) Math.atan(x)+Math.cos(y)*Math.cos(y)-2*x*x*y*y*y-
Math.sqrt(4*Math.exp(2*x))
l) Math.sqrt(2*a*s+u*u)
2. Write a program that outputs the results of the following evaluations based on
the number entered by the user:
i) Natural logarithm of the number
ii) Absolute value of the number
iii) Square root of the number
iv) Random numbers between 0 and 1. [ICSE 2006]
Ans. import java.util.*;
class Question2
{
static void main()
{
double n,l,a,s,r;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number:");
n=sc.nextDouble();
l=Math.log(n);
a=Math.abs(n);
s=Math.sqrt(n);
r=Math.random();
System.out.println("Natural Logarithm="+l);
System.out.println("Absolute Value="+a);
System.out.println("Square Root="+s);
System.out.println("Random Number between 0 and 1="+r);
}
}
3. Write a program to calculate the interest and total amount to be paid by entering
the amount of loan and the number of years, either by simple interest method or
by compound interest method, as per the choice of user.
For Simple Interest,
Interst=(Amount*Rate * Number of Years) / 100 and Total amount=Amount +
Interest
For Compound Interest,
𝑹𝒂𝒕𝒆
Total amount = Amount (𝟏 + ) No. of years
𝟏𝟎𝟎
Ans. import java.util.*;
class Question3
{
static void main()
{
double p,r,t,i,a;
int ch;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the principle:");
p=sc.nextDouble();
System.out.println("Enter the rate:");
r=sc.nextDouble();
System.out.println("Enter the time:");
t=sc.nextDouble();
System.out.println("Enter 1 to find the Simple Interest");
System.out.println("Enter 2 to find the Compound Interest");
System.out.print("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{
case 1:
i=(p*r*t)/100;
a=p+i;
System.out.println("Interest:"+i);
System.out.println("Amount Payable:"+a);
break;
case 2:
a=p*Math.pow((1+r/100),t);
i=a-p;
System.out.println("Interest:"+i);
System.out.println("Amount Payable:"+a);
break;
default:
System.out.println("Invalid Choice!");
}
}
}
4. The following formulae describe the properties of portion of circle with radius ‘r’
and central angle ‘x’ in degrees:
Area = r2
If the values of r and x are entered through the keyboard. Write a program to
calculate the above values of the circle.
Ans. import java.util.*;
class Question4
{
static void main()
{
double r,x,area,arc,chord,segment,y;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of r and x:");
r=sc.nextDouble();
x=sc.nextDouble();
y=Math.toRadians(x); //Convert degrees to radians to use with Math.sin()
area=Math.PI*r*r;
arc=Math.PI*r*x/180;
chord=2*r*Math.sin(y/2);
segment=(Math.PI*r*r*x)/360-(r*r*Math.sin(y))/2;
System.out.println("Area="+area);
System.out.println("Length of arc="+arc);
System.out.println("Length of chord="+chord);
System.out.println("Area of segment="+segment);
}
}
5. Write a program to input the length of the 3 sides of a triangle (say a, b and c)
and calculate the area depending upon the following criteria:
denominator=1+Math.tan(Math.toRadians(a))*Math.tan(Math.toRadians(b));
x=numerator/denominator;
System.out.println(x);
}
}
}
7. Write a program to calculate and print the values of:
𝒙𝟐 + 𝒚𝟐
𝒁=
𝒙+𝒚
Where, x ranges from 0 to 50 and y remains constant at 5. Use symbolic constant
for y.
Ans. class Question7
{
static void main()
{
float x,Z;
final int y=5;
for(x=0;x<=50;x++)
{
Z=(x*x+y*y)/(x+y);
System.out.println(Z);
}
}
}
8. Write a program using conditional operator to input two integers and if the
difference is positive, find the square root of its difference, otherwise find its cube
root.
Ans. import java.util.*;
class Question8
{
static void main()
{
int a,b,d;
double ans;
Scanner sc=new Scanner(System.in);
System.out.println("Enter two integers:");
a=sc.nextInt();
b=sc.nextInt();
d=a-b;
ans=(d>0)?Math.sqrt(d):Math.cbrt(d);
System.out.println("Answer="+ans);
}
}
9. Write a program to input two integers, say x and n, and find the sum of the
following series:
sum+=Math.pow(x,i)/f;
}
System.out.println("Answer="+sum);
}
static void series_vii()
{
int i,j,x,n;
long f;
double sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter two integers:");
x=sc.nextInt();
n=sc.nextInt();
for(i=1;i<=n;i++)
{
f=1;
for(j=1;j<=i+1;j++)
f=f*j;
sum+=Math.pow(x,i)/f;
}
System.out.println("Answer="+sum);
}
static void series_viii()
{
int i,j,x,n;
long f;
double sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter two integers:");
x=sc.nextInt();
n=sc.nextInt();
for(i=1;i<=n;i++)
{
f=1;
for(j=1;j<=i;j++)
f=f*j;
sum+=Math.pow(x,i+1)/f;
}
System.out.println("Answer="+sum);
}
if(i%2==0)
sum-=Math.pow(x,i)/f;
else
sum+=Math.pow(x,i)/f;
}
System.out.println("Answer="+sum);
}
if(i%2==0)
sum-=Math.pow(x,i)/f;
else
sum+=Math.pow(x,i)/f;
}
System.out.println("Answer="+sum);
}
if(i%2==0)
sum-=Math.pow(x,i+1)/f;
else
sum+=Math.pow(x,i+1)/f;
}
System.out.println("Answer="+sum);
}
}
10. Write a program to find the sum of the following logarithmic series:
11. A projectile fired at an angle , given an initial velocity of vo, will travel a distance
produces a table of the following form for all angles from 30 to degrees in 5
degree increments and initial velocities from 500 to 1000m/sec in 100m/sec
increments:
(INITIAL VELOCITY=500m/sec)
ANGLE DISTANCE TIME HEIGHT
Ans. class Question11
{
static void main()
{
double vo, theta, d,t,h;
final double g=9.8;
vo=500; //initial velocity
System.out.println("ANGLE\t\tDISTANCE\t\t\tTIME\t\t\t\tHEIGHT");
for(theta=30;theta<=90;theta+=5)
{
d=(vo*vo)/g*Math.sin(Math.toRadians(2*theta));
t=2*vo*Math.sin(Math.toRadians(theta))/g;
h=vo*vo/g*Math.sin(Math.toRadians(theta));
System.out.println(theta+"\t\t"+d+"\t\t"+t+"\t\t"+h);
}
}
}
12. A game of dice is to be simulated for two players, each player gets a chance to
throw his dice, and the value is added to his points, this process continues
alternately until for the player whose added points equal to 20 and is declared the
winner. Write a program to simulate this process using the random( ) function.
Ans. class Question12
{
static void main()
{
int d1,d2,s1=0,s2=0;
do
{
d1=1+(int)(Math.random()*6); //dice throw for first player
s1+=d1;//Add the value of the dice to the first players total
if(s1>=20)
break;
d2=1+(int)(Math.random()*6); //dice throw for second player
s2+=d2;//Add the value of the dice to the second players total
if(s2>=20)
break;
}while(s1<20 && s2<20);
if(s1>=20)
System.out.println("First player is the winner");
else
System.out.println("Second player is the winner");
}
}
15. Write a function that simulates rolling a pair of dice until the total on the dice
comes up to be a given number. The number that you are rolling for is a parameter
to the function. The number of times you have to roll the dice is the return value of
the function. You can assume that the parameter is one of the possible totals: 2, 3,
..., 12. Use your function in a program that computes and prints the number of
rolls it takes to get snake eyes. (Snake eyes means that the total showing
on the dice is 2.)
Ans. class Question15
{
static int rollingPair(int n)
{
int d1,d2,c=0;
do
{
c++;
d1=1+(int)(Math.random()*6);
d2=1+(int)(Math.random()*6);
if(d1+d2==n)
break;
}while(true);
return c;
}
static void main()
{
int s;
s=rollingPair(2);
System.out.println("Number of rollings for Snake eyes:"+s);
}
}
16. The roots (say x1 and x2) of a quadratic equation ax2+bx+c=0 can be
determined by its discriminant (d), where d = b2 – 4ac. Depending upon its value
the nature of the roots and the value of the roots can be determined.
i) If d=0 then the roots are Real and Equal and the roots can be found using the
formula:
−𝒃
𝟐𝒂
ii) If d>0 then the roots are Real and Distinct and the roots can be found using the
formula:
−𝒃±√𝐝
𝟐𝒂
iii) If d<0 then the roots are Imaginary and therefore roots are not found.
Write a program to input a,b and c the coefficient of the quadratic equation and
find its roots.
Ans. import java.util.*;
class Question16
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a,b,c,d;
double r1,r2;
System.out.println("Enter the coefficients of the quadratic equation:");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=b*b-4*a*c;
if(d==0)
{
System.out.println("Roots are Real and Equal");
r1=r2=-b/(2*a);
System.out.println("Roots are:"+r1+"\t"+r2);
}
else if(d>0)
{
System.out.println("Roots are Real and Distinct");
r1=(-b+Math.sqrt(d))/(2*a);
r2=(-b-Math.sqrt(d))/(2*a);
System.out.println("Roots are:"+r1+"\t"+r2);
}
else
{
System.out.println("Roots are Imaginary");
System.out.println("Roots not found");
}
}
}
17. Write a program for all four operations (addition, subtraction, multiplication
and division according to the user’s choice). Each of the problem is to be random.
Also if the user gets a problem incorrect, give him/her a second try at the problem.
If the problem is correct display “Right”, otherwise display “Wrong” after the
second try.
18. Write a program to input a real number (floating point number) and round off
each number to 2 places of decimal and display the answer.
For example, if
INPUT: 12.3867
OUTPUT: 12.39
similarly, if
INPUT: 73.2846
OUTPUT: 73.28
Ans. import java.util.*;
class Question18
{
static void main()
{
float n,f;
int r;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a real number:");
n=sc.nextFloat();
r=Math.round(n*100);//Move the decimal place 2 digits to the right
f=(float)r/100;
System.out.println(f);
}
}
19. Write a program to input 10 numbers and find their sum after converting each
number to its equivalent positive value.
Ans. import java.util.*;
class Question19
{
static void main()
{
float n,s=0;
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 10 numbers:");
for(i=1;i<=10;i++)
{
n=sc.nextFloat();
s=s+Math.abs(n);
}
System.out.println("Sum="+s);
}
}
20. Write a program to input a binary number (consisting of only 1's and 0's) and
convert it to its equivalent decimal.
For example, if
INPUT: 110
OUTPUT: 6
similarly if
INPUT: 1002
OUTPUT: No a proper binary number.
Ans. import java.util.*;
class Question20
{
static void main()
{
int n,s=0,c=0,f=0,d;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a binary number:");
n=sc.nextInt();
while(n!=0)
{
d=n%10;
if(d!=1 && d!=0)
{
f=1;
break;
}
s=s+d*(int)Math.pow(2,c++);
n=n/10;
}
if(f==0)
System.out.println("Decimal Equivalent="+s);
else
System.out.println("Not a proper binary number");
}
}
Chapter 9: Functions/Methods
Practice Questions
---------------------->Objective-Type Questions<----------------------
A. Fill in the blanks:
1. In Java functions are known as Methods.
2. Methods are contained in class.
3. The function name and the parameter list together is known as Function Signature.
4. The access specifier, return type and the function signature together is known as Function
prototype.
5. The arguments of the function given in function prototype are called Formal Parameters.
6. The arguments of the function given in statement that calls the function are called Actual
Parameters.
7. If a function does not return any value, the returning type in the function prototype will be
void.
8. When a function is called by Value, the values of actual parameters are copied into separate
memory locations as allocated by the formal parameters.
9. Impure functions use call by Reference.
10. One of the practical implementations of polymorphism is Method Overloading.
B. Write function prototypes for the following:
1. private access method sum which accepts three int type variables as parameters and
return a float type.
Ans. private float sum(int a, int b, int c)
2. default access method Length which accepts a String type variable as parameters and
return an int type.
Ans. int Length(String s)
3. public access method increment which accepts an object of Myclass type as parameters
and do not return any value.
Ans. public void increment(Myclass ob)
4. protected access method largest which accepts a float type, int type and double type data
as parameters and have a byte type as return type.
Ans. protected byte largest(float a, int b, double c)
5. public access static method calculate which accepts a byte and int type data type as
parameters and return float type.
Ans. public static float calculate(byte a, int b)
6. Write the function prototype for the function "sum" that takes an integer variable (x) as
it argument and returns a value of float data type. [ICSE 2009]
Ans. float sum(int x)
7. Write the prototype of a function which takes in 2 integers and 1 String arguments and
returns a value which is either ‘true’ or false’. [ICSE 2010]
Ans. boolean function (int a, int b, String s)
--------------------->Subjective-Type Questions<----------------------
A. Answer the following questions:
1. What is a method?
Ans. Function or Method is a block of code containing executable lines of code that
represents the behavioural aspect of an object.
2. Write two advantages of using functions in a program. [ICSE 2010]
Ans. The Advantages of using functions are:
a) Reduces Complexity: Breaking a large task into smaller tasks
automatically reduces complexity, thereby increasing the maintainability
of the program.
b) Reusability: Once a method is defined, it can be invoked again and again
from different segments of a program thus reusing the method whenever
required.
4. If a function contains several return statements, how many of them will be executed?
[ICSE 2007]
Ans. If a function contains several return statements, only the first one which JVM
comes across is executed. Thus forcing an exit from the function and therefore the
remaining return statements are not executed.
5. Name the keyword that causes the control to transfer back to the method call.
[ICSE 2009]
Ans. The keyword that causes the control to transfer back to the method call is –return.
6. What is the role of the keyword void in declaring functions? [ICSE 2007]
Ans. The void return-type of a function is used to ensure that a function do not return
any value.
7. Classify functions depending upon the value it returns.
Ans. Depending on the value that is returned by a function, it is classified as:
a) Computational Function
b) Manipulative Function
c) Procedural Function
totalsurfaceArea(x,y,z);
where x, y and z are variables of float type and are assigned to l, b and h respectively.
After a function computes a value, it can be returned to the place where it is invoked using
the general syntax:
return <value>;
Example,
// Demonstrate method overloading.
public class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
//Overload test for one integer parameter.
void test(int a)
{
System.out.println("a:" + a);
}
//Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a +" " + b);
}
//Overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a );
return a*a;
}
static void call()
{
OverloadDemo ob=new OverloadDemo();
double result;
ob.test();
ob.test(5);
ob.test(7,9);
result=ob.test(12.73);
System.out.println("Result of ob.test(12.73): "+result);
}
}
18. Which OOP principle implements function overloading? [ICSE 2007]
Ans. The principle of Polymorphism is implemented using Function Overloading.
19. When there are multiple definitions with the same function name, what makes them
different from each other? [ICSE 2009]
Ans. When there are multiple definitions with the same name, the parameter-list makes
them different from each other.
20. What are the different access specifiers available in Java?
Ans. The different access specifiers in Java are: default, public, protected and private.
21. What is the function of main( ) method?
Ans. In conventional Java the main( ) function is from where the program execution
begins and is therefore also called the driver function. In BlueJ environment main() do
not have any relevance at all it behaves exactly like any other function in Java.
22. How are static methods of one class called by methods in other classes?
Ans. Methods which are static are called by other classes using the class name of which it
is a content followed by the method call statement. For example,
class Myclass
{
static void trial()
{
}
}
class Anyclass
{
static void call()
{
Myclass.trial();//static method of Myclass is invoked
}
}
B. Answer as directed:
1. In the program given below: [ICSE 2012]
class MyClass
{
static int x = 7;
int y = 2;
public static void main(String args[ ])
{
MyClass obj = new MyClass( );
System.out.println(x);
obj.sampleMethod(5);
int a= 6;
System.out.println(a);
}
void sampleMethod(int n)
{
System.out.println(n);
System.out.println(y);
}
}
State the name and value of the:
i) method argument or argument variable.
ii) class variable.
iii) local variable.
iv) instance variable .
Ans. i) int n value= 5
ii) int x value=7
iii) int a value 6
iv) int y value 2
Lab Exercises
Write programs for the following:
1. Create a method which accepts two int type variable a and b as parameter and evaluate
the following expression:
𝟒. 𝟓𝒂 + 𝒃𝟐
𝒂−𝒃
and return it.
Ans. class Question1
{
static float calc(int a,int b)
{
float c;
c=(float)(4.5*a+b*b)/(a-b);
return c;
}
}
2. Create a function which accepts an integer as parameter and return true if it is a prime
number otherwise return false. In the main( ) method input an integer and using the above
method check whether it is a prime number or not.
Ans. import java.util.*;
class Question2
{
static boolean isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
3. Create a function which accepts an integer as parameter and return true if it is a perfect
number otherwise return false. In the main( ) method input two integers and check whether
both the numbers are perfect numbers or not.
Ans. import java.util.*;
class Question3
{
static boolean isPerfect(int n)
{
int i,s=0;
for(i=1;i<n;i++)
{
if(n%i==0)
s+=i;
}
if(s==n)
return true;
else
return false;
}
4. Create a function which accepts an integer as parameter and return the sum of the
square of its digits. In the main( ) method display all three-digit Armstrong numbers.
Ans. class Question4
{
static int sum(int n)
{
int d,s=0;
while(n!=0)
{
d=n%10;
s+=d*d*d;
n=n/10;
}
return s;
}
static void main()
{
int i,s;
System.out.println("All 3 digit armstrong numbers:");
for(i=100;i<=999;i++)
{
s=sum(i);
if(i==s)
System.out.println(i+" ");
}
}
}
6. Create a function which accepts an integer as parameter and return the sum of its digits.
Create another function to input 10 integers and find the sum of the digits of each number.
Ans. import java.util.*;
class Question6
{
static int sum(int n)
{
int d,s=0;
while(n!=0)
{
d=n%10;
s=s+d;
n=n/10;
}
return s;
}
8. Create a method which accepts temperature in Celsius and return its Fahrenheit
equivalent. Create another method which accepts temperature in Fahrenheit and return its
Celsius equivalent. Also create a method to invoke the above methods.
Ans. import java.util.*;
class Question8
{
static float celciusToFarenheit(float c)
{
float f=(float)(9*c)/5+32;
return f;
}
}
}
10. Create a class with the following methods:
i) int sum(int n), which finds the sum of the digits in n and returns it.
ii) void call( ) to input 10 integers using scanner and find the sum of its digits of each integer
value entered by the user using the above method.
Ans. import java.util.*;
class Question10
{
static int sum(int n)
{
int d,s=0;
while(n!=0)
{
d=n%10;
s=s+d;
n=n/10;
}
return s;
}
}
}
}
}
if(f==1)
System.out.println("Largest Armstrong number="+l);
else
System.out.println("No Armstrong number present");
}
}
}
}
}
}
}
}
}
}
s=sumOfPrimeDigits(n);
p=isPrime(s);
if(p==true)
System.out.println("Sum of prime digits is also a prime number");
else
System.out.println("Sum of prime digits is not a prime number");
}
}
23. Create a class called Series which will contain the following members function:
i) long fact(int f) to find the factorial of f and return it.
ii) void sumSeries1(int x,int n) to calculate and print the sum of the following series:
x+x/2! +x/3! +x/4! +...+x/n!
iii) void sumSeries2(int x,int n) to calculate and print the sum of the following series:
x/2! +x2/3! +x3/4! +x4/5! +…+xn/(n+1)!
iv) void sumSeries3(int x,int n) to calculate and print the sum of the following series:
x/2! – x2/3! +x3/4! – x4/5! +…±xn/(n+1)!
Ans. //QUESTION 23
class Series
{
static long fact(int f)
{
int i;
long p=1;
for(i=1;i<=f;i++)
p=p*i;
return p;
}
24. Where the symbol ! stands for factorial, e.g. 5!=5*4*3*2*1, 3!=3*2*1
• Using overloading technique, write methods to:
• accept two int type data as parameters and return their sum.
• accept three int type data as parameters and return their sum.
• accept two double type data as parameters and return their sum.
• accept a double type and int type as parameters and return their sum.
Ans. class Question24
{
static int sum(int a,int b)
{
int c;
c=a+b;
return c;
}
25. Create a function which accepts an integer as parameter and return true if it is a prime
number otherwise return false. Create another function which accepts an integer as
parameter and return true if it is palindrome otherwise return false. In the main( ) method
display all three-digit pal-prime number. Pal-prime numbers are such numbers which are
both palindrome as well as prime numbers.
For example, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919 and 929 are
all three digit pal-prime numbers.
Ans. class Question25
{
static boolean prime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
}
}
26. Create a function which accepts an integer as parameter and return the sum of its digits.
Create another function which accepts an integer as parameter and return true if it is a
magic number otherwise return false. In the main input an integer and check whether it is a
magic number or not.
If you iterate the process of summing the squares of the decimal digits of a number and if
this process terminates in 1, then the original number is called a magic number. For
example, 55 ⇒ (5+5)=10 ⇒ (1+0)=1.
Ans. import java.util.*;
class Question26
{
static int sum(int n)
{
int d,s=0;
while(n!=0)
{
d=n%10;
s=s+d;
n=n/10;
}
return s;
}
27. Create a function which accepts an integer as parameter and return the sum of the
square of its digits. Create another function which accepts an integer as parameter and
return true if it is happy number otherwise return false. In the main input an integer and
check whether it is a happy number or not. For example, 7 (72) =49 (42+92) =97
(92 +72) =130 (12 +32+02) =10 (12+02) = 1.
Ans. import java.util.*;
class Question27
{
static int sum(int n)
{
int d,s=0;
while(n!=0)
{
d=n%10;
s=s+d*d;
n=n/10;
}
return s;
}
29. Write a class with the name volume using function overloading that computes the
volume of a cube, a sphere and a cuboid. [ICSE 2008]
Formula:
volume of a cube (vc) = s*s*s
volume of a sphere (vs) = 4/3 * pi * r * r * r (where pi = 3.14 or 22/7)
Volume of a cuboid (vcd) = l * b * h
Ans. //Question 29
class Volume
{
void function(int s)
{
int v;
v=s*s*s;
System.out.println("Volume="+v);
}
void function(float r)
{
float v;
v=4/3f*3.14f*r*r*r;
System.out.println("Volume="+v);
}
36. Write a menu-driven program to accept a number from the user and check whether is a
‘BUZZ’ number or to accept any two numbers and print ‘GCD’ of them. [ICSE 2009]
i) A BUZZ number is the number which either ends with 7 or divisible by 7.
ii) GCD (Greatest Common Divisor) of two integers is calculated by continued division
method. Divide the larger number by the smaller, the remainder then divides the previous
divisor. The process is repeated till the remainder is zero. The divisor then results the GCD.
Ans. import java.util.*;
class Question36
{
static void isBuzz(int n)
{
if(n%7==0 || n%10==7)
System.out.println("Buzz Number");
else
System.out.println("Not a Buzz Number");
}
37. Write a menu-driven program to accept a number and check and display whether it is a
Prime Number or not OR an Automorphic Number or not (Use switch-case statement).
[ICSE 2010]
i) Prime number: A number is said to be a prime number if it is divisible only by 1 and itself
and not by any other number. Example: 3, 5, 7, 11, 13, etc.
ii) Automorphic number: An automorphic number is the number which is contained in the
last digit(s) of its square. Example: 25 is an automorphic number as its square is 625 and 25
is present as the last two digits.
Ans. import java.util.*;
class Question37
{
static void isPrime(int n)
{
int i,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
System.out.println("Prime Number");
else
System.out.println("Not a Prime Number");
}
static void isAutomorphic(int n)
{
int s,c=0,t=n;
s=n*n;
while(n!=0)
{
c++;
n/=10;
}
if(s%(int)Math.pow(10,c)==t)
System.out.println("Automorphic Number");
else
System.out.println("Not an Automorphic Number");
}
38. Write a menu-driven program to perform the following: (Use switch-case statement)
i) To print the series 0, 3, 8, 15, 24… n terms(value of ‘n’ is to be an input by the user).
ii) To find the sum of the series given below:
S= 1/2 + 3/4 + 5/6 + 7/8 …. 19/20. [ICSE 2011]
Ans. import java.util.*;
class Question38
{
static void series1(int n)
{
int i,c=3,s=0;
for(i=1;i<=n;i++)
{
System.out.print(s+" ");
s=s+c;
c=c+2;
}
}
39. Using the switch statement, write a menu-driven program to: [ICSE 2012]
i) Generate and display the first 10 terms of the Fibonacci series 0, 1, 1, 2, 3, 5, ….
ii) find the sum of the digits of an integer that is input. E.g. 15390=18
For an incorrect choice, appropriate error message should be displayed.
Ans. import java.util.*;
class Question39
{
static void fibonacci()
{
int i,a=0,b=1,c;
System.out.print("Fibonacci Series:"+a+" "+b+" ");
for(i=1;i<=8;i++)
{
c=a+b;
System.out.print(c+" ");
a=b;
b=c;;
}
}
default:
System.out.println("Invalid Entry!");
}
}
}
40. Using the switch statement, write a menu-driven program: [ICSE 2013]
i) To check and display whether a number input by the user is a composite number or not
(A number is said to be a composite, if it has one or more than one factors excluding 1 and
the number itself).
Example: 4, 6, 8, 9…
ii) To find the smallest digit of an integer that is input:
Sample input: 6524
Sample output: Smallest digit is 2
For an incorrect choice, an appropriate error message should be displayed.
Ans. import java.util.*;
class Question40
{
static void isComposite(int n)
{
int i,c=0;
for(i=2;i<n;i++)
{
if(n%i==0)
c++;
}
if(c>=1)
System.out.println("Composite Number");
else
System.out.println("Not a Composite Number");
}
default:
System.out.println("Invalid Entry!");
}
}
}
41. Create a function which accepts an integer as parameter and return true if it is a
Fibonacci number otherwise return false. A number is said to be Fibonacci if it comes
under the Fibonacci series (1, 1, 2, 3, 5, 8, 13, 21, 34 …). In the main( ) input a number (say
n) and check whether it is a
Fibonacci number or not.
Sample Input/Output
INPUT
Enter an integer:13
OUTPUT
It is a valid Fibonacci number
INPUT
Enter an integer: 12
OUTPUT
Not a valid Fibonacci number
Ans. import java.util.*;
class Question41
{
static boolean isFibonacci(int n)
{
int a=1,b=0,c=0;
while(c<n)
{
c=a+b;
a=b;
b=c;
}
if(c==n)
return true;
else
return false;
}
42. Create a function which accepts an integer as parameter and return true if it is a
Fibonacci number otherwise return false. In the main input 10 integers and print the largest
Fibonacci number if any.
Note that the number which will be entered by the user may not be ordered.
Sample Input/Output
INPUT
Enter 10 integers:
5 16 21 9 15 4 8 16 11 10
OUTPUT
Largest Fibonacci number:21
INPUT
Enter 10 integers:
25 10 7 6 4 12 18 10 9 14
OUTPUT
No Fibonacci number present
Ans. import java.util.*;
class Question42
{
static boolean isFibonacci(int n)
{
int a=1,b=0,c=0;
while(c<n)
{
c=a+b;
a=b;
b=c;
}
if(c==n)
return true;
else
return false;
}
class Myclass
{
int a,b; //Instance Variable
static void main( )
{
Myclass ob1=new Myclass();
Myclass ob2=new Myclass();
ob1.a=5;ob1.b=6;
ob2.a=7;ob2.b=8;
}
}
In the main( ) function, there are two objects that are instantiated ob1 and ob2.
Each object i.e. ob1 will have a set of instance variable a and b (which are
assigned 5 and 6 respectively) similarly ob2 will have another set of instance
variable a and b (which are assigned 7 and 8 respectively).
5. What does the following mean? [ICSE 2008]
Employee staff = new Employee( );
Ans. An object named staff is being allocated memory using the new command of the
Employee class.
6. What is the use of the keyword this? [ICSE 2009]
Ans. This keyword is used within a member function that acts as a reference to the
current object.
7. What is a composite data type? In this respect also explain why a class is called composite
data type?
Ans. Composite data type refers to a data type that is composed of multiple predefined
discrete data types. The class acts as a composite data type as it may contain data
members that are composed of varied data types kept as a single unit.
E. Consider the following code and answer the questions that follow:
class vxl
{
int x,y;
void init( )
{
x=5;
y=10;
}
protected void access( )
{
int a=50, b=100;
vxl vin=new vxl( );
vin.int( );
System.out.println("Object created");
System.out.println("I am X="+vin.x);
System.out.println("I am Y="+vin.y);
}
}
i) What is the object name of the class vxl?
ii) Name the local variables of class.
iii) What is the access specifier of method access( )?
iv) Write the output of above program.
Ans. i) vin
ii) a and b of int data type
iii) protected
iv) Object Created
I am X=5
I am Y=10
F. Find the errors in the program given below and rewrite the corrected form:
My class
{
int a;
static int b;
void My class(int x, int y)
void display1( )
{
System.out.println(a+" "+b);
}
static void display2( )
{
System.out.println(a+" "+b);
}
public static void main(String args[ ])
{
My class ob1=new My class( );
ob1.My class(5,6);
ob1.display1( );
ob2.display2( );
}
}
Ans. class Myclass
{
int a;
static int b;
Myclass(int x, int y)
{
a=x;
b=y;
}
void display1( )
{
System.out.println(a+" "+b);
}
static void display2( )
{
System.out.println(b);
}
public static void main(String args[ ])
{
Myclass ob1=new Myclass(5,6 );
ob1.display1( );
display2( );
}
}
G. Write programs for the following:
1. Write a class with name Employee and basic as its data member, to find the gross pay of
an employee for the following allowances and deduction. Use meaningful variables.
[ICSE 2005]
Dearness Allowance = 25% of Basic Pay
House Rent Allowance = 15% of Basic Pay
Provident Fund = 8.33% of Basic Pay
Net Pay = Basic Pay + Dearness Allowance + House Rent Allowance
Gross Pay = Net Pay − Provident Fund
Ans. import java.util.*;
//Question 1
class Employee
{
float basic;
void getvalue()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the basic pay:");
basic=sc.nextFloat();
}
void calculate()
{
float da,hra,pf,netPay,grossPay;
da=25/100f*basic;
hra=15/100f*basic;
pf=8.33f/100*basic;
netPay=basic+da+hra;
grossPay=netPay-pf;
System.out.println("Dearness Allowance:"+da);
System.out.println("House Rent Allowance:"+hra);
System.out.println("Provident Fund:"+pf);
System.out.println("Net Pay:"+netPay);
System.out.println("Gross Pay:"+grossPay);
}
}
void display()
{
System.out.println("Name:"+name);
System.out.println("Address:"+address);
System.out.println("Phone number:"+phone);
System.out.println("Subject Speciallization:"+subject);
System.out.println("Monthly Salary:"+monthlySalary);
System.out.println("Income Tax="+incomeTax);
}
void compute()
{
float annualSalary;
annualSalary=12*monthlySalary;
if(annualSalary>175000)
incomeTax=5/100f*(annualSalary-175000);
else
incomeTax=0;
}
void display()
{
System.out.println("Pan Number\tName\t\tTax-income\t\tTax");
System.out.println(pan+"\t\t"+name+"\t\t"+tax_income+"\t\t"+tax);
}
void calc()
{
if(tax_income<=100000)
tax=0;
else if(tax<=150000)
tax=10/100.0*(tax_income-100000);
else if(tax<=250000)
tax=5000+20/100.0*(tax_income-150000);
else
tax=25000+30/100.0*(tax_income-250000);
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the bike's number:");
bno=sc.nextInt();
System.out.println("Enter the phone number:");
phno=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter the name:");
name=sc.nextLine();
System.out.println("Enter the no. of days taken for rent :");
days=sc.nextInt();
}
void compute()
{
if(days<=5)
charge=500*days;
else if(days<=10)
charge=500*5+(days-5)*400;
else
charge=500*5+400*5+(days-10)*200;
}
void display()
{
System.out.println("Bike No.\tPhone No.\tName\t\tNo. of dsys\t\tCharge");
System.out.println(bno+"\t\t"+phno+"\t\t"+name+"\t\t"+days+"\t\t"+charge);
}
}
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the name:");
name=sc.nextLine();
System.out.println("Enter marks in hindi:");
hindi=sc.nextInt();
System.out.println("Enter marks in english:");
english=sc.nextInt();
System.out.println("Enter marks in maths:");
maths=sc.nextInt();
System.out.println("Enter marks in computer:");
computer=sc.nextInt();
}
void calcavg()
{
average=(float)(hindi+english+maths+computer)/4;
if(average>=90)
grade="A++";
else if(average>=75 && average<=89)
grade="A";
else if(average>=60 && average<=74)
grade="B";
else if(average<60)
grade="C";
System.out.println("Grade="+grade);
}
void initialise()
{
name="Amit";
acno=1234673;
type="Savings";
bal=5000;
}
void depo(int a)
{
bal+=a;
}
void withdraw(int a)
{
if(bal-a<1000)
System.out.println("Minimum balance should be Rs 1000");
else
bal-=a;
}
void print()
{
System.out.println("Name:"+name);
System.out.println("Account Number:"+acno);
System.out.println("Account Type:"+type);
System.out.println("Balance:"+bal);
}
float compute()
{
if(consumerno<=100)
return unitconsumed*1.20f;
else if(consumerno>100 && consumerno<=200)
return unitconsumed*2.20f;
else if(consumerno>200 && consumerno<=300)
return unitconsumed*3.20f;
else
return unitconsumed*4.00f;
}
void display()
{
System.out.println("Consumer Name\tConsumer No\tUnit Consumed\tBill
Amount");
System.out.println(name+"\t"+consumerno+"\t\t"+unitconsumed+"\t\t"+compute());
}
}
8. Write a program with the following specifications:
Class : Empl
Data Members:
Emp_No : To store the employee number
Name : To store the name of the employee
Basic : To store the basic salary of an employee
DA : To store the dearness allowance of an employee
HRA : To store the House Rent Allowance of an employee
TA : To store the Travelling Allowance of an employee
PF : To store the Provident Fund of an employee
Gross : To store the Gross Salary
Member Methods:
get ( ) : To accept Employee No., Name and Basic Salary of the
employees
calcu ( ) : To calculate the Gross Salary based on the following
condition:
void calcu()
{
if(basic>=20000)
{
da=53/100f*basic;
ta=12/100f*basic;
hra=10/100f*basic;
pf=8/100f*basic;
}
else if(basic>=10000 && basic<20000)
{
da=45/100f*basic;
ta=10/100f*basic;
hra=12/100f*basic;
pf=7.5f/100*basic;
}
else
{
da=40/100f*basic;
ta=8/100f*basic;
hra=14/100f*basic;
pf=7f/100*basic;
}
gross=(basic+da+ta+hra)-pf;
}
void display()
{
System.out.println("Employee No.\tName\tGross Salary\tPF");
System.out.println(emp_no+"\t\t"+name+"\t"+gross+"\t"+pf);
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the product code:");
product_code=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter the flavour:");
flavour=sc.nextLine();
System.out.println("Enter the pack type:");
pack_type=sc.nextLine();
System.out.println("Enter the pack size:");
pack_size=sc.nextInt();
System.out.println("Enter the product price:");
product_price=sc.nextInt();
}
void discount()
{
product_price=product_price-10;
}
void display()
{
System.out.println("Product Code\tFlavour\t\tPack Type\tPack Size\tProduct
Price");
System.out.println(product_code+"\t\t"+flavour+"\t\t"+pack_type+"\t\t"+pack_size+"\t\t"
+product_price);
}
float total_cost(int N)
{
return N*price;
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the BOOK NO.:");
book_no=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter the BOOK TITLE:");
book_title=sc.nextLine();
System.out.println("Enter the BOOK PRICE:");
price=sc.nextFloat();
}
void purchase()
{
Scanner sc=new Scanner(System.in);
int p;
System.out.println("Enter the number of copies to be purchased:");
p=sc.nextInt();
System.out.println("TOTAL COST="+total_cost(p));
}
void calfuel()
{
if(dist<=1000)
fuel=500;
else if(dist>1000 && dist<=2000)
fuel=1100;
else
fuel=2200;
}
void feedinfo()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Flight Number:");
fl_no=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter the Destination:");
dest=sc.nextLine();
System.out.println("Enter the Distance:");
dist=sc.nextInt();
calfuel();
}
void showinfo()
{
System.out.println("Flight No.:"+fl_no);
System.out.println("Destination:"+dest);
System.out.println("Distance:"+dist);
System.out.println("Fuel:"+fuel);
}
float calc()
{
if(nod*tariff<=10000)
return nod*tariff;
else
return 1.05f*nod*tariff;
}
void checkin()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Room Number:");
rno=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter the Name:");
name=sc.nextLine();
System.out.println("Enter the Tariff:");
tariff=sc.nextFloat();
System.out.println("Enter the No. of days:");
nod=sc.nextInt();
}
void checkout()
{
System.out.println("Room Number:"+rno);
System.out.println("Name:"+name);
System.out.println("Tariff:"+tariff);
System.out.println("No. of days:"+nod);
System.out.println("Amount:"+calc());
}
However, every customer has to pay Rs.180 per month as monthly rent for availing the
service.
Ans. import java.util.*;
class Telephone //Question 13
{
int prv,pre,call;
String name;
double amt,total;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the previous meter reading:");
prv=sc.nextInt();
System.out.println("Enter the present meter reading:");
pre=sc.nextInt();
sc.nextLine();// dummy input
System.out.println("Enter the name:");
name=sc.nextLine();
}
void cal()
{
call=pre-prv;
if(call<=100)
amt=0;
else if(call<=200)
amt=0.90f*call;
else if(call<=400)
amt=0.80f*call;
else
amt=0.70f*call;
total=180+amt;
}
void display()
{
System.out.println("Name\tCalls Made\tAmount\tTotal Amount");
System.out.println(name+"\t"+call+"\t\t"+amt+"\t"+total);
}
}
14. Define a class called Number having the following members:
Data Members:
lLimit : Lower limit of int type
uLimit : Upper limit of int type
Member Functions:
void getual( ) : To accept the lower and upper limit to depict a range.
boolean isArmstrong(int n) : Checks and returns true if 'n' is an armstrong
number, otherwise return false.
void display ( ) : It displays all armstrong numbers between the given
range.
Ans. import java.util.*;
class Number //Question 14
{
int lLimit,uLimit;
void getval()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the lower limit:");
lLimit=sc.nextInt();
System.out.println("Enter the upper limit:");
uLimit=sc.nextInt();
}
boolean isArmstrong(int n)
{
int t=n,d,s=0;
while(t!=0)
{
d=t%10;
s=s+d*d*d;
t=t/10;
}
if(s==n)
return true;
else
return false;
}
void display()
{
int i;
for(i=lLimit;i<=uLimit;i++)
{
if(isArmstrong(i))
System.out.println(i);
}
}
}
Chapter 11: Constructors
Practice Questions
--------------->Objective-Type Questions<--------------
Fill in the blanks:
1. A constructor is a Function defined in a class with name same as that of the class.
2. Constructor is invoked when an object is created.
3. A constructor that does not have any argument is called Default Constructor.
4. A constructor that takes the arguments is called Parameterised Constructor.
5. The class is the implicit return type of a constructor function.
------------->Subjective-Type Questions<--------------
A. Answer the following questions:
1. What is a constructor? Why is it needed in a program?
Ans. Constructor is a function that have the same name as the class and is
automatically invoked during creation of an object.
It is needed for:
a) Allocate memory space for an object.
b) Initialize data members within an object.
2. State the characteristics of a constructor.
Ans. Constructor is a member function of a class having the following
characteristics:
1. It has same name as the class-name.
2. It cannot have a return type, not even void is used, because
the implicit return type of a constructor is the class itself.
3. It follows the usual rules of accessibility as other members of
a class and therefore access modifiers can be applied to it.
4. It gets called automatically whenever an object is created.
5. It is usually used to initialize the members of the class with legal
initial values.
3. How are constructors invoked?
Ans. Constructor function gets invoked automatically whenever an object is
created.
4. Why do we need a constructor as a class member? [ICSE 2007]
Ans. Whenever an object is created, it must be constructed usually with legal
initial values automatically without being specified by the programmer. This will
immensely relieve the programmer from initializing values of objects for large
programs and hence the need for constructor.
5. State the difference between function and constructor. [ICSE 2005]
Ans. Difference between function and constructor:
Function Constructor
Its name is different as the name Its name is same as the class-
of the class. name.
Its return-type should be No return-type needs to be
specified. specified.
6. How are private constructors called?
Ans. Private constructors can be invoked only when an object is being created
only within the same class block.
7. What are the different types of constructors available in Java?
Ans. Parameterised Constructor and Non-Parameterised Constructor.
8. What is a default constructor? [ICSE 2006]
Ans. Default Constructor refers to a non-parameterised constructor that
initializes data members with default legal values.
9. Point out the difference between implicit and explicit default constructors.
Ans. Implicit default constructor is a constructor which gets created
automatically by the JVM (which initializes the data members with default initial
values) incase the class do not have a constructor explicitly defined by the user.
Explicit default constructor is a non-parameterised constructor defined by the
programmer to initialize the data-members within a class with default initial
values.
10. What are Temporary Objects? How are they created, explain with the help
of an example?
Ans. An object that do not have a name and exist as long as the line is being
executed is called Temporary or Anonymous object. Temporary or Anonymous
objects or instances are the ones that live in the memory as long as it is being
used or referenced in an expression and after that it dies. For example,
public class temp
{
int a,b;
temp(int x, int y)
{
a=x;
b=y;
}
void show()
{
System.out.println(a+","+b);
}
static void test( )
{
new temp(1,2).show( ); /*Temporary object is being called to invoke
} show( ) function.*/
}
11. What is constructor overloading? Illustrate it with the help of an example.
Ans. Multiple constructors of a class having different parameter lists in a class is
termed as constructor overloading. For example,
class Cuboid
{
double width;
double height;
double depth;
Cuboid( ) //Constructor with no parameter.
{
width=0;
height=0;
depth=0;
}
Cuboid(double n) //Constructor with single parameter
{
width=height=depth=n;
}
Cuboid(double w, double h,double d)
//Constructor with 3 parameters
{
width=w;
height=h;
depth=d;
}
void displayVolume()
{
double vol;
//Compute volume
vol= width*height*depth;
System.out.println("The Volume is="+vol);
}
static void createObjects()
{
Cuboid mycuboid1=new Cuboid();
//Calls the first constructor version.
Cuboid mycuboid2=new Cuboid(2.0);
//Calls the 2nd constructor version.
Cuboid mycuboid3=new Cuboid(1.5,2.5,4.5);
//Calls the 3rd constructor version.
mycuboid1.displayVolume( );
mycuboid2.displayVolume( );
mycuboid3.displayVolume( );
}
}
12. What is a destructor? Is destructor function necessary in Java? If no,
explain why.
Ans. Destructor is a function whose purpose is to deallocate memory space for an
object which was allocated by the constructor. But Java uses a unique automatic
method of deallocation of memory called garbage collection. This happens when
no references to an object exist, that object isassumed to be no longer needed,
and therefore the memory occupied by the object can be reclaimed. Since
garbage collection happens automatically in Java, there is no need of explicitly
defining a destructor function in a class.
13. What is the implicit return type of a constructor function?
Ans. The implicit return type of a constructor is the class type.
14. Enter any two variables through constructor with parameters and write a
program to swap and print the values. [ICSE 2005]
Ans. class Swap
{
int a,b;
Swap(int x, int y)
{
a=x;
b=y;
}
void change()
{
int t;
t=a;
a=b;
b=t;
System.out.println(a+" "+b);
}
}
15. What is the default initial value of a boolean variable datatype?
[ICSE2009]
Ans. The default initial value of boolean variable is false.
B. Find the errors in the following program and rectify it:
class Myclass
{
int a,b;
void Myclass(int x, int y)
{
a=x;
b=y;
}
int Myclass(int x)
{
a=b=x;
}
void show( )
{
System.out.println(a+ " "+y);
}
public static void main(String args[ ])
{
Myclass ob1=new Myclass( );
Myclass ob2=new Myclass(12.3,14.6,15);
Myclass ob3=new Myclass(7);
ob1.ob2.ob3.show( );
}
}
Ans. class Myclass
{
int a,b;
Myclass(int x, int y)
{
a=x;
b=y;
}
Myclass(int x)
{
a=b=x;
}
void show( )
{
System.out.println(a+ " "+y);
}
public static void main(String args[ ])
{
Myclass ob1=new Myclass(5,6 );
Myclass ob2=new Myclass(7);
ob1.show( );
ob2.show( );
}
}
C. Consider the following code and answer the questions that
follow:
class academic
{
int x,y;
void access( )
{
int a,b;
academic student=new academic( );
System.out.println(Object Created");
}
}
i) What is the object name of the class?
ii) Name the instance variables used in the class.
iii) Write the name of local variables used in the program.
iv) Give the type of function being used and its name.
Ans. i) student
ii) x and y
iii) a and b
iv) Type: Procedural function
Name: access()
D. Consider the following code and answer the questions that
follow:
class Today
{
static int a;
char b;
void input( )
{
a=20;
b='Z';
}
void convert( )
{
char c=(char)(a+b);
System.out.println(c);
}
public static void main( )
{
Today t=new Today( );
t.input( );
t.convert( );
}
}
Based on the above given piece of code, answer the questions which follow:
i) Name the instance, class and local variables.
ii) What is the name of the constructor of the above class?
iii) Explain the line: Today t=new Today( );
void compute()
{
int volume;
volume=length*breadth*height;
System.out.println("Volume="+volume);
}
}
2. Define a class called Friend, having members as:
Data Members: Name, Address, Favourite hobby
Member Functions:
i) Constructor to initialize the data members.
ii) To display the details.
Also create the main( ) and create 2 objects in it and initialize it with
information of two of your friends and display it, by calling the above
functions.
Ans. class Friend //Question 2
{
String name,address,hobby;
Friend(String n, String a, String h)
{
name=n;
address=a;
hobby=h;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Address="+address);
System.out.println("Favourite Hobby="+hobby);
}
FourSide(int l,int b)
{
length=l;
breadth=b;
}
void display()
{
int area;
area=length*breadth;
System.out.println("Area="+area);
}
void compute()
{
s=(n*(n+1))/2;
}
void display()
{
System.out.println("Sum="+s);
}
}
5. Define methods in a class named Algebra to find the difference between
the following equations:
f1(x)=x2 + 2x +15
f2(y)= – y2 – 13y + 12
f3(x,y)=f1(x) – f2(y)
where x and y are both of double data type.
Ans. class Algebra //Question 5
{
static double f1(double x)
{
return x*x+2*x+15;
}
void convert()
{
length=Conversion.mTocm(length);
}
void compute()
{
int area;
convert();
area=Conversion.multiply(length,breadth);
System.out.println("Area="+area);
}
}
7. Design a class named Numbers, which will contain the following members:
Data Members: a , b and c of int data type.
Member Functions:
i) Parameterized constructor to initialize a and b.
ii) void show( ) to display the contents of a, b and c.
iii) void compute( ) to add a and b and store it in c.
In the main( ) create an object and initialize a and b with any value and add a
and b by invoking the compute( ) function and display the contents of a, b
and c using show( ) function.
Ans. class Numbers //Question 7
{
int a,b,c;
Numbers(int x,int y)
{
a=x;
b=y;
}
void show()
{
System.out.println(a+" "+b+" "+c);
}
void compute()
{
c=a+b;
}
SumIntegers()
{
a=b=0;
}
SumIntegers sum(SumIntegers p)
{
if(a+b>p.a+p.b)
return this;
else
return p;
}
static
{
sum=count=0;
}
SumDemo(int p)
{
n=p;
}
void addIt()
{
sum+=n;
count++;
}
void calculate()
{
c=Average.calc(a,b);
System.out.println(c);
}
}
3. Create a class named Number with the following members:
Data members: a of int data type.
Member Functions:
i) Parameterized constructor to initialize the data member.
ii) Default constructor to initialize the data member with 0.
iii) To display 'a' only.
iv) Which accepts an instance of Number class as parameter and creates
another object, whose a will contain the sum the a’s of the current and the
passed object. This function should return the object newly instantiated.
Also create a main( ) to show its implementation.
Ans. class Number //Question 3
{
int a;
Number(int p)
{
a=p;
}
Number()
{
a=0;
}
void display()
{
System.out.println(a);
}
Number sum(Number ob)
{
Number s=new Number();
s.a=a+ob.a;
return s;
}
Number(int x)
{
a=x;
}
void add()
{
b+=a;
}
void display()
{
System.out.println(a);
}
void roundIt()
{
int b;
b=(int)(a+0.5f);
System.out.println("Rounded Off="+b);
}
void calculate()
{
if(units<=100)
bill=units*1;
else if(units<=200)
bill=100*1+(units-100)*1.50f;
else
bill=100*1+100*1.50f+(units-200)*2.00f;
bill=hire+bill;
}
void display()
{
System.out.println("Phone Number="+phone);
System.out.println("Name="+name);
System.out.println("Hire Charge="+hire);
System.out.println("Units Consumed="+units);
System.out.println("Bill Amount="+bill);
}
}
8. Define a class Taximeter having the following description:
Data members/instance variables:
int taxino : to store taxi number
String name : to store passenger’s name
int km : to store number of kilometres travelled
Member functions:
Taximeter( ) : constructor to initialize taxino to 0, name to "" and km to 0.
input( ) : to store taxino,name,km
calculate( ) : to calculate bill for a customer according to given
conditions:
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the taxi number:");
taxino=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter the name:");
name=sc.nextLine();
System.out.println("Enter the kilometers travelled:");
km=sc.nextInt();
}
int calculate()
{
int bill,rate;
if(km==1)
rate=25;
else if(km<=6)
rate=10;
else if(km<=12)
rate=15;
else if(km<=18)
rate=20;
else
rate=25;
bill=km*rate;
return bill;
}
void display()
{
System.out.println("Iaxi No.\tName\tKilometres travelled\tBill amount");
System.out.println(taxino+"\tt"+name+"\t"+km+"\t\t"+calculate());
}
}
9. Create a class which will contain the following components:
Data Members: a and b of int type.
Member Functions:
i) Constructor to initialize a and b.
ii) Return the sum of a and b.
iii) To display the value of a and b.
Also create a static function which accepts two objects as parameters and
print a and b of the object whose sum is the maximum.
In the main( ) create two objects, initialize them and display the data
members of that object whose sum of the data-members is the maximum.
Ans. class Question9
{
int a,b;
Question9(int x,int y)
{
a=x;
b=y;
}
int sum()
{
return a+b;
}
void display()
{
System.out.println(a+" "+b);
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the product code:");
product_code=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter the flavour:");
flavour=sc.nextLine();
System.out.println("Enter the pack type:");
pack_type=sc.nextLine();
System.out.println("Enter the pack size:");
pack_size=sc.nextInt();
System.out.println("Enter the product price:");
product_price=sc.nextInt();
}
void discount()
{
product_price-=10;
}
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);
System.out.println("Product price:"+product_price);
}
void salaryCal()
{
specialAlw=25/100.0*basicPay;
pf=11/100.0*basicPay;
gross=basicPay+specialAlw+conveyanceAlw;
netSalary=gross-pf;
AnnualSal=12*netSalary;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Basic Pay="+basicPay);
System.out.println("Special Allowance="+specialAlw);
System.out.println("Conveyance Allowance="+conveyanceAlw);
System.out.println("Gross="+gross);
System.out.println("Provident Fund="+pf);
System.out.println("Net Salary="+netSalary);
System.out.println("Annual Salary="+AnnualSal);
}
double findInterest()
{
double ci;
ci=pamt*Math.pow(1+rate/100,time)-pamt;
return ci;
}
void printData()
{
System.out.println("Principal:"+pamt);
System.out.println("Rate:"+rate);
System.out.println("Time:"+time);
}
void calculate()
{
float cost;
if(no_of_units<=50)
cost=0;
else if(no_of_units<=150)
cost=50*0+(no_of_units)*0.80f;
else if(no_of_units<=200)
cost=50*0+100*0.80f+(no_of_units-150)*1.00f;
else
cost=50*0+100*0.80f+200*1.00f+(no_of_units-350)*1.20f;
amount=rent + cost;
}
PhoneBill()
{
customerName="Raju";
phoneNumber=259461;
no_of_units=50;
rent=100;
amount=100;
}
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Customer name:");
customerName=sc.nextLine();
System.out.println("Enter the Phone Number:");
phoneNumber=sc.nextLong();
System.out.println("Enter number of units consumed:");
no_of_units=sc.nextInt();
System.out.println("Enter rent:");
rent=sc.nextInt();
calculate();
}
void display()
{
System.out.println("Customer Name:"+customerName);
System.out.println("Phone Number:"+phoneNumber);
System.out.println("Number of units consumed:"+no_of_units);
System.out.println("Rent:"+rent);
System.out.println("Amount:"+amount);
}
}
14. Define a class Sports with following descriptions:
Data members:
s_code of type long
s_name of type (String)
fees of type integer
duration of type integer
Member Functions:
i) Constructor to assign initial values of s_code as 1001, s_name as "Cricket", fees as
500, duration as 70.
ii) A function newSports( ) which allows user to enter s_code, s_name and duration.
Also assign the values to fees as per the following conditions:
s_name Fees
Table Tennis 2000
Swimming 4000
Football 3000
iii) A function displaySports( ) to display all the details.
Ans. //Question 14
import java.util.*;
class Sports
{
long s_code;
String s_name;
int fees;
int duration;
Sports()
{
s_code=1001;
s_name="Cricket";
fees=500;
duration=70;
}
void newSports()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Sports code:");
s_code=sc.nextLong();
sc.nextLine();//dummy input
System.out.println("Enter the Sports name:");
s_name=sc.nextLine();
System.out.println("Enter the duration:");
duration=sc.nextInt();
if(s_name.equals("Table Tennis"))
fees=2000;
else if(s_name.equals("Swimming"))
fees=4000;
else if(s_name.equals("Football"))
fees=3000;
}
void displaySports()
{
System.out.println("Sports Code:"+s_code);
System.out.println("Sports Name:"+s_name);
System.out.println("Duration:"+duration);
System.out.println("Fees:"+fees);
}
}
15. Create a class called GeneratePrime which will be used to generate 'n' number
of prime numbers.
The class should have the following members:
Data Members: n of int data type.
Member Functions:
i) Parameterized constructor to initialize the value of n.
ii) Method called isPrime( ) which accepts an integer as a parameter and return true
if it is a prime number otherwise return false.
iii) Method called display( ) which displays the first n prime numbers by calling the
above function.
Ans. //Question 15
import java.util.*;
class GeneratePrime
{
int n;
GeneratePrime(int x)
{
n=x;
}
boolean isPrime(int p)
{
int i,c=0;
for(i=1;i<=p;i++)
{
if(p%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
void display()
{
int i=0,p=2;
while(i<n)
{
if(isPrime(p))
{
System.out.print(p+" ");
i++;
}
p++;
}
}
}
16. Create a class called PrimeDigits to find the sum of the prime digits in an integer. The
class should have the following members.
Data Members: n of int data type.
Member Functions:
i) Parameterized constructor to initialize the value of n.
ii) Method called isPrime( ) which accepts an integer as a parameter and return true if it is
a prime number otherwise return false.
Static Method called sumOfPrimeDigits( ) which accepts an integer as a parameter and find
the sum of prime digits only.
Ans. //Question 16
import java.util.*;
class PrimeDigits
{
int n;
PrimeDigits(int x)
{
n=x;
}
boolean isPrime(int p)
{
int i,c=0;
for(i=1;i<=p;i++)
{
if(p%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
long factorial(int p)
{
int i;
long f=1;
for(i=1;i<=p;i++)
{
f=f*i;
}
return f;
}
void sumOfseries1()
{
int i;
long f;
double s=0;
for(i=1;i<=n;i++)
{
f=factorial(i);
s=s+x/f;
}
System.out.println("Sum of the Series="+s);
}
void sumOfseries2()
{
int i;
long f;
double s=0;
for(i=1;i<=n;i++)
{
f=factorial(i+1);
s=s+x/f;
}
System.out.println("Sum of the Series="+s);
}
void sumOfseries3()
{
int i;
long f;
double s=0;
for(i=1;i<=n;i++)
{
f=factorial(i+1);
if(i%2==0)
s=s-x/f;
else
s=s+x/f;
}
System.out.println("Sum of the Series="+s);
}
}
18. Create a class named Rounding which contains the following members:
Data members: n and r of double type
Member Functions:
i) Constructor to read a real number from the keyboard into n.
ii) to round off n to two places of decimal and store it in r.
iii) to display the value of the data members.
Ans. //Question 18
import java.util.*;
class Rounding
{
double n,r;
Rounding()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a real number:");
n=sc.nextDouble();
}
void roundOff2()
{
double t=n*100;
r=Math.round(t)/100.0;
}
void display()
{
System.out.println("Original Number="+n);
System.out.println("Rounded Off to 2 places of decimal="+r);
}
}
Chapter 12: String Manipulation
A. Answer the following questions:
1. What is a String? Explain its use.
Ans.The String data type is a class defined in the java.lang package and every variable
that you create of String data type is actually an object or object reference of the String
class.
Using String variable in Java it is possible to manipulate strings i.e. a group of characters,
by extracting characters and manipulate it.
2. Why is String considered to be immutable?
Ans. String is considered to be immutable as it is not possible to insert or remove
characters from it. Moreover every time a new value is assigned to a String variable it
occupies a different memory location as compared to the previous allocation.
3. What are the common methods of initializing String objects?
Ans. A string may be initialised either using a String reference. For example,
String s="COMPUTER";
Or initialised using a constructor while creating a String object. For example,
String s=new String("COMPUTER");
4. What is concatenation? Give an example to show how '+' operator is used to
perform concatenation.
Ans. Joining of two or more strings to form a single string is termed as concatenation.
For example,
String a="AB", b="CD",c;
c=a+b;
Thus the value of the variable c is "ABCD".
5. Explain, with the help of an example, the functionality of toString( ).
Ans. The toString( ) function in Java is used to convert a value of any data type to
String. For example, the following statements convert a value (say 45) stored in an
integer variable to a String.
int a=45;//45 is stored in int type variable
String s=Integer.toString(a); // Content of variable a is converted to String.
6. Give the code to extract the first and the last character of a string in Java.
Ans. In case the String is stored in a variable named ‘s’.
To extract the first character use: s.charAt(0)
To extract the last character use: s.charAt(s.length( )-1)
7. State the use of the following String member functions, along with examples:
i) substring( )
ii) replace( )
iii) trim( )
Ans. i)substring( ) : It is used a part of a string from a given string . It has two
syntaxes:
a) substring(s,e): Extracts characters from s to e-1(s and e
are indexes and should be of int type). For example,
“INDIA”.substring(1,4) will give “NDI”.
b) substring(s): Extracts characters from s till the end of the
string (s is an index and should be of int type). For example,
“Laserjet”.substring(5) will yield ”jet”.
ii) replace( ) :It is used to replace a character/string from a string with another
character/string. Its general syntax is:
replace(c,d): It is used to replace the character c with character d. For example,
“BEETEL”.replace(‘E’,’O’) will yield “BOOTOL”
iii) trim() : It is used to remove leading and trailing spaces in a string. For example,
“ COMPUTER ”.trim( ) will yield “COMPUTER”
8. Give the difference between the following functions:
i) = = and equals( ) [ICSE 2008]
ii) toLowerCase( ) and toUpperCase( ) [ICSE 2005]
iii) startsWith( ) and endsWith( )
iv) indexOf( ) and lastIndexOf( ) [ICSE 2010]
Ans. i)
== equals( )
Checks whether two strings belong to Checks whether two string quantities
the same memory location or not. are same or not.
Checks whether two quantities are Checks only two string quantities are
equal or not. The quantities may be same or not.
any data type other than string.
ii)
toLowerCase( ) toUpperCase( )
Converts a given character or a string to Converts a given character or a string to
lower case. upper case.
iii)
startsWith( ) endsWith( )
Checks whether a string begins with a Checks whether a string ends with a
certain character or a string or not and certain character or a string or not and
returns true or false accordingly. returns true or false accordingly.
iv)
indexOf( ) lastIndexOf( )
Searches for a certain character or string Searches for a certain character or string
from to left to right in a given string and from to right to left in a given string and
return the index for the first occurrence of return the index for the first occurrence of
the found character or string otherwise the found character or string otherwise
return -1. return -1.
9. Explain compareTo( ) function, with respect to the values that it returns.
[ICSE 2010]
Ans. The compareTo( ) function is used to lexicographically check two strings where
the Unicode differs and accordingly return their difference.
The value returned by the compareTo( ) function is the difference between the
corresponding Unicodes of the characters, where it differs. If at no point the character
differs in the strings a 0 is returned.
For example,
System.out.println("abc".compareTo("abde"));
Will display –1, as the strings differ from the character at position 2 (i.e. 'c' and 'd'). The
Unicode for 'c' is 99 and 'd' is 100 and therefore their difference is –1.
System.out.println("COMPUTRONICS".compareTo("COMPUTER"));
Will display 13, as the pair of strings differ from the character at position 6 (i.e. 'R' and 'E').
The Unicode for 'R' is 82 and 'E' is 69 and therefore their difference is 13.
If there is no index position at which they differ, then the shorter string lexicographically
precedes the longer string. In this case, it returns the difference of the lengths of the strings.
For example,
System.out.println("AB".compareTo("ABCD"));
will display –2 as "AB".length( )–"ABCD".length( )=2 – 4=–2
10. Differentiate between compareTo( ) and equals( ) methods. [ICSE 2006]
Ans.
compareTo( ) equals( )
Checks two strings lexicographically. Checks two strings for equality.
Returns the first difference between the Returns either a true or a false.
Unicode of the characters where it differs.
Return type is int. Return type is Boolean.
11. What is Unicode? How can you get the unicode value of a Java character?
Ans. Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages. Using this system of encoding it is possible
to represent 65,536 characters.
To get the Unicode value of a Java character simply type-cast it with int. For example,
char x='B';
int p=(int)x; //It will assign the Unicode of the character x into p.
12. Explain what arithmetic operation can be performed with Java characters.
Ans. You can use increment or decrement operator with character variables to get the previous
or next character. For example, if
char x='B';
char y='d';
x++;
y--;
x++ will make the character x to 'C' and will make the character y to 'c'.
B. Answer as directed:
1. Give the output of the following program fragment:
String s=new String("He went to the market");
String r;
r=s.replace("went","is going");
System.out.println(r);
ii) HiequalsHi→true
Hiequalsthere→false
HiequalsHI→false
HiequalsIgnoreCaseHI→true
}
}
14. Write a method to accept a name as parameter and print the initial first and
then the title.
Example,
Parameter: AJAY PRATAP SINGH RATHORE
Output: A.P.S. RATHORE
Ans. import java.util.*;
class Question14
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,w="",last;
int i,l;
char x,y;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s.toUpperCase();
s=" "+s;
l=s.lastIndexOf(' ');
last=s.substring(l+1);
for(i=0;i<l;i++)
{
if(s.charAt(i)==' ' && s.charAt(i+1)!=' ')
w=w+s.charAt(i+1)+".";
}
w=w+last;
System.out.println(w);
}
}
15. Write a program to input a string and print out the text with the uppercase and
lowercase letters reversed, but all other characters should remain the same as
before. [ICSE 2008]
Example :
INPUT : WelComE TO School
OUTPUT : wELcOMe to sCHOOL
Ans. import java.util.*;
class Question15
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,rs="";
int i;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x>='A' && x<='Z')
x=(char)(x+32);
else if(x>='a' && x<='z')
x=(char)(x-32);
rs=rs+x;
}
System.out.println("Reversed Sentence:"+rs);
}
}
16. Write a program to input a sentence and change it to its Title case. Title case
means to change the first alphabet of every word to capital and rest to small
letters.
Ans. import java.util.*;
class Question16
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,t="",w="";
int i;
char x,y;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s.toLowerCase();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
y=w.charAt(0);
y=Character.toUpperCase(y);
w=y+w.substring(1);
t=t+w+" ";
w="";
}
}
System.out.println(t);
}
}
17. Write a program to input a sentence and display only those words which begin
with alphabet 'A' or 'a'.
Ans. import java.util.*;
class Question17
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,t="",w="";
int i;
char x,y;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s.toLowerCase();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
y=w.charAt(0);
if(y=='a' || y=='A')
t=t+w+" ";
w="";
}
}
System.out.println(t);
}
}
18. Write a program to input a sentence and display only those words which end
with alphabet 'A' or 'a'.
Ans. import java.util.*;
class Question18
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,t="",w="";
int i;
char x,y;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s.toLowerCase();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
y=w.charAt(w.length()-1);
if(y=='a' || y=='A')
t=t+w+" ";
w="";
}
}
System.out.println(t);
}
}
19. Write a program to input a sentence and display only those words which begin
with a vowel.
Ans. import java.util.*;
class Question19
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,t="",w="";
int i;
char x,y;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s.toLowerCase();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
y=w.charAt(0);
if(y=='a' || y=='A' || y=='e' || y=='E' || y=='i' ||
y=='I' || y=='o' || y=='O' || y=='u' || y=='U')
t=t+w+" ";
w="";
}
}
System.out.println(t);
}
}
20. Write a program to input a sentence and display only those words which begin
and ends with the same alphabet.
Ans. import java.util.*;
class Question20
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,t="",w="";
int i;
char x,y,z;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s.toLowerCase();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
y=w.charAt(0);
z=w.charAt(w.length()-1);
if(y==z)
t=t+w+" ";
w="";
}
}
System.out.println(t);
}
}
21. Write a program to input a sentence and print the longest word, assume that
there is only one longest word in the given sentence.
Ans. import java.util.*;
class Question21
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,lng="",w="";
int i,f=0;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
if(f==0)
{
lng=w;
f=1;
}
if(w.length()>lng.length())
lng=w;
w="";
}
}
System.out.println("Longest Word="+lng);
}
}
22. Write a program to print the smallest word in a given sentence, assume that
there is only one smallest word in the given sentence.
Ans. import java.util.*;
class Question22
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,sma="",w="";
int i,f=0;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
if(f==0)
{
sma=w;
f=1;
}
if(w.length()<sma.length())
sma=w;
w="";
}
}
System.out.println("Smallest Word="+sma);
}
}
23. Write a program to input a sentence and display only those words which have
even number of vowels.
Ans. import java.util.*;
class Question23
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,t="",w="";
int i,c=0;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
{
w=w+x;
if(x=='a' || x=='A' || x=='e' || x=='E' || x=='i' ||
x=='I' || x=='o' || x=='O' || x=='u' || x=='U')
c++;
}
else
{
if(c%2==0)
t=t+w+" ";
w="";
c=0;
}
}
System.out.println(t);
}
}
24. Write a program to print the word with maximum number of vowels in a given
sentence. Assume that there is only one word having maximum number of
vowels.
Ans. import java.util.*;
class Question24
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,max="",w="";
int i,c=0,f=0,l=0;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
{
w=w+x;
if(x=='a' || x=='A' || x=='e' || x=='E' || x=='i' ||
x=='I' || x=='o' || x=='O' || x=='u' || x=='U')
c++;
}
else
{
if(f==0)
{
max=w;
l=c;
f=1;
}
else
{
if(c>l)
{
l=c;
max=w;
}
}
w="";
c=0;
}
}
System.out.println("Word having maximum number of vowels:"+max);
}
}
25. Write a program to input a sentence and print the word having least number of
vowels. Assume that there is only one word having least number of vowels.
Ans. import java.util.*;
class Question25
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,min="",w="";
int i,c=0,f=0,l=0;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
{
w=w+x;
if(x=='a' || x=='A' || x=='e' || x=='E' || x=='i' ||
x=='I' || x=='o' || x=='O' || x=='u' || x=='U')
c++;
}
else
{
if(f==0)
{
min=w;
l=c;
f=1;
}
else
{
if(c<l)
{
l=c;
min=w;
}
}
w="";
c=0;
}
}
System.out.println("Word having minimum number of vowels:"+min);
}
}
26. Write a method to accept a sentence as parameter and print the longest word
with least number of vowels in it. Assume that there is only one such word in the
given sentence.
Ans. import java.util.*;
class Question26
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,lng="",w="",min="";
int i,f=0,l=0,c=0;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
if(f==0)
{
lng=w;
f=1;
}
if(w.length()>lng.length())
lng=w;
w="";
}
}
f=0;
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
{
w=w+x;
if(x=='a' || x=='A' || x=='e' || x=='E' || x=='i' ||
x=='I' || x=='o' || x=='O' || x=='u' || x=='U')
c++;
}
else
{
if(w.length()==lng.length())
{
if(f==0)
{
min=w;
l=c;
f=1;
}
else
{
if(c<l)
{
l=c;
min=w;
}
}
}
w="";
c=0;
}
}
System.out.println("Longest Word having least number of vowels:"+min);
}
}
27. Write a program to input a sentence and print only those words which have all
the five vowels present in it (i.e. A, E, I, O, U), in a given sentence.
For example,
INPUT
Enter a sentence: EDUCATION IS A MUST FOR THE DEVELOPMENT
OF THE COUNTRY
OUTPUT
EDUCATION
Ans. import java.util.*;
class Question27
{
static void main()
{
Scanner sc=new Scanner(System.in);
String s,t="",w="";
int i,fa=0,fe=0,fi=0,fo=0,fu=0;
char x;
System.out.print("Enter a sentence:");
s=sc.nextLine();
s=s.trim();
s=s+" ";
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
{
w=w+x;
if(x=='a' || x=='A' ) fa=1;
if(x=='e' || x=='E') fe=1;
if(x=='i'|| x=='I') fi=1;
if(x=='o' || x=='O') fo=1;
if(x=='u' || x=='U') fu=1;
}
else
{
if(fa==1 && fe==1 && fi==1 && fo==1 && fu==1)
t=t+w+" ";
w="";
fa=fe=fi=fo=fu=0;
}
}
System.out.println("Word having all the five vowels:"+t);
}
}
28. Write a method to accept a word as parameter and print the alphabets in
alphabetical order.
e.g. Input: world
Output: DLORW
e.g. Input: HUMAN
Output: AHMNU
Ans. class Question28
{
static void alphabetical(String w)
{
w=w.toUpperCase();
int i;
char x;
String t="";
for(x='A';x<='Z';x++)
{
for(i=0;i<w.length();i++)
{
if(x==w.charAt(i))
t=t+x;
}
}
System.out.println(t);
}
}
29. Write a method to accept a word as parameter and return true if all its
alphabets are unique otherwise return false. Now use it in another function to
print those words whose all alphabets are unique in a given sentence.
Ans. import java.util.*;
class Question29
{
static boolean isUnique(String w)
{
int i,j;
boolean f=true;
for(i=0;i<w.length();i++)
{
for(j=i+1;j<w.length();j++)
{
if (w.charAt(i)==w.charAt(j))
f=false;
}
}
return f;
}
For example, to declare an object of size 10 for a class named Cuboid, you may
use,
Cuboid obj[ ]=new Cuboid[10];
or,
Cuboid[ ] obj=new Cuboid[10];
or,
Cuboid obj[ ];
obj=new Cuboid[10];
6. With the help of an example, show how arrays in Java are dynamic in nature.
Ans. Arrays in Java are always dynamic in nature in the sense that the size of an array is
specified at run-time. Here is an example, that takes an integer(say n) as input using
Scanner and then declares an integer array of size n.
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter the value of n:");
n=sc.nextInt( );
int a[ ]=new int [n];
Note that the array ‘a’ of size n is declared at runitime.
7. "Array variables are references to a block of elements". What do you understand
by this statement?
Ans. An array variable is always a reference to a block of memory and therefore
can be used to refer to a memory location which is referred by another array
variable.
For example,
int[ ] a = {100, 99, 98}; // "a" references the array object.
int[ ] b; // "b" doesn't refer to anything.
b = a; // Now "b" refers to the SAME array as "a"
b[1] = 0; // Also changes a[1] to 0 because a and b refer to the same array.
8. How do you determine the length of an array?
Ans. Length of an array refers to the number of elements in the array. To determine the
length of an array the following general syntax is used:
<array-name>.length( );
9. With the help of an example show how arrays are passed to a function as Call by
Reference.
Ans. An array when passed to a function, it is always passed as a reference, therefore any
changes made to the formal parameter is reflected by to the actual parameter.
The following example shows how this is performed:
class ArrayDemo
{
/*Method to double the value of each element in the
array.*/
static void doubleIt(int b[ ])
{
for(int i=0;i<b;i++)
{
b[i]=2*b[i];
}
}
public static void main(String args[ ])
{
int a[ ]={4,5,12,7,8,3};
System.out.println("Original Array...");
for(int i=0;i<6;i++)
System.out.print(a[i]+"\t");
doubleIt(a); //this is how you pass an array as
parameter.
System.out.println("Updated Array...");
for(int i=0;i<6;i++)
System.out.print(a[i]+"\t");
}
}
Output when main( ) is executed will be,
Original Array...
4 5 12 7 8 3
Updated Array...
8 10 24 14 16 6
10. Explain:
i) Linear Search ii) Binary Search
Ans. i) Linear Search: Linear Search is a search process technique that involves
checking each element sequentially with the given element to be searched for.
ii) Binary Search: Binary search is a search process technique where an
element to be searched is checked with the central element of the array and
depending upon its value, it is checked in the sub-array before the central
position or in the sub-array after the central position. The same search process
continues even with the sub-array.
11. Compare Linear Sorting, Selection Sorting and Bubble Sorting.
Ans. Linear Sorting: The linear sorting process checks each element of the array with
the remaining elements of the array after it. In case the array element is greater than
either of the remaining elements, the elements are interchanged. The process continues
until all elements are exhausted.
Bubble Sorting: The bubble sorting process checks adjacent elements of the array, i.e.
first element with the second element, the second element with the third element and the
process continues until all elements are exhausted. In case the array element is greater
than the adjacent element, the elements are interchanged. The process continues until all
elements are exhausted.
Selection Sort: During the selection sort process, an element is taken from the first and
from the remaining elements the smallest or largest number (for ascending or descending
order respectively) is found and interchanged.
12. Differentiate between Binary Search and Linear Search. [ICSE 2007]
Ans.
Disadvantages:
i) Arrays allow you to store elements of only one data type, i.e. only
homogeneous data can be stored, thus data of heterogeneous data type
cannot be stored, which is often required by a programmer.
ii) Arrays always require contiguous free memory location to be allocated for
storing elements. But there may be situations when the available memory
is discrete in nature and therefore array cannot be used to efficiently use
the memory.
B. Answer as directed:
1. What is the difference between these two statements:
i) int sum[ ]=new int[10] ii) sum[1]=10;
Ans. i) int sum[ ]=new int [10] is used to declare an integer array named ‘sum’ of size 10.
ii) sum[1]=10 on the other hand is used to assign the value 10 to the index position
1 in the array ‘sum’.
2. Write the correct form of the following 'float' arrays:
i) A1(2) ii) Name[2/5] iii) Roll[2;] iv) Matrix(5)
Ans. i) float A1[ ]=new float[2];
ii) float Name=new float[25];
iii) float Roll[]=new float[2];
iv) float Matrix[]=new float[5];
3. Write the value of individual array element.
int c[ ]={78,23,45,12,16};
Ans. c[0]=78, c[1]=23, c[2]=45, c[3]=12 and c[4]=16.
4. Give the proper array declaration for the following:
i) Declare an integer array, which can hold 25 values.
ii) Declare an integer array initialised with 12, 36, 49, 50, 67.
iii) Declare an array of float data type initialised to 13.7, 14.6, 19.3, 12.
Ans. i) int a[]=new int[25];
ii) int a[]={12,36,49,50,67};
iii) float a[]={13.7f, 14.6f,19.3f,12};
5. What will be the output of the following program:
class Output
{
public static void main(String args[])
{
int a[ ]={6,5,4,3,2,1};
int x;
for(x=5;x>=0;x– –)
{
System.out.println(a[x]);
}
}
}
Ans. 1
2
3
4
5
6
6. What will be the output of the following program?
class First
{
public static void main(String args[ ])
{
int a[ ]={5,1,15,20,25};
int i,j;
int m;
i=++a[1];
j=a[2]++;
m=a[i++];
System.out.print(i+" "+j+" "+m);
}
}
Ans. 3 15 16
7. What will be the output of the following program, when method invoke( ) is
called?
public class StringArray
{
void change(String arr[ ])
{
for(int i=0;i<arr.length;i++)
{
arr[i]=arr[i].substring(0,1).toUpperCase( )+arr[i].substring(1);
}
}
void invoke( )
{
String ar[ ]={"kolkata","gangtok","bangalore"};
for(int i=0;i<ar.length;i++)
System.out.println(ar[i]);
change(ar);
for(int i=0;i<ar.length;i++)
System.out.println(ar[i]);
}
}
Ans. kolkata
gangtok
bangalore
Kolkata
Gangtok
Bangalore
8. Find and correct the errors in the following program segment:
int n[ ] = (2,4,6,8,10);
for (int i = 0; i < = 5; i ++)
System.out.println("n[" + i + "] = " + n[i ]); [ICSE 2006]
Ans. int n[ ] = {2,4,6,8,10};
for (int i = 0; i < 5; i ++)
System.out.println("n[" + i + "] = " + n[i ]);
9. Identify error(s), if any, in the following program:
class First
{
public static void main(String args[ ])
{
int i;
int a[6]={0,1,8,7,6,4};
for(i=0;i<=a.length( );i++)
System.out.println(a[i]);
}
}
Ans. class First
{
public static void main(String args[ ])
{
int i;
int a[6]={0,1,8,7,6,4};
for(i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
18. Write a program to input 10 numbers into an integer array and find
the average of even as well as odd numbers separately.
Ans. import java.util.*;
class Question18
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int i,se=0,ce=0,so=0,co=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
if(a[i]%2==0)
{
se=se+a[i];
ce++;
}
else
{
so=so+a[i];
co++;
}
}
if(ce>0)
System.out.println("Average of even numbers:"+(float)se/ce);
else
System.out.println("No even numbers present");
if(co>0)
System.out.println("Average of odd numbers:"+(float)so/co);
else
System.out.println("No odd numbers present");
}
}
19. Create a method to accept a float type array as parameter and print
the average of the largest and smallest number.
Ans. class Question19
{
static void main(float a[])
{
int i;
float lar=0,sma=0;
for(i=0;i<a.length;i++)
{
if(i==0)
lar=sma=a[i];
if(a[i]>lar)
lar=a[i];
if(a[i]<sma)
sma=a[i];
}
System.out.println("Average of largest and smallest number:"+(float)(lar+sma)/2);
}
}
20. Write a program to input 10 numbers into an integer array and print
the position of the largest number.
Ans. import java.util.*;
class Question20
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int i,l=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
if(i==0)
l=a[i];
if(a[i]>l)
l=a[i];
}
System.out.println("Positions where largest number is present are:");
for(i=0;i<a.length;i++)
{
if(a[i]==l)
System.out.print(i+" ");
}
}
}
21. Create a method to accept an integer array as parameter and print
the position of the largest and smallest.
Ans. class Question21
{
static void main(int a[])
{
int i,l=0,s=0;
for(i=0;i<a.length;i++)
{
if(i==0)
s=l=a[i];
if(a[i]>l)
l=a[i];
if(a[i]<s)
s=a[i];
}
System.out.println("Positions where largest number is present are:");
for(i=0;i<a.length;i++)
{
if(a[i]==l)
System.out.print(i+" ");
}
System.out.println("\nPositions where smallest number is present are:");
for(i=0;i<a.length;i++)
{
if(a[i]==s)
System.out.print(i+" ");
}
}
}
22. Write a program to input 10 numbers into an integer array and print
the smallest prime number (if any) in the array. (Note that there may not
be any prime number in the array and therefore getting the smallest
prime number is beyond question and therefore you need to print a
relevant message to show its absence.)
Ans. import java.util.*;
class Question22
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int i,s=0,j,c,f=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c==2)
{
if(f==0)
{
s=a[i];
f=1;
}
if(a[i]<s)
s=a[i];
}
}
if(f==1)
System.out.println("Smallest Prime Number:"+s);
else
System.out.println("No Prime No. present");
}
}
23. Create a method to accept a String type array as parameter and print
the smallest word in it.
Ans. class Question23
{
static void smallest(String a[])
{
String s="";
int i;
for(i=0;i<a.length;i++)
{
if(i==0)
s=a[i];
if(a[i].length()<s.length())
s=a[i];
}
System.out.println("Smallest Word="+s);
}
}
24. Create a method to accept an array as parameter and print the second
largest number in it.
Ans. class Question24
{
static void secondLargest(int a[])
{
int i,l=0,sl=0,f=0;
for(i=0;i<a.length;i++)
{
if(i==0)
l=a[i];
if(a[i]>l)
l=a[i];
}
for(i=0;i<a.length;i++)
{
if(a[i]!=l)
{
if(f==0)
{
sl=a[i];
f=1;
}
if(a[i]>sl)
sl=a[i];
}
}
System.out.println("Second Largest Number="+sl);
}
}
25. Create a method to accept an array as parameter and print the
position of the second largest number in it.
Ans. class Question25
{
static void secondLargest(int a[])
{
int i,l=0,sl=0,f=0,p=0;
for(i=0;i<a.length;i++)
{
if(i==0)
l=a[i];
if(a[i]>l)
l=a[i];
}
for(i=0;i<a.length;i++)
{
if(a[i]!=l)
{
if(f==0)
{
sl=a[i];
p=i;
f=1;
}
if(a[i]>sl)
{
sl=a[i];
p=i;
}
}
}
System.out.println("Position of Second Largest Number="+p);
}
}
26. Write a program to input 10 numbers into an integer array and
replace all prime numbers in it (if any) by 0 and print the modified array.
For example, if the array contains the following elements:
}
}
27. Write a program to input an integer array and replace all Armstrong
numbers in it with 0 and display the modified array.
Ans. class Question27
{
static void main(int a[])
{
int i,j,s,t,d;
for(i=0;i<a.length;i++)
{
s=0;t=a[i];
while(t!=0)
{
d=t%10;
s+=d*d*d;
t=t/10;
}
if(s==a[i])
a[i]=0;
}
System.out.println("Modified Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
28. Write a program to input 10 numbers into an integer array and
interchange the largest number with the smallest number within the
array and print the modified array. Assume that there is only one largest
and smallest number.
For example, if array contains
Ans. import java.util.*;
class Question28
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int i,l=0,lp=0,s=0,sp=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
if(i==0)
{
s=l=a[i];
sp=lp=i;
}
if(a[i]>l)
{
l=a[i];
lp=i;
}
if(a[i]<s)
{
s=a[i];
sp=i;
}
}
a[lp]=s;
a[sp]=l;
System.out.println("Modified Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
29. Write a program to bubble-sort the following set of values in
ascending order: 5,3,8,4,9,2,1,l2,98,16 [ICSE 2005]
OUTPUT: 1 2 3 4 5 8 9 12 16 98
Ans. class Question29
{
static void main()
{
int a[]={5,3,8,4,9,2,1,12,98,16};
int i,j,t;
for(i=a.length-1;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println("Sorted Array:");
for(i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
30. Write a program to input 10 numbers into a float type array and
arrange the numbers in descending order using Selection Sorting
technique.
Ans. import java.util.*;
class Question30
{
static void main()
{
Scanner sc=new Scanner(System.in);
float a[]=new float[10],l;
int i,j,p;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextFloat();
}
for(i=0;i<a.length-1;i++)
{
l=a[i];p=i;
for(j=i+1;j<a.length;j++)
{
if(a[j]>l)
{
l=a[j];
p=j;
}
}
a[p]=a[i];
a[i]=l;
}
System.out.println("Sorted Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
31. Write a program to accept 15 integers from the keyboard, assuming
that no integer entered is a zero. Perform selection sort on the integers
and then print them in ascending order. [ICSE 2006]
Ans. import java.util.*;
class Question31
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[15],s,i,j,p;
System.out.println("Enter 15 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length-1;i++)
{
s=a[i];p=i;
for(j=i+1;j<a.length;j++)
{
if(a[j]<s)
{
s=a[j];
p=j;
}
}
a[p]=a[i];
a[i]=s;
}
System.out.println("Sorted Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
32. Write a program to input 10 numbers into an integer array and
arrange only the even numbers in ascending order using Bubble Sorting
technique.
Ans. import java.util.*;
class Question32
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],t,i,j;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=a.length-1;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]>a[j+1] && a[j]%2==0 && a[j+1]%2==0)
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println("Sorted Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
33. Write a program to input 10 numbers into an integer array and
arrange only the numbers at even positions in descending order using
Bubble Sorting technique.
Ans. import java.util.*;
class Question33
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],t,i,j;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=8;i>0;i-=2)
{
for(j=0;j<i;j+=2)
{
if(a[j]<a[j+2])
{
t=a[j];
a[j]=a[j+2];
a[j+2]=t;
}
}
}
System.out.println("Sorted Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
34. Write a program to input 10 numbers into an integer array and
reverse the array and print the modified array.
For example, if array contains
Ans. import java.util.*;
class Question34
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],t,i,j;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length/2;i++)
{
t=a[i];
a[i]=a[a.length-1-i];
a[a.length-1-i]=t;
}
System.out.println("Modified Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
35. Write a program to input 10 numbers into an integer array and
interchange the consecutive elements in it. That is, interchange a[0] with
a[1], a[2] with a[3], a[4] with a[5].
For example, if array contains
System.out.println("Modified Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
36. Write a program to input 10 numbers into an integer array and
interchange the elements of the first half with the corresponding
elements of the second half. That is, interchange a[0] with a[5], a[1] with
a[6], a[2] with a[7], a[3] with a[8] and a[4] with a[9].
For example, if array contains
while(ib<b.length)
c[ic++]=b[ib++];
System.out.println("Merged Array:");
for(ic=0;ic<c.length;ic++)
{
System.out.print(c[ic]+" ");
}
}
}
39. Write a program to input 10 numbers into an integer array and input
a position. Now delete the element at that position by shifting the rest of
the numbers to the left and insert a 0 at the end.
For example, if array contains
Notice that the last element i.e. 25 got removed after the shifting process.
Ans. import java.util.*;
class Question40
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],p,i,n;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Enter the number to insert:");
n=sc.nextInt();
System.out.println("Enter the position where to insert:");
p=sc.nextInt();
for(i=a.length-1;i>p;i--)
{
a[i]=a[i-1];
}
a[p]=n;
System.out.println("Modified Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
41. Write a program to input 10 positive or negative numbers (no zero)
into an integer array and shift all positive numbers to the beginning of
the array and negative numbers to the end of the array, without
changing the order of the numbers.
For example, if the array contains the following elements:
System.out.println("Modified Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
42. Write a program to input 10 numbers into an integer array and shift
all even numbers to the beginning of the array and odd numbers to the
end of the array, without changing the order of the numbers.
Ans. import java.util.*;
class Question42
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],t,i,j;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=a.length-1;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]%2!=0 && a[j+1]%2==0)
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println("Modified Array:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
43. Write a program to input 10 numbers into an integer array and print
those single-digit positive numbers which are not present in the array.
Ans. import java.util.*;
class Question43
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],x,i,f;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Single Digit Positive Numbers that are not present in the array
are:");
for(x=1;x<=9;x++)
{
f=0;
for(i=0;i<a.length;i++)
{
if(a[i]==x)
f=1;
}
if(f==0)
System.out.print(x+" ");
}
}
}
44. Write a program to input 10 numbers into an integer array and find
the frequency of each two-digit positive numbers present in it.
Ans. import java.util.*;
class Question44
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],x,i,c;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(x=10;x<=99;x++)
{
c=0;
for(i=0;i<a.length;i++)
{
if(a[i]==x)
c++;
}
if(c>0)
System.out.println("Frequency of "+x+"is="+c);
}
}
}
45. Create a method to accept an integer array as parameter and print
the frequency of each element in it.
Ans. class Question45
{
static void main(int a[])
{
int i,j,f,c;
for(i=0;i<a.length;i++)
{
f=0;
for(j=0;j<i;j++)
{
if(a[i]==a[j])
f=1;
}
if(f==0)
{
c=0;
for(j=i;j<a.length;j++)
{
if(a[i]==a[j])
c++;
}
System.out.println("Frequency of "+a[i]+"is="+c);
}
}
}
}
46. Write a program to input 10 numbers into an integer array and print
the number having maximum frequency.
Ans. import java.util.*;
class Question46
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,c,l=0,n=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length;i++)
{
c=0;
for(j=0;j<a.length;j++)
{
if(a[i]==a[j])
c++;
}
if(i==0)
{
l=c;
n=a[i];
}
if(c>l)
{
l=c;
n=a[i];
}
}
System.out.println("Number having maximum frequency="+n);
}
}
47. Write a program to input 10 numbers into an integer array and print
the number having least frequency.
Ans. import java.util.*;
class Question47
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10],i,j,c,s=0,n=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length;i++)
{
c=0;
for(j=0;j<a.length;j++)
{
if(a[i]==a[j])
c++;
}
if(i==0)
{
s=c;
n=a[i];
}
if(c<s)
{
s=c;
n=a[i];
}
}
System.out.println("Number having least frequency="+n);
}
}
48. Write a program to input 10 words into an integer array and print
only those words that begin with an 'A' or 'a'.
Ans. import java.util.*;
class Question48
{
static void main()
{
Scanner sc=new Scanner(System.in);
String a[]=new String[10];
int i;
System.out.println("Enter 10 words:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextLine();
}
System.out.println("Words that begins with character A or a");
for(i=0;i<a.length;i++)
{
if(a[i].charAt(0)=='A' || a[i].charAt(0)=='a')
System.out.println(a[i]);
}
}
}
49. Write a program to input 10 numbers into an integer array and store
only the even numbers into another array and display it.
Ans. import java.util.*;
class Question49
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int b[]=new int[10];
int i,c=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length;i++)
{
if(a[i]%2==0)
b[c++]=a[i];
}
System.out.println("Numbers that are stored in array b:");
for(i=0;i<c;i++)
{
System.out.print(b[i]+" ");
}
}
}
50. Write a program to input 10 numbers into an integer array and store
all prime numbers into another array and display it.
Ans. import java.util.*;
class Question50
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int b[]=new int[10];
int i,c=0,j,p=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length;i++)
{
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c==2)
b[p++]=a[i];
}
System.out.println("Numbers that are stored in array b:");
for(i=0;i<p;i++)
{
System.out.print(b[i]+" ");
}
}
}
51. Write a program to input 10 numbers into an integer array and store
only the unique numbers into another array and display it.
Ans. import java.util.*;
class Question51
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int b[]=new int[10];
int i,c=0,j,p=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length;i++)
{
c=0;
for(j=0;j<a.length;j++)
{
if(a[i]==a[j])
c++;
}
if(c==1)
b[p++]=a[i];
}
System.out.println("Numbers that are stored in array b:");
for(i=0;i<c;i++)
{
System.out.print(b[i]+" ");
}
}
}
52. Write a program to input 10 numbers into an integer array and store
each number only once into another array irrespective of the number of
times it is present in the array.
Ans. import java.util.*;
class Question52
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int b[]=new int[10];
int i,c=0,j,p=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length;i++)
{
c=0;
for(j=0;j<i;j++)
{
if(a[i]==a[j])
c=1;
}
if(c==0)
b[p++]=a[i];
}
System.out.println("Numbers that are stored in array b:");
for(i=0;i<p;i++)
{
System.out.print(b[i]+" ");
}
}
}
53. Write a program to input 10 numbers into an integer array and store
all even numbers into one array and all odd numbers into another array.
Display all the three arrays.
Ans. import java.util.*;
class Question53
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int b[]=new int[10];
int c[]=new int[10];
int i,p=0,q=0;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<a.length;i++)
{
if(a[i]%2==0)
b[p++]=a[i];
else
c[q++]=a[i];
}
System.out.println("Original Array:");
for(i=0;i<10;i++)
{
System.out.print(a[i]+" ");
}
System.out.println("\nArray where even numbers are stored:");
for(i=0;i<p;i++)
{
System.out.print(b[i]+" ");
}
System.out.println("\nArray where odd numbers are stored:");
for(i=0;i<q;i++)
{
System.out.print(c[i]+" ");
}
}
}
54. Write a program to input 10 numbers and store each one of them into
an integer array in such a way that the array is always maintained in
ascending order.
Ans. import java.util.*;
class Question54
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int i,n,j,f=0,k;
System.out.println("Enter 10 numbers:");
for(i=0;i<a.length;i++)
{
n=sc.nextInt();
f=0;
for(j=0;j<i;j++)
{
if(a[j]>n)
{
f=1;
break;
}
}
if(f==1)
{
for(k=i;k>j;k--)
{
a[k]=a[k-1];
}
a[j]=n;
}
else
a[i]=n;
}
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
55. Write a program to store the first 10 prime numbers into an integer
array and display it.
Ans. class Question55
{
static void main()
{
int a[]=new int[10];
int i=0,n=2,j,c;
while(i<10)
{
c=0;
for(j=1;j<=n;j++)
{
if(n%j==0)
c++;
}
if(c==2)
a[i++]=n;
n++;
}
System.out.println("First 10 prime numbers:");
for(i=0;i<10;i++)
{
System.out.print(a[i]+" ");
}
}
}
56. Write a program to generate the first 20 numbers of the Fibonacci
series using an array.
Ans. class Question56
{
static void main()
{
int a[]=new int[20];
int i;
a[0]=a[1]=1;
for(i=2;i<20;i++)
{
a[i]=a[i-1]+a[i-2];
}
System.out.println("First 20 numbers of the fibonacci series:");
for(i=0;i<20;i++)
{
System.out.print(a[i]+" ");
}
}
}
57. Create a method to accept an integer array as parameter and find the
mean, median and mode of it.
Ans. class Question57
{
static void main(int a[])
{
int i,j,t,s=0,c,l=0,n=0;
for(i=0;i<a.length;i++)
{
s+=a[i];
}
System.out.println("Mean="+(float)s/10);
for(i=0;i<a.length-1;i++)
{
for(j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
if(a.length%2!=0)
System.out.println("Median:"+a[a.length/2]);
else
System.out.println("Median:"+(float)(a[a.length/2]+a[a.length/2-1])/2);
for(i=0;i<a.length;i++)
{
c=0;
for(j=0;j<a.length;j++)
{
if(a[i]==a[j])
c++;
}
if(c>l)
{
l=c;
n=a[i];
}
}
System.out.println("Number having maximum frequency:"+n);
}
}
58. Create a method to accept an integer array as parameter and check
whether all numbers in it are two-digit numbers or not.
Ans. class Question58
{
static void is2digit(int a[])
{
int i;
boolean f=true;
for(i=0;i<a.length;i++)
{
if(!(a[i]>=10 && a[i]<=99 || a[i]>=-99 && a[i]<=-10))
f=false;
}
if(f)
System.out.println("All are 2-digit numbers");
else
System.out.println("All are not 2-digit numbers");
}
}
59. Create a method to accept an integer array as parameter and check
whether all numbers in it are even numbers or not.
Ans. class Question59
{
static void isEven(int a[])
{
int i;
boolean f=true;
for(i=0;i<a.length;i++)
{
if(a[i]%2!=0)
f=false;
}
if(f)
System.out.println("All are even numbers");
else
System.out.println("All are not even numbers");
}
}
60. Create a method to accept an integer array as parameter and check
whether all numbers in it are prime numbers or not.
Ans. class Question60
{
static void isPrime(int a[])
{
int i,j,c;
boolean f=true;
for(i=0;i<a.length;i++)
{
c=0;
for(j=1;j<=a[i];j++)
{
if(a[i]%j==0)
c++;
}
if(c!=2)
f=false;
}
if(f)
System.out.println("All are prime numbers");
else
System.out.println("All are not prime numbers");
}
}
61. Create a method to accept an integer array as parameter and check
whether all numbers are sorted in ascending order or not.
Ans. class Question61
{
static void isAscending(int a[])
{
int i;
boolean f=true;
for(i=0;i<a.length-1;i++)
{
if(a[i]>a[i+1])
f=false;
}
if(f)
System.out.println("All are in ascending order");
else
System.out.println("All are not in ascending order");
}
}
}
if(f==1)
System.out.println("Largest Even Number="+l);
else
System.out.println("No even number found="+l);
}
}
63. Create a method to accept a char array as parameter and check
whether all elements in it are unique or not.
Ans. class Question63
{
static void isUnique(char a[])
{
int i,j;
boolean f=true;
for(i=0;i<a.length-1;i++)
{
for(j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
f=false;
}
}
if(f)
System.out.println("All characters in it are unique");
else
System.out.println("All characters are not unique");
}
}
64. Create a method to accept an integer array as parameter and check
whether all elements in it come under the Fibonacci series or not.
Assume that the numbers may be in any order.
Ans. class Question64
{
static void isFibo(int a[])
{
int i,x,y,z;
boolean f=true;
for(i=0;i<a.length;i++)
{
x=1;y=0;z=0;
while(z<a[i])
{
z=x+y;
x=y;
y=z;
}
if(z!=a[i])
f=false;
}
if(f)
System.out.println("All are fibonacci numbers");
else
System.out.println("All are not fibonacci numbers");
}
}
65. Create a method to accept an integer array as parameter and store it
in another array by removing all duplicate elements.
Ans. class Question65
{
static void removeDuplicate(int a[])
{
int i,j,f,c=0,b[]=new int[a.length];
for(i=0;i<a.length;i++)
{
f=0;
for(j=0;j<i;j++)
{
if(a[i]==a[j])
f=1;
}
if(f==0)
b[c++]=a[i];
}
System.out.println("After removing duplicate elements:");
for(i=0;i<c;i++)
{
System.out.print(b[i]+" ");
}
}
}
66. Using overloading technique print the number having least
frequency in a double type array and the character having least
frequency in a char type array.
Ans. class Question66
{
static void leastFrequency(double a[])
{
int i,j,l=0,c=0;
double n=0;
for(i=0;i<a.length;i++)
{
c=0;
for(j=0;j<a.length;j++)
{
if(a[i]==a[j])
c++;
}
if(i==0)
{
l=c;
n=a[i];
}
if(c<l)
{
l=c;
n=a[i];
}
}
System.out.println("Number having least frequency="+n);
}
void display()
{
int i;
for(i=0;i<farr.length;i++)
{
System.out.println(farr[i]+"\t"+iarr[i]);
}
}
void roundOff()
{
int i;
for(i=0;i<farr.length;i++)
{
iarr[i]=Math.round(farr[i]);
}
}
void search(int r)
{
int i;
boolean f=false;
for(i=0;i<roll.length;i++)
{
if(roll[i]==r)
{
System.out.println(name[i]);
f=true;
break;
}
}
if(!f)
System.out.println("Not Found!");
}
}
70. Create a method which accepts a sentence as a parameter and print
the words according to ascending order of length.
Ans. class Question70
{
static void ascending(String s)
{
s=s.trim();
s=s+" ";
String w="",t="";
int i,j,c=0;
char x;
String a[]=new String[s.length()];
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
if(w!="")
a[c++]=w;
w="";
}
}
for(i=0;i<c-1;i++)
{
for(j=i+1;j<c;j++)
{
if(a[i].length()>a[j].length())
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(i=0;i<c;i++)
{
System.out.print(a[i]+" ");
}
}
}
71. Create a method which accepts a sentence as a parameter and print
the words in alphabetical order.
Ans. class Question71
{
static void ascending(String s)
{
s=s.trim();
s=s+" ";
String w="",t="";
int i,j,c=0;
char x;
String a[]=new String[s.length()];
for(i=0;i<s.length();i++)
{
x=s.charAt(i);
if(x!=' ')
w=w+x;
else
{
if(w!="")
a[c++]=w;
w="";
}
}
for(i=0;i<c-1;i++)
{
for(j=i+1;j<c;j++)
{
if(a[i].compareTo(a[j])>0)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(i=0;i<c;i++)
{
System.out.print(a[i]+" ");
}
}
}
72. Write a program to initialize an array of 5 names and initialize
another array with their respective telephone numbers. Search for a
name input by the User, in the list. If found, display "Search Successful
" and print the name along with the telephone number, otherwise
display "Search unsuccessful. Name not enlisted". [ICSE 2005]
Ans. import java.util.*;
class Question72
{
static void search()
{
Scanner sc=new Scanner(System.in);
String name[]={"Amit","Deb","Somesh","Trina","Ashish"};
long
phone[]={9832164084L,9476278923L,8936745126L,9866733497L,9832349667L};
String n;
boolean f=false;
int i;
System.out.println("Enter the name to search:");
n=sc.nextLine();
for(i=0;i<name.length;i++)
{
if(n.equalsIgnoreCase(name[i]))
{
System.out.println("Search Successful");
System.out.println(name[i]+"\t"+phone[i]);
f=true;
break;
}
}
if(!f)
System.out.println("Search unsuccessful. Name not enlisted");
}
}
73. The marks obtained by 50 students in a subject are tabulated as
follows: -
Name Marks
Write a program to input the names and the marks of the students in the
subject. Calculate and display:
i) The subject average marks (subject average marks = subject total / 50)
ii) The highest mark in the subject and the name of the student. (The
maximum marks in the subject are 100). [ICSE 2006]
Ans. import java.util.*;
class Question73
{
static void main()
{
String name[]=new String[50],n="";
int marks[]=new int[50];
int i,tot=0,max=0;
float avg;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the names and marks for 50 students:");
for(i=0;i<name.length;i++)
{
name[i]=sc.nextLine();
marks[i]=sc.nextInt();
sc.nextLine();//dummy input
}
for(i=0;i<name.length;i++)
{
tot=tot+ marks[i];
}
avg=(float)tot/50;
System.out.println("Subject Average Marks:"+avg);
for(i=0;i<name.length;i++)
{
if(i==0)
{
max=marks[i];
n=name[i];
}
if(marks[i]>max)
{
max=marks[i];
n=name[i];
}
}
System.out.println("Highest mark:"+max+" Name:"+n);
}
}
74. Define a class and store the given city names in a single dimensional
array. Sort these names in alphabetical order using the Bubble Sort
technique only.
INPUT: Delhi, Bangalore, Agra, Mumbai, Calcutta
OUTPUT: Agra, Bangalore, Calcutta, Delhi, Mumbai [ICSE 2008]
Ans. class Question74
{
static void main()
{
String a[]={"Delhi","Bangalore","Agra","Mumbai","Calcutta"};
int i,j;
String t="";
for(i=a.length-1;i>=0;i--)
{
for(j=0;j<i;j++)
{
if(a[j].compareTo(a[j+1])>0)
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println("Sorted Array:");
for(i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
75. 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 [ICSE 2010]
Ans. import java.util.*;
class Question75
{
static void main()
{
Scanner sc=new Scanner(System.in);
int a[]={5,7,9,11,15,20,30,45,89,97};
int n,l=0,u=a.length-1,m;
boolean f=false;
System.out.println("Enter the number to search:");
n=sc.nextInt();
while(l<=u)
{
m=(l+u)/2;
if(a[m]==n)
{
System.out.println("Element:"+a[m]);
System.out.println("Position:"+m);
f=true;
break;
}
else if(a[m]>n)
u=m-1;
else
l=m+1;
}
if(!f)
System.out.println("Search element not found");
}
}
76. The annual examination results of 50 students in a class are
tabulated as follows:
Roll no. Subject A Subject B Subject C
--------- ------------ ------------ ------------
Write a program to read the data, calculate and display the following: (a)
Average mark obtained by each student, (b) Print the roll number and
average marks of the students whose average mark is above 80, (c)
Print the roll number and average marks of the students whose average
mark is below 40. [ICSE 2009]
Ans. import java.util.*;
class Question76
{
static void main()
{
Scanner sc=new Scanner(System.in);
int rollno[]=new int[50];
int subA[]=new int[50];
int subB[]=new int[50];
int subC[]=new int[50];
float avg[]=new float[50];
int i;
System.out.println("Enter the roll no. and marks in 3 subjects for 50 students:");
for(i=0;i<rollno.length;i++)
{
rollno[i]=sc.nextInt();
subA[i]=sc.nextInt();
subB[i]=sc.nextInt();
subC[i]=sc.nextInt();
sc.nextLine();//dummy input
}
System.out.println("Average of each student:");
for(i=0;i<rollno.length;i++)
{
avg[i]=(float)(subA[i]+subB[i]+subC[i])/3;
System.out.println(rollno[i]+"\t\t"+avg[i]);
}
System.out.println("Students whose average is more than 80:");
for(i=0;i<rollno.length;i++)
{
if(avg[i]>80)
System.out.println(rollno[i]+"\t\t"+avg[i]);
}
System.out.println("Students whose average is less than 40:");
for(i=0;i<rollno.length;i++)
{
if(avg[i]<40)
System.out.println(rollno[i]+"\t\t"+avg[i]);
}
}
}
77. Create a method which accepts an integer as parameter and return
true if it comes under the Fibonacci series, otherwise return false. Now
use it another method which accepts a two-dimensional integer array as
parameter and check whether all elements in it comes under the
Fibonacci series or not.
Ans. class Question77
{
static boolean isFibo(int n)
{
int a=1,b=0,c=0;
while(c<n)
{
c=a+b;
a=b;
b=c;
}
if(c==n)
return true;
else
return false;
}
for(i=0;i<R.length;i++)
{
System.out.println(R[i]);
}
}
}
79. Write a program to enter 10 words into a String type array and print
only those words which end with 'A' or 'a'.
Ans. import java.util.*;
class Question79
{
static void main()
{
String s[]=new String[10];
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 10 words:");
for(i=0;i<10;i++)
{
s[i]=sc.nextLine();
}
System.out.println("Words that end with A or a:");
for(i=0;i<10;i++)
{
char x=s[i].charAt(s[i].length()-1);
if(x=='a' || x=='A')
System.out.println(s[i]);
}
}
}
80. Write a program to input 10 words into a String type array and print
only those words which begin and end with the same alphabet.
Ans. import java.util.*;
class Question80
{
static void main()
{
String s[]=new String[10];
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 10 words:");
for(i=0;i<10;i++)
{
s[i]=sc.nextLine();
}
System.out.println("Words that begins and ends with same alphabet:");
for(i=0;i<10;i++)
{
char x=s[i].charAt(s[i].length()-1);
char y=s[i].charAt(0);
if(x==y)
System.out.println(s[i]);
}
}
}
81. Write a program to input 10 words int a String type array and print the
longest word.
Ans. import java.util.*;
class Question81
{
static void main()
{
String s[]=new String[10],l="";
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 10 words:");
for(i=0;i<10;i++)
{
s[i]=sc.nextLine();
}
for(i=0;i<10;i++)
{
if(i==0)
l=s[i];
if(s[i].length()>l.length())
l=s[i];
}
System.out.println("Longest Word="+l);
}
}
Chapter 14: Console Input / Output
Practice Questions
A. Answer the following questions:
1. What is the function of the System class? What are the stream variables
associated with the Stream?
Ans. class System is a built-in class present in java.lang package, having a final modifier,
which does not allow it to be inherited and contains pre-defined methods and fields, which
provide facilities like standard input, output, etc.
The Stream variables associated with the Stream class are System.in and System.out.
2. Explain the concept of Streams in Java.
Ans. A stream in Java is an ordered sequence of bytes of undetermined length.
Streams are ordered and in sequence so that the Java virtual machine can understand
and work upon the stream. There are two categories of streams in Java, namely Byte
stream and Character stream.
3. Briefly explain the two types of streams available in Java.
Ans. Byte streams carry integers with values that range from 0 to 255. A diverse
assortment of data can be expressed in byte format, including numerical data, executable
programs, Internet communications and bytecode—the class files run by a Java virtual
machine.
Character streams are a specialized type of byte stream that handles only textual data.
They are distinguished from byte streams because Java's character set supports Unicode, a
standard that includes many more characters than could be expressed easily using bytes.
4. What is the function of the BufferedReader class? In this respect explain the
function of the InputStreamReader class. Also state the package under which the
above classes are associated.
Ans. The BufferedReader class read text from a character input stream, buffering
characters so as to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used.
The InputStreamReader class is a bridge from byte streams to character streams: It
reads bytes and decodes them into characters using a specified char set. The char set
that it uses may be specified by name or may be given explicitly, or the platform's
default character set may be accepted.
The package under which these classes are available is java.io.
5. Show, with the help of an example, how character and String can be entered
through console using BufferedReader class.
Ans. Program to input a character from the console:
import java.io.*;
class readCharDemo
{
static void test() throws IOException
{
char x;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a character:");
x=(char)br.read();
/*typecasting is necessary as the method read()
returns the unicode of the corresponding
character entered by the user.*/
System.out.println("You have input:"+x);
}
}
sc.useDelimiter("[,; ]");
void sum()
{
int c;
c=a+b;
System.out.println("Sum="+c);
}
}
3. Write a program to input two integers and interchange their values:
i) Using a third variable.
ii) Without using a third variable.
Ans. import java.util.*;
class Question3
{
static void swap_i()
{
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println("Enter 2 integers:");
a=sc.nextInt();
b=sc.nextInt();
System.out.println("Before swapping a="+a+" b="+b);
c=a;
a=b;
b=c;
System.out.println("After swapping a="+a+" b="+b);
}
}
}
9. Write a program to input an integer (of Binary Number System) and check
whether it is a valid binary number or not. A number is said to be a Binary Number
because all digits in it contains only 0 and 1, any other digit other than 0 and 1, it
is considered to be a valid Binary Number.
Ans. import java.util.*;
class Question9
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,d;
boolean f=true;
System.out.println("Enter a binary number:");
n=sc.nextInt();
while(n!=0)
{
d=n%10;
if(d!=1 && d!=0)
f=false;
n=n/10;
}
if(f)
System.out.println("Valid binary number");
else
System.out.println("Not a Valid binary number");
}
}
Chapter 15: Encapsulation
Practice Questions
-------------------------->Objective-Type Questions<--------------------------
A. State whether true or false:
1. A class is used to implement encapsulation. [True]
2. Instance variables are used to represent behaviour of an object. [False]
3. You need to prefix the keyword default before data members which
should have default/friendly access specifier. [False]
4. The access specifier private allows accessibility of a member only within the
class where the member is declared/defined, but not outside the class. [True]
5. Java source code should always have the .jav extension. [False]
B. Fill in the blanks:
1. The access specifier protected allows accessibility within the same package by both
classes and sub-classes but only by sub-classes in a different package.
2. In case there are multiple classes in a source code the class from where the program
should start execution should have the access specifier as public.
3. The private access specifier is not allowed for a class.
4. The extends keyword is used to perform inheritance in Java.
5. The keyword used to include a class in a package is package.
C. Choose the correct answer:
1. Which among the following allows global accessibility?
a) public b) private c) protected d) All of these
Ans. a) public
2. Which among the following allows accessibility only within the class where the
member is defined or declared?
a) public b) private c) protected d) All of these
Ans. b) private
3. In case, a source code has multiple classes; the class from which the program begins
should have the ________________ access specifier.
a) public b) private c) protected d) All of these
Ans. a) public
4. Which among the following is true, if a constructor is declared as private for a class?
a) Another class may declare the object of that class.
b) An object may be declared only within that class.
c) An object may be declared in a different package.
d) None of these.
Ans. b) An object may be declared only within that class.
5. Which among the following is not true for inheritance?
a) The class which is being inherited is called the super-class and the class that inherits
it is called the sub-class.
b) The extends keyword is used to perform inheritance.
c) private members of a super-class is also inherited in the sub-class.
d) The member functions of a super-class can manipulate the values of the data-
members of a sub-class.
Ans. d) The member-functions of a super-class can manipulate the values of the data-
members of a sub-class.
------------------------->Subjective-Type Questions<-------------------------
Answer the following questions:
1. What is a wrapper class? Give few examples of wrapper classes.
Ans. The wrapper class encapsulate or wrap the primitive data-types within a class to form
an object representation of it.
Lab Exercises
Write programs for the following:
1. Create a class name Sentence having the following:
private data members: s of String type.
public member functions:
i) Parameterized constructor to initialize it with a sentence.
ii) To accepts a word as parameter and return true if it is palindrome else return
false.
iii) To print the longest palindrome word in s.
Create another public class called Main and input a sentence and print the longest
word in the sentence using the above class.
Ans. //Question 1
import java.util.*;
class Sentence
{
private String s;
public Sentence(String t)
{
s=t;
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the pan no.:");
pan=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter your name:");
name=sc.nextLine();
System.out.println("Enter the annual taxable income:");
taxincome=sc.nextDouble();
}
void calc()
{
if(taxincome<=100000)
tax=0;
else if(taxincome<=150000)
tax=10/100.0*(taxincome-100000);
else if(taxincome<=250000)
tax=5000+20/100.0*(taxincome-150000);
else
tax=25000+30/100.0*(taxincome-250000);
}
void display()
{
System.out.println("Pan Number\t\tName\t\tTax-income\t\tTax");
System.out.println(pan+"\t\t"+name+"\t\t"+taxincome+"\t\t"+tax);
}
}
3. Define a class Salary described as below:-
private data Members: Name, Address, Phone, Subject Specialization, Monthly
Salary, Income Tax.
public Member methods:
i) To accept the details of a teacher including the monthly salary.
ii) To display the details of the teacher.
iii) To compute the annual Income Tax as 5% of the annual salary above
Rs.1,75,000/-.
Write a main method to create object of the class and call the above member
method.
Ans. //Question 3
import java.util.*;
class Salary
{
private long phone;
private String name,address,subjectSpecialization;
private double monthlySalary,incomeTax;
Special()
{
n=0;
}
Special(int x)
{
n=x;
}
int factorial(int p)
{
int i,f=1;
for(i=1;i<=p;i++)
f=f*i;
return f;
}
void isSpecial()
{
int t=n,d,s=0;
while(t!=0)
{
d=t%10;
s=s+factorial(d);
t=t/10;
}
if(s==n)
System.out.println("Special Number");
else
System.out.println("Not a Special Number");
}
}
void read()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string:");
st=sc.nextLine().toUpperCase();
len=st.length();
}
void takeout(int p)
{
st=st.substring(0,p)+st.substring(p+1);
}
void change()
{
int i;
char x;
String tst="";
for(i=0;i<len;i++)
{
x=st.charAt(i);
if(x=='Y')
x='A';
else if(x=='Z')
x='C';
else
x=(char)(x+2);
tst+=x;
}
st=tst;
}
}
6. Design a class named Myclass inside a package named myPackage, which will
contain two protected integer data members and a member function to add these
two data members and display them.
Now inherit this class into another class named SubClass outside myPackage.
Create member functions to initialize the two inherited data members and display
their sum. Also include a main( ) to show its implementation.
Ans. //Question 6
package myPackage;
//Question 6
import myPackage.Myclass;
class SubClass extends Myclass
{
void initialize(int x,int y)
{
a=x;
b=y;
void generate()
{
int i,j,f,r;
for(i=0;i<20;i++)
{
f=0;
r=1+(int)(Math.random()*20);
for(j=0;j<i;j++)
{
if(ar[j]==r)
f=1;
}
if(f==0)
ar[i]=r;
else
i--;
}
}
void display()
{
int i;
for(i=0;i<20;i++)
{
System.out.print(ar[i]+" ");
}
}
Student(int r,String n)
{
roll=r;
name=n;
}
void display()
{
System.out.println(name);
}
boolean isBinary(int n)
{
int d;
boolean f=true;
while(n!=0)
{
d=n%10;
if(d!=1 && d!=0)
f=false;
n=n/10;
}
return f;
}
void add()
{
int d1,d2,s=0,c=0,carry=0,x;
if(isBinary(a) && isBinary(b))
{
while(a!=0 || b!=0)
{
d1=a%10;
d2=b%10;
x=d1+d2+carry;
if(x>=2)
{
x=x-2;
carry=1;
}
s=s+x*(int)Math.pow(10,c++);
a=a/10;
b=b/10;
}
s=s+carry*(int)Math.pow(10,c);
System.out.println("Sum="+s);
}
else
System.out.println("Not a valid binary number");
}
ii)
private default
It allows accessibility only within the class It allows accessibility by all classes within
of which it is a member. the package.
14. What happens when a constructor is given a private access?
Ans. When a constructor is given a private access, its object can only be created within
the class of which it is a member.
15. Give an example to show how overloaded constructors can have different
access specifiers.
Ans. public class Example
{
int a,b;
Example()
{
a=b=0;
}
private Example(int x)
{
a=b=x;
}
void show()
{
System.out.println(a+"\t"+b);
}
}
16. What is inheritance? Which command is used for inheritance in Java?
Ans. Inheritance is the property by which all members of one class becomes members of
another class. The class which is being inherited is called the base or super class and the
class which inherits it is called the derived or sub-class.
The command used for inheritance is ‘extends’.
17. What are packages? Which package is imported by default in Java?
Ans. Package is a folder that contains compiled classes having both a name and a visibility
control mechanism for using its function in another class.
The package which is imported by default is java.lang.
18. State the conditions necessary to make a class part of a package.
Ans. To make a class part of a package, the first line of the source code should include
the code:
package <package-name>;
19. What is the function of import command in Java? Show with the help of an
example how a single class within a package is imported. Also state how all
classes may be imported in a program.
Ans. The import command in Java is used to include a class or group of classes that are
within the package for its functions and variables to be reused within a class.
To import a single class of a package, use the following syntax:
import <package-name>.<class-name>;
To import an all classes of a package, use the following syntax:
import <package-name>.*;
while(true)
{
a[i]=sc.nextInt();
i++;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Only 10 integers!");
}
}
}
5. Write a program to continue entering integers and find the sum of even and odd
integers separately unless a zero is entered. In that case throw any type of
exception and the program should end.
Ans. import java.util.*;
class Question5
{
static void main()
{
Scanner sc=new Scanner(System.in);
int n,se=0,so=0;
System.out.println("Enter the sum of even and odd integers:");
try
{
while(true)
{
n=sc.nextInt();
if (n==0)
throw new Exception("Only non-zero intgers!");
if(n%2==0)
se+=n;
else
so+=n;
}
}
catch(Exception e)
{
System.out.println("Error: "+e.getMessage());
}
finally
{
System.out.println("Sum of even numbers:"+se);
System.out.println("Sum of odd numbers:"+so);
}
}
}
6. Write a program to input a line of text and search for a given word, use all
relevant exceptions while using try-catch-finally block.
Ans. import java.util.*;
class Question6
{
static void main()
{
Scanner sc=new Scanner(System.in);
String txt,w;
int p=0,i=0,f=0;
try m,n
{
System.out.println("Enter the line of text:");
txt=sc.nextLine();
System.out.println("Enter the word:");
w=sc.next();
txt=txt.trim();
txt=" "+txt+" ";
w=w.trim();
w=" "+w+" ";
do
{
p=txt.indexOf(w,i);
if(p!=-1)
{
System.out.println("Found!");
f=1;
break;
}
i++;
}while(i<txt.length());
if(f==0)
System.out.println("Not Found!");
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
7. Create a class name Sentence having the following:
Data members: s of String type.
Member functions:
i) Parameterized constructor to initialize it with a sentence.
ii) To accept a word as parameter and return true if it is palindrome, else return
false.
iii) To print the longest palindrome word in s.
Ans. //Question 7
import java.util.*;
class Sentence
{
private String s;
public Sentence(String t)
{
s=t;
}
void calc()
{
if(taxincome<=100000)
tax=0;
else if(taxincome<=150000)
tax=10/100.0*(taxincome-100000);
else if(taxincome<=250000)
tax=5000+20/100.0*(taxincome-150000);
else
tax=25000+30/100.0*(taxincome-250000);
}
void display()
{
System.out.println("Pan Number\t\tName\t\tTax-income\t\tTax");
System.out.println(pan+"\t\t"+name+"\t\t"+taxincome+"\t\t"+tax);
}
}
9. Define a class salary described as below:
Data Members: Name, Address, Phone, Subject Specialization, Monthly Salary,
Income Tax.
Member methods:
i) To accept the details of a teacher including the monthly salary.
ii) To display the details of the teacher.
iii) To compute the annual Income Tax as 5% of the annual salary above
Rs.1,75,000/-.
Write a main method to create object of the class and call the above member
method.
Ans. //Question 9
import java.util.*;
class Salary
{
private long phone;
private String name,address,subjectSpecialization;
private double monthlySalary,incomeTax;
Special()
{
n=0;
}
Special(int x)
{
n=x;
}
return f;
}
void read()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string:");
st=sc.nextLine().toUpperCase();
len=st.length();
}
Ans. //Question 12
import myPackage.Myclass;
class SubClass extends Myclass
{
void initialize(int x,int y)
{
a=x;
b=y;
Student(int r,String n)
{
roll=r;
name=n;
}
void display()
{
System.out.println(name);
}
public static void main(String args[])throws
ArrayIndexOutOfBoundsException,NumberFormatException
{
Student ob[]=new Student[10];
int i,r,f=0;
String n;
Scanner sc=new Scanner(System.in);
for(i=0;i<10;i++)
{
System.out.println("Enter Roll No.:");
r=sc.nextInt();
sc.nextLine();//dummy input
System.out.println("Enter Name:");
n=sc.nextLine();
ob[i]=new Student(r,n);
}
Solutions