Computer Application Part 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 158

Solutions for APC Understanding Computer Applications With BlueJ

ICSE Class 10 Java Program

Chapter 1 - Unit 1

Introduction to Object Oriented Programming Concepts

Multiple Choice Questions

Question 1

In object oriented programming, the stress is given on:

1. procedure
2. methods
3. class
4. data

Answer

data

Reason — In Object Oriented Programming, the stress is put on the data values rather than functions.

Question 2

Which of the following principle does not allow to access directly from outside the class premises?

1. data hiding
2. encapsulation
3. abstraction
4. all of the above

Answer

all of the above

Reason — Data hiding, Encapsulation and Abstraction, all the three restrict direct access to data from outside a
class.

Question 3

The process of combining data and functions that enables them to be together as a single entity is called

1. inheritance
2. encapsulation
3. classification
4. attributes

Answer
Encapsulation

Reason — Wrapping of data and functions of an object as a unit that can be used together in a specific
operation is known as Encapsulation.

Question 4

The process by which a class acquires the properties from another class is called:

1. polymorphism
2. inheritance
3. abstraction
4. object

Answer

Inheritance

Reason — Inheritance is a property by virtue of which one class acquires some features from another class.

Question 5

In procedural programming, the stress is laid on:

1. class
2. function
3. data
4. object

Answer

Function

Reason — A programming language in which emphasis is given on the functions rather than data values is
known as Procedure Oriented Programming Language.

Question 6

Which of the following is a blue print that creates objects of similar types?

1. abstraction
2. encapsulation
3. class
4. function

Answer

class

Reason — Class is a blue print that creates objects of similar types.

Question 7

Which of the following is not an object oriented programming language?


1. C++
2. Simula
3. BASIC
4. Java

Answer

BASIC

Reason — BASIC is a procedure oriented programming language.

Question 8

The process of restricting the free flow of data from the outside world is known as:

1. encapsulation
2. inheritance
3. function
4. class

Answer

encapsulation

Reason — The process of restricting the free flow of data from the outside world is known as encapsulation.

Question 9

Which of the following is true for Polymorphism?

1. Uses same function for different operations


2. Uses same operation for different functions
3. It is not a principle of oop
4. It uses reusability feature.

Answer

Uses same function for different operations

Reason — Polymorphism is the process of using a function for carrying multiple operations.

Question 10

In procedure oriented programming, the stress is given on:

1. Data
2. Function
3. Object
4. Class

Answer

Function
Reason — In procedure oriented programming, the stress is given on function or procedure.

Fill in the blanks

Question 1

Object is the fundamental concept in object oriented programming language.

Question 2

Objects can communicate with each other through function in object oriented programming language.

Question 3

Using a function for multiple operations is called as polymorphism.

Question 4

Data Abstraction is an act of representing essential features without including background details.

Question 5

Feature of wrapping data and functions as a single unit is called encapsulation.

Question 6

Inheritance promotes the reusability feature, in object oriented programming.

Question 7

Data hiding confirms the security of data members from being manipulated from unauthorized access.

Question 8

In encapsulation, data can be public or private whereas, in data hiding, data must be private only.

Write short answers

Question 1

What is object oriented programming? Name two object oriented programming languages.

Answer

Object Oriented Programming is an approach in which stress is laid on data rather than functions. The data
values remain associated with the functions of a particular block of the program so as to encourage data
security.

Two object oriented programming languages are C++ and Java.

Question 2

Name four basic principles of object oriented programming.


Answer

Four basic principles of object oriented programming are:

1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism

Question 3

Why do we prefer object oriented approach in complex programming? Explain.

Answer

Object Oriented approach offers advantages like:

1. Data Values are secured.


2. Mishandling of data is protected.
3. Error detection and correction becomes easier.
4. Easier in coding complex programs.

For these reasons, Object Oriented approach is preferred for complex programming.

Question 4

What is meant by a base class and a derived class?

Answer

The class that is inherited is known as base class and the class that inherits from the base is known as derived
class.

Question 5

Mention two limitations of procedure oriented programming approach.

Answer

Two limitations of procedure oriented programming approach are:

1. No restriction on data values.


2. No reusability concept hence time management, testing and length of the program increases.

Question 6

What is meant by Encapsulation?

Answer

Wrapping of data and functions of an object as a unit that can be used together in a specific operation is called
Encapsulation.
Question 7

Define the following with an example each.

(a) Inheritance

(b) Polymorphism

Answer

(a) Inheritance is a property by virtue of which one class acquires some features from another class. It promotes
reusability.

As an example of inheritance, we can consider the case of vehicles. All vehicles have some common features
like they can move on the road and transport people and goods from one place to another. These vehicles differ
from each other in certain aspects like whether it transports passengers or goods, how many passengers it can
accommodate at a time, whether it is a two-wheeler or four-wheeler, etc. So, we have different types of vehicles
like Cars, Bikes, Scooters, Auto rickshaw, Buses, Trucks, etc. Using inheritance, we can make vehicles the base
class with the different types of vehicles being the derived class as shown below:

(b) Polymorphism is the process of using a function for carrying multiple operations. During this process, an
object may include a function for multiple operations.

As an example, if we ask different animals to speak, they respond in their own way. Dog will bark, duck will
quack, cat will say meow and so on. So, the same action of speaking is performed in different ways by different
animals. This is the concept of Polymorphism.

Question 8

In what way is Data Hiding related to Data Abstraction?

Answer

Data Hiding and Data Abstraction are complementary concepts. Data Abstraction focuses on the observable
behaviour of an object, whereas Data hiding or Data Encapsulation focuses upon the implementation that gives
rise to this behaviour. In other words, Data Abstraction cares about what something does but not how it does it.
Data Encapsulation cares about how something does what it does such that others don't have to worry about the
implementation details. Hence, we can say that Encapsulation is a way to implement Data Abstraction.

Question 9

Give an example to explain Data Abstraction.

Answer

Data abstraction is an act of representing the essential features without knowing the background details.

As an example, lets consider the electrical switchboard. Switchboard provides us a very simple way to switch
ON/OFF lights, fans and other electrical appliances. It hides all the details like the internal wiring of the house,
how the switch is turning the light ON/OFF, etc.
Question 10

What is meant by Data Hiding?

Answer

The insulation of data that does not allow it to be accessed directly outside the class premises, although it is
available in the same program is known as Data Hiding.

Question 11

Give two differences between Data Hiding and Encapsulation.

Answer

Two differences between Data Hiding and Encapsulation are as follows:

1. Data hiding focuses more on data security whereas, encapsulation focuses more on hiding the
complexity of the system.
2. Data hiding focuses on restricting the use of data whereas, encapsulation deals with wrapping of data
and functions.

Question 12

'Encapsulation reduces the complexity and makes the system easier'. Explain this statement with a real world
example.

Answer

Encapsulation means wrapping of data and methods into a single unit and restricting direct access to some of
the object's components.

Let us take the example of an ATM machine. When we want to withdraw money from an ATM machine, we
swipe our card, enter the pin and then enter the amount of money we want to withdraw. The ATM machine
processes our request and gives us the required money.

Here, money is treated as data and the various processes such as verification of the authenticity of the user, pin
and balance in the account etc., are the methods. The data and methods are encapsulated in the ATM (which is
treated as a class). Since the user doesn't have to understand the actual working of the ATM machine,
encapsulation reduces the complexity and makes the system (ATM machine) easier to use.

Question 13

Give two differences between Procedure Oriented languages and Object Oriented languages.

Answer

Two differences between Procedure Oriented languages and Object Oriented languages are as follows:
Procedure Oriented languages Object Oriented languages

Procedure Oriented languages lay emphasis on Object Oriented languages lay emphasis on data
functions and procedures rather than data. rather than functions.

Limited and difficult code reusability leading to Versatile and easy code reusability leading to
lengthy programs which are difficult to debug and simpler programs which are easier to debug and
maintain. maintain.

Question 14

Which of the Object Oriented programming principles explain the following illustrations? Justify.

(a) The variables and methods are put together in a Class.

(b) A man withdrawing money from ATM.


Answer

(a) Encapsulation is illustrated in the given picture. Wrapping of data and functions of an object as a unit (class)
that can be used together in a specific operation is known as Encapsulation. In the picture, the variables and
methods are being encapsulated in a class.

(b) The principle of Data abstraction is illustrated here as the man withdraws money from the ATM using the
withdraw option. He knows the essential features of the ATM machine such as withdrawing money, without
knowing the complex background details of how the ATM machine is operating to provide money to him.

Chapter 1 - Unit 2

Elementary Concept of Objects and Classes

Multiple Choice Questions

Question 1

Which of the following keywords is used to create an instance of a class?

1. new
2. public
3. class
4. main

Answer

new

Reason — New keyword is used to create an instance of a class.

Question 2

The ............... is called an instance of a class.

1. attribute
2. object
3. state
4. features

Answer

object

Reason — The data members declared within a class are known as instance variables. When an object of a
class is created, it includes instance variables described within the class. Hence, an object is called as an
instance of a class.

Question 3

The objects we see around us are called as:


1. Real world object
2. Virtual object
3. Imaginary object
4. None of the above

Answer

Real world object

Reason — The objects we see around us are called as Real world objects.

Question 4

Which of the following makes a function non-returnable?

1. public
2. static
3. void
4. new

Answer

void

Reason — The keyword 'void' makes a function non-returnable.

Question 5

Which of the following statements is valid for the objects?

1. They possess same characteristics and behaviour.


2. They possess same characteristics but different behaviour.
3. They possess different characteristics and different behaviour.
4. They possess different characteristics but common behaviour.

Answer

They possess different characteristics but common behaviour.

Reason — Objects are the entities which possess different characteristics and common behaviour described
within the class.

Fill in the blanks

Question 1

Creating object is the fundamental concept in object oriented programming language.

Question 2

A class is also considered as an object factory.


Question 3

A real world object deals with characteristics and behaviours.

Question 4

The object of a class differs on various characteristics.

Question 5

The characteristics of the real world objects are considered to be the data members of the software objects.

Question 6

An object of a class is created by using a keyword new.

Question 7

Class is a blueprint of the objects.

Question 8

new keyword is used for dynamic allocation of an object.

Answer the following questions

Question 1

How will you define a software object?

Answer

A software object replaces the characteristics and behaviours of a real world object with data members and
member methods, respectively.

Question 2

Define class and object with an example.

Answer

An object is an entity having a specific identity, specific characteristics and specific behavior.

A class is a blue print that represents a set of objects that share common characteristics and behaviour.

Take the example of a house. An architect will have the blueprints for a house. Those blueprints will be plans
that explain exactly what properties the house will have and how they are all laid out. However, it is just the
blueprint, we can't live in it. Builders will look at the blueprints and use those blueprints to make a physical
house. They can use the same blueprint to make as many houses as they want. Each house will have the same
layout and properties. Each house can accommodate its own families. So, in this example, the blueprint is the
class, the house is the object and the people living in the house are data stored in the object's properties.
Question 3

What does the following statement mean?


Employee staff = new Employee ( );
Answer

This statement creates a new object of class Employee. The newly created object is assigned to a variable
named staff which is of Employee type. The object can be accessed using staff variable.

Question 4

A class is also referred to as 'Object Factory'. Comment.

Answer

A class has the complete description of the data elements the object will contain, the methods the object can do,
the way these data elements and methods can be accessed. A class is used to create similar objects that possess
different characteristics and common behaviour. Hence, class is called an object factory.

Question 5

Why is a class known as composite data type?

Answer

When a user creates a class, it becomes a data type for his program. This data type includes different primitive
types such as int, float, char, etc. Thus, class is referred to as a user defined data type or Composite Data Type.

Question 6

A statement is given as:


'Study_Table' is an object of the class 'Furniture'. Write down Java statement for the same.

Answer
Furniture Study_Table = new Furniture();

Question 7

Class and Objects are inter-related. Explain.

Answer

A Class is used to create various Objects that have different characteristics and common behaviours. Each
object follows all the features defined within a class. That is why class is also referred to as a blue print or
prototype of an object. This way we can say that they are inter-related.

Question 8

Why is an Object called an 'Instance' of a class? Explain.

Answer

The data members declared within a class are also known as instance variables. When an object of a class is
created, it includes instance variable described within the class. This is the reason that an object is called an
instance of a class.
Question 9

Write a statement to create an object 'Keyboard' of the class 'Computer'.

Answer
Computer Keyboard = new Computer();

Question 10

Mention three characteristics and two methods for the following Classes:

(a) class Mobile Phone

(b) class Bike

(c) class Fruits

(d) class Pen

Answer

(a) class Mobile Phone

Characteristics Methods

colour makeCall()

model receiveCall()

IMEI Number

(b) class Bike

Characteristics Methods

colour startEngine()

model stopEngine()

Registration Number

(c) class Fruits

Characteristics Methods

name buy()
Characteristics Methods

quantity sell()

cost

(d) class Pen

Characteristics Methods

name write()

type refill()

Company

Question 11

Design a program in Java to calculate the discount given to a customer on purchasing LED Television. The
program also displays the amount paid by the customer after discount. The details are given as:
Class name : Television
Data members: int cost, int discount, int amount
Member functions:
Accept( ) : to input the cost of Television
Calculate( ) : to calculate the discount
Display( ) : to show the discount and the amount paid after discount

Answer

class Television {
int cost;
int discount;
int amount;

void Accept() {
/*
* Input the cost
* of Television
*/
}

void Calculate() {
/*
* Calculate the discount
*/
}
void Display() {
/*
* Show the discount and
* the amount paid
* after discount
*/
}
}

Chapter 1 - Unit 3

Values and Data Types

Multiple Choice Questions

Question 1

How many bytes a char data type occupies in the memory?

1. 2
2. 8
3. 4
4. 16

Answer

Reason — A char data type occupies 2 bytes in the memory.

Question 2

Which of the following is a non-primitive data type?

1. int
2. double
3. char
4. String

Answer

String

Reason — String is a non-primitive data type.

Question 3

Which of the following is non-numeric data type?


1. boolean
2. int
3. float
4. double

Answer

boolean

Reason — boolean data type can store only two values - true or false.

Question 4

Which of the following ASCII code range is applicable for lowercase letters?

1. 65 - 90
2. 90 - 115
3. 97 - 122
4. 95 - 110

Answer

97 - 122

Reason — 97 - 122 is the ASCII code range for lowercase letters.

Question 5

What is not an escape sequence?

1. \t
2. \\
3. \n
4. ||

Answer

||

Reason — || is the symbol for logical OR operator.

State True or False

Question 1

There are 128 set of different characters used in a Java program.


False

Explanation — Java uses Unicode which can represent much more than 128 characters

Question 2

The ASCII codes of upper case letters range from 97 to 122.


False
Explanation — ASCII codes of upper case letters range from 65 to 90.

Question 3

A variable gives the exact representation of data.


False

Explanation — A literal gives exact representation of data. As value of variable can change, so it cannot give
exact representation of data.

Question 4

The data types int, float, char are called non-primitive types.
False

Explanation — The data types int, float, char are called Primitive types.

Question 5

A String literal is assigned to a String variable.


True

Explanation — The data type of the variable that can hold a String literal should also be String.

Question 6

A character literal is always enclosed in double quotes.


False

Explanation — A character literal is enclosed in single quotes.

Question 7

String constant can be written by using a set of alphanumeric characters.


True

Explanation — A String literal or String constant is defined by enclosing a set of alphanumeric characters
within double quotes.

Question 8

An object is said to be a non-primitive data.


True

Explanation — Class is a non-primitive data type so Objects are non-primitive data.

Question 9

The data type int stores fractional values.


False

Explanation — float or double data type stores fractional values.


Question 10

Boolean type data is used to test a condition and results in either true or false.
True

Explanation — Boolean data type can be either true or false.

Write short answers

Question 1

What is meant by data type? Name two types of data type.

Answer

Data types are used to identify the type of data a memory location can hold and the associated operations of
handling it. Data Types are of two types:

1. Primitive Data Types


2. Reference or Composite Data Types

Question 2

Why is it necessary to define data type in Java programming?

Answer

Data types tells Java how much memory it should reserve for storing the data value. Data types also help in
preventing errors as the compiler can check and flag illegal operations at compile time itself.

Question 3

Define the following with an example:

(a) variable

(b) constant

(c) boolean data type

(d) coercion

(e) primitive data type

(f) non-primitive data type

Answer

(a) Variable — Variables are identifiers that are used to name a data that holds a value in the memory. The
value can change depending upon our requirements in the program. For Example,
int mathScore = 95;
(b) Constant — The keyword final before a variable declaration makes it a constant. Its value can't be changed
in the program.
Example:
final int DAYS_IN_A_WEEK = 7;
(c) Boolean Data Type — A boolean data type is used to store one of the two boolean values — true or false.
The size of boolean data type is 8 bits or 1 byte.
Example:
boolean bTest = false;
(d) Coercion — In a mixed mode expression, when the data type of the result gets converted into the higher
most data type available in the expression without any intervention of the user, is known as Implicit Type
conversion or Coercion.
Example:

int a = 42;
long b = 50000;
long c = a + b;
Here, a is int, b is long so the result of a + b automatically gets converted into long and assigned to variable c
which is of long type.

(e) Primitive Data Type — Primitive data types are the basic or fundamental data types used to declare a
variable. Examples of primitive data types in Java are byte, short, int, long, float, double, char and boolean.

(f) Non-Primitive Data Type — A non-primitive data type is one that is derived from primitive data types. A
number of primitive data types are used together to represent a non-primitive data type. Examples of non-
primitive data types in Java are Class and Array.

Question 4

What is a token? Name different types of tokens.

Answer

A token is defined as each individual component of Java program that carries some meaning and takes active
part in program execution. The different types of tokens in Java are:

1. Identifiers
2. Literals
3. Operators
4. Punctuators
5. Separators
6. Keywords

Question 5

Explain the term type casting.

Answer

Type casting is a data conversion in which the data type of the result in a mixed mode expression, gets
converted into a specific type as per user's choice. The choice of data type must be written within braces ( )
before the expression.
For example,

int a; float b; char c;


char d = (char) (a + b * c);

Question 6

Assign the following to a variable with suitable data type.

(a) m = 22 / 7
(b) p = 1.4142135 (value of square root of 2)

(c) k = 0.00004545

(d) n = 24.50

Answer

(a) double m = (22.0 / 7.0);

(b) double p = 1.4142135;

(c) double k = 0.00004545;

(d) float n = 24.50f;

Question 7

Distinguish between:

(a) Token and Identifier

(b) Character and Boolean literal

Answer

(a) Difference between Token and Identifier:

Token Identifier

A token is the smallest element of a program Identifiers are used to name things like classes,
that is meaningful to the compiler. objects, variables, arrays, functions an so on.

(b) Difference between Character and Boolean literal:

Character literal Boolean literal

A boolean literal can take only one of the two


Character literals are written by enclosing a character
boolean values represented by the words true or
within a pair of single quotes.
false.

Character literals can be assigned to variables of any


Boolean literals can only be assigned to variables
numeric data type — byte, short, int, long, float,
declared as boolean
double, char

Escape Sequences can be used to write character Only true and false values are allowed for
literals boolean literals

Question 8

Explain the term type conversion. How is implicit conversion different from explicit conversion?

Answer
The process of converting one predefined type into another is called type conversion.

In an implicit conversion, the result of a mixed mode expression is obtained in the higher most data type of the
variables without any intervention by the user. For example:

int a = 10;
float b = 25.5f, c;
c = a + b;
In case of explicit type conversion, the data gets converted to a type as specified by the programmer. For
example:

int a = 10;
double b = 25.5;
float c = (float)(a + b);

Question 9

Classify the following as primitive or non-primitive data types.

(a) char

(b) arrays

(c) int

(d) classes

Answer

(a) char — Primitive Data Type

(b) arrays — Non-Primitive Data Type

(c) int — Primitive Data Type

(d) classes — Non-Primitive Data Type

Question 10

In what way is static initialization of data type different from dynamic initialization?

Answer

In static initialization, the initial value of the variable is provided as a literal at the time of declaration. For
example:

int mathScore = 100;


double p = 1.4142135;
char ch = 'A';
In dynamic initialization, the initial value of the variable is the result of an expression or the return value of a
method call. Dynamic initialization happens at runtime. For example:

int a = 4;
int b = Math.sqrt(a);

double x = 3.14159, y = 1.4142135;


double z = x + y;
Question 11

Predict the return data type of 'r' and 'n' from the snippet:

int p; float m;
r = p+m;
n = m/3*(Math.pow(4,3));
System.out.println(r);
System.out.println(n);
Answer

Return type of r is float and n is double.

Question 12

Give reason whether the following assignments are correct or not.

(a) int m =155;

(b) float f = 0.002654132;

(c) String str = 'Computer';

(d) boolean p = false;

(e) String b = "true";

(f) char ch = "apps";

(g) String st= "Application";

(h) double n = 455.29044125;

Answer

(a) This assignment is correct as 155 is an integer literal and it is assigned to an int variable m.

(b) This assignment is incorrect as data type of 0.002654132 is double but it is assigned to a float variable. The
correct assignment will be double f = 0.002654132d;

(c) This assignment is incorrect as the String literal Computer is enclosed in single quotes. It should be in
double quotes. The correct assignment will be: String str = "Computer";
(d) This assignment is correct as false is a valid boolean literal and it is assigned to a boolean variable.

(e) This assignment is correct as "true" is a string literal not a boolean literal as it is enclosed in double quotes.
It is correctly assigned to a String variable.

(f) This assignment is incorrect as "apps" is a string literal not a character literal and it is assigned to a variable
ch of char data type.

(g) This assignment is correct as "Application" is a string literal and it is correctly assigned to a String variable.

(h) This assignment is correct as 455.29044125 is a literal of double data type and it is correctly assigned to a
double variable.
Chapter 1 - Unit 4

Operators in Java

Multiple Choice Questions

Question 1

Which of the following is the correct precedence of logical operators?

1. !, &&, ||
2. &&, !, ||
3. ||, !, &&
4. &&, ||, !

Answer

!, &&, ||

Reason — The correct precedence of logical operators is !, &&, ||.

Question 2

Choose the odd one out from the following:

1. >
2. ==
3. &&
4. <

Answer

&&

Reason — && is the logical AND whereas the other operators are relational.

Question 3

Given: String st = (a>= 90)? "Excellent": "Best";


Predict the output, when a = 90.

1. Best
2. Excellent: Best
3. Best: Excellent
4. Excellent

Answer

Excellent

Reason — Since condition (a>= 90) of ternary operator is true, st is assigned the value of expression 1 i.e.,
excellent.
Question 4

Choose the odd one out from the following:

1. Unary operator
2. Binary operator
3. Ternary operator
4. Bitwise operator

Answer

Bitwise operator

Reason — Unary operator, Binary operator and ternary operator are arithmetic operators.

Question 5

Given: x += x++ + ++x + --x


Find the value, when x=5.

1. 23
2. 21
3. 22
4. 24

Answer

23

Reason — The expression is calculated as follows:

x = x + (x++ + ++x + --x) (x = 5)


x = 5 + (5 + ++x + --x) (x = 6)
x = 5 + (5 + 7 + --x) (x = 7)
x = 5 + (5 + 7 + 6) (x = 6)
x = 5 + 18
x = 23
State True or False

Question 1

The precedence of operators in Java follows BODMAS.


False

Question 2

The output of a++ will be 1, if int a = -1.


False

Question 3

The relational operators always result in terms of 'True' or 'False'.


True
Question 4

Given: int m=5; m*=5 then the value stored in m results in 55.
False

Question 5

The statement (a>b)&&(a>c) uses a logical operator.


True

Question 6

If int a=27,b=4,c=0; then c = a % b; results in 3.


True

Question 7

The statement p += 5 means p = p*5.


False

Question 8

In the precedence of logical operators; NOT is followed by AND.


True

Write Java expressions

Question 1

ab+cd33ab+cd
Answer
Math.cbrt(a * b + c * d)

Question 2

p3+q4−12rp3+q4−21r
Answer
Math.pow(p, 3) + Math.pow(q, 4) - (1.0 / 2.0 * r)

Question 3

−b+b2−4ac2a2a−b+b2−4ac
Answer
(-b + Math.sqrt((b * b) - (4 * a * c))) / (2.0 * a)

Question 4

0.05−2y3(x−y)(x−y)0.05−2y3
Answer
(0.05 - (2 * Math.pow(y,3))) / (x - y)

Question 5

mn+(m+n)3mn+3(m+n)
Answer
Math.sqrt(m * n) + Math.cbrt(m + n)

Question 6

34(a+b)−25ab43(a+b)−52ab
Answer
(3.0 / 4.0 * (a + b)) - (2.0 / 5.0 * a * b)

Question 7

38(b2+c3)83(b2+c3)
Answer
3.0 / 8.0 * Math.sqrt((Math.pow(b,2) + Math.pow(c,3)))

Question 8

a3+b2−c33a+b2−3c
Answer
Math.cbrt(a) + Math.pow(b,2) - Math.cbrt(c)

Question 9

a+b2+c333a+b2+c3
Answer
Math.sqrt(a + Math.pow(b,2) + Math.pow(c,3)) / 3

Question 10

3x+x2(a+b)(a+b)3x+x2
Answer
Math.sqrt(3 * x + Math.pow(x,2)) / (a + b)

Question 11

z=x3+y3−yz3z=x3+y3−z3y
Answer
z = Math.pow(x,3) + Math.pow(y,3) - y / Math.pow(z,3)

Question 12

q=1a+b+3c2q=a+b1+c23
Answer
q = 1 / Math.sqrt(a + b) + 3 / Math.pow(c,2)
Predict the output

Question 1

int c = (3<4)? 3*4 : 3+4;

Output

12

Explanation

As 3 is less than 4 so condition of ternary operator is true. Variable c is assigned the value of expression 1
which is 3 * 4 = 12.

Question 2

int a = 14, b = 4; boolean x = (a > b) ? true : false;

Output

true

Explanation

As 14 is greater than 4 so condition of ternary operator is true. Variable x is assigned the value of expression 1
which is true.

Question 3

int x = 90;
char c = (x<=90)? 'Z' : 'I';

Output

Explanation

As value of x is 90 so condition of ternary operator is true. Variable c is assigned the value of expression 1
which is Z.
Question 4

int a = 18; int b = 12;


boolean t = (a > 20 && b < 15)? true : false;

Output

false

Explanation

The condition a > 20 is false as value of a is 18. So the logical AND operator — && returns false. Variable t is
assigned the value of expression 2 which is false.

Question 5

c = (val + 550 < 1700)? 200: 400;


if: (a) val = 1000 (b) val = 1500

Output

(a) 200
(b) 400

Explanation

When val = 1000, val + 550 = 1550. As 1550 is less than 1700 so condition of ternary operator is true. Variable
c is assigned the value of expression 1 which is 200.
When val = 1500, val + 550 = 2050. As 2050 is greater than 1700 so condition of ternary operator is false.
Variable c is assigned the value of expression 2 which is 400.

Answer the following questions

Question 1

What is an operator? What are the three main types of operators? Name them.

Answer

An operator is a symbol or sign used to specify an operation to be performed in Java programming.

The three main types of operators are Arithmetical, Logical and Relational.

Question 2

How is Java expression different from statement?

Answer

An expression is a set of variables, constants and operators i.e. an expression is a combination of operators and
operands. When an expression is assigned to a variable, the complete set is referred to as a statement.

Question 3

Explain the following with one example each.


(a) Arithmetic operator

Answer

Arithmetic operators are used to perform mathematical operations on its operands. Operands of arithmetic
operators must be of numeric type. A few arithmetic operators operate upon one operand. They are called
Unary Arithmetic operators. Other arithmetic operators operate upon two operands. They are called Binary
Arithmetic operators.
As an example consider the below statement:
int a = 10 + 20;
Here, the addition arithmetic operator, represented by the symbol + will add 10 and 20. So variable a will be 30.
(b) Relational operator

Answer

Relational operators are used to determine the relationship between the operands. Relational operators compare
their operands to check if the operands are equal to ( == ), not equal to ( != ), less than ( < ), less than equal to (
<= ), greater than ( > ), greater than equal to ( >= ) each other. The result of an operation involving relation
operators is a boolean value — true or false.
Example:
int a = 8;
int b = 10;
boolean c = a < b;
Here, as a is less than b so the result of a < b is true. Hence, boolean variable c becomes true.
(c) Logical operator

Answer

Logical operators operate on boolean expressions to combine the results of these boolean expression into a
single boolean value.
Example:
int a = 7;
int b = 10;
boolean c = a < b && a % 2 == 0;
Here, the result of first boolean expression a < b is true and the result of second boolean expression a %
2 is false. The logical AND operator ( && ) combines these true and false boolean values and gives a resultant
boolean value as false. So, boolean variable c becomes false.
(d) Ternary operator

Answer

Ternary operator operates on three operands. Its syntax is:


condition ? expression 1 : expression 2
Ternary operator evaluates the condition. If the condition is true then result of ternary operator is the value of
expression 1. Otherwise the result is the value of expression 2.
Example:
boolean isLeapYear = true;
int febDays = isLeapYear ? 29 : 28;
Here, the ternary operator checks if the value of boolean variable isLeapYear is true or false. As it is true,
expression 1, which in this example is the value 29, is the result of the ternary operator. So, int
variable febDays becomes 29.

Question 4

Distinguish between:

(a) Unary & Binary arithmetic operator


Answer

Unary Arithmetic Operator Binary Arithmetic Operator

It operates on a single operand It operates on two operands

Increment (++) and Decrement (--) operators are Multiplication (*) and Division (/) are examples
examples of Unary Arithmetic Operators of Binary Arithmetic Operators

(b) Postfix increment and Prefix increment

Answer

Postfix Increment Prefix Increment

It works on the principle of CHANGE-THEN-


It works on the principle of USE-THEN-CHANGE.
USE.

The increment operator (++) is written before


The increment operator (++) is written after the operand.
the operand.

Example: Example:
int a = 99; int a = 99;
int b = a++; int b = ++a;
After the execution of these two statements, a will have After the execution of these two statements,
the value of 100 and b will have the value of 99. both a and b will have the value of 100.
(c) Postfix decrement and Prefix decrement

Answer

Postfix Decrement Prefix Decrement

It works on the principle of CHANGE-THEN-


It works on the principle of USE-THEN-CHANGE.
USE.

The decrement operator (--) is written before


The decrement operator (--) is written after the operand.
the operand.

Example: Example:
int a = 100; int a = 100;
int b = a--; int b = --a;
After the execution of these two statements, a will have After the execution of these two statements,
the value of 99 and b will have the value of 100. both a and b will have the value of 99.
(d) (p != q) and !(p == q)

Answer
(p != q) !(p == q)

This expression uses the relational This expression first checks if values of p and q are equal using the
operator != (Not equal to) to relational operator == (equality). It then inverts the result of equality
determine if values of p and q are operator using the logical NOT (!) operator to determine if values of
different. p and q are different.

Question 5

What is the difference between

(a) / and % operator?

Answer

/ %

Division operator Modulus operator

Returns the quotient of division operation Returns the remainder of division operation

Example: int a = 5 / 2; Here a will get the value of Example: int b = 5 % 2; Here b will get the value of
2 which is the quotient of this division operation 1 which is the remainder of this division operation

(b) = and == ?

Answer

= ==

It is the assignment operator used for It is the equality operator used to check if a variable is
assigning a value to a variable. equal to another variable or literal.

Example: Example:
int a = 10; if (a == 10)
This statement assigns 10 to variable a. This statement checks if variable a is equal to 10 or not.

Question 6(a)

What will be the output of the following code?

int k=5,j=9;
k += k++ - ++j + k;
System.out.println("k="+k);
System.out.println("j="+j);

Output

k=6
j=10

Explanation

k+= k++ - ++j + k


⇒ k = k + (k++ - ++j + k)
⇒ k = 5 + (5 - 10 + 6)
⇒k=5+1
⇒k=6

Question 6(b)

If int y =10 then find int z = (++y*(y++ + 5));

Output

z = 176

Explanation

z = (++y * (y++ + 5))


⇒ z = (11 * (11 + 5))
⇒ z = (11 * 16)
⇒ z = 176

Question 6(c)

Give the output of the following expression:


a += a++ + ++a + --a + a--; when a = 7;

Output

a = 39

Explanation

a+= a++ + ++a + --a + a--


⇒ a = a + (a++ + ++a + --a + a--)
⇒ a = 7 + (7 + 9 + 8 + 8)
⇒ a = 7 + 32
⇒ a = 39

Question 6(d)

What is the value of y after the execution?


y += ++y + y-- + --y; when int y=8

Output

y = 33

Explanation

y+= ++y + y-- + --y


⇒ y = y + (++y + y-- + --y)
⇒ y = 8 + (9 + 9 + 7)
⇒ y = 8 + 25
⇒ y = 33

Question 7

Rewrite the following program segment using if-else statements instead of the ternary operator.

(a) String grade = (marks>=90)?"A": (marks>=80)? "B": "C";

Answer

String grade;
if (marks >= 90)
grade = "A";
else if (marks >= 80)
grade = "B";
else
grade = "C";
(b) commission = (sale > 5000) ? sale*10/100 : 0;

Answer

if (sale > 5000)


commission = sale * 10 / 100;
else
commission = 0;
(c) net = (salary > 10000) ? salary - (8.33/100)*salary : salary - (5/100)*salary

Answer

if (salary > 10000)


net = salary - (8.33/100) * salary;
else
net = salary - (5/100) * salary;
(d) s = (a + b < c || a + c <= b || b + c <= a) ? "Triangle is not possible": "Triangle is possible";

Answer

if (a + b < c || a + c <= b || b + c <= a)


s = "Triangle is not possible";
else
s = "Triangle is possible";
(e) c = (x >= 'A' && x <= 'Z') ? "Upper Case Letter" : "Lower Case Letter";

Answer

if (x >= 'A' && x <= 'Z')


c = "Upper Case Letter";
else
c = "Lower Case Letter";

Question 8

Rewrite the following using ternary operator.

(a)
if (x % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
Answer

System.out.println(x % 2 == 0 ? "Even" : "Odd");


(b)

if (bill > 10000)


discount=bill*10.0/100;
else
discount=bill*5.0/100;
Answer

discount = bill > 10000 ? bill*10.0/100 : bill*5.0/100;


(c)

if(income < 10000)


tax = 0;
else
tax = 12;
Answer

tax = income < 10000 ? 0 : 12;


(d)

if(a > b)
{
if (a > c)
g = a;
else
g = c;
}
else if (b > c)
g = b;
else
g = c;
Answer

g = a > b ? a > c ? a : c : b > c ? b : c;


(e)

if (p >= 4750)
k = p * 5 / 100;
else
k = p * 10 / 100;
Answer

k = (p >= 4750) ? p * 5 / 100 : p * 10 / 100;

Chapter 1 - Unit 5a

Introduction to Java
Multiple Choice Questions

Question 1

A Java program developed and executed by the users without using web browser is known as:

1. application
2. applet
3. object
4. none

Answer

application

Reason — Java application is a Java program that is developed to run on a computer without any help of a web
browser.

Question 2

Who developed Java?

1. James Gosling
2. Robert James
3. Bjarne Stroustrup
4. None

Answer

James Gosling

Reason — James Gosling developed Java.

Question 3

Java Virtual Machine (JVM) is an:

1. interpreter
2. compiler
3. machine code
4. byte code

Answer

interpreter

Reason — Java Virtual Machine (JVM) is a Java interpreter.

Question 4

Java is a case sensitive language. Which is the most appropriate statement with respect to this context?

1. Upper and lower case letters are distinguished.


2. Upper and lower case letters are ignored.
3. Only lower case letters are distinguished.
4. None.

Answer

Upper and lower case letters are distinguished.

Reason — Java is case sensitive, i.e., it can distinguish between uppercase and lowercase letters.

Question 5

Which of the following package is needed to find the square root of a number?

1. java.text
2. java.math
3. java.lang
4. None

Answer

java.lang

Reason — Math class inside java.lang package contains mathematical functions. The official documentation is
provided here. It should not be confused with java.math package which contains BigDecimal, BigInteger and
MathContext classes.

Question 6

Which of the following is not a Java reserved word?

1. private
2. public
3. break
4. total

Answer

total

Reason — total is not a Java reserved word.

Question 7

The most suitable statement for BlueJ is:

1. It is a window based platform.


2. It is a DOS based platform.
3. It is a window based and DOS based platform.
4. None.

Answer

It is a window based and DOS based platform.


Reason — BlueJ is a window based and DOS based platform.

Fill in the blanks

Question 1

The initial name of Java was Oak.

Question 2

Compiler converts source code to byte code.

Question 3

JVM is used to convert Byte Code into machine code.

Question 4

Java is platform independent language.

Question 5

Windows based Java platform is known as BlueJ.

Question 6

Reserved words are also called keywords.

Question 7

java.lang package is used for mathematical functions in Java.

Clarification: Math class inside java.lang package contains mathematical functions. The official
documentation is provided here. It should not be confused with java.math package which contains
BigDecimal, BigInteger and MathContext classes.

Predict the output of the following snippets

Question 1

System.out.println("My name is ");


System.out.print("Kunal Kishore");
System.out.println("I am a student of Class X");

Output

My name is
Kunal KishoreI am a student of Class X

Question 2

System.out.println("This is my first Java program");


System.out.print("Display the message:");
System.out.print("Have fun!!!");

Output

This is my first Java program


Display the message:Have fun!!!

Question 3

System.out.println("India got independence");


System.out.println("on");
System.out.println("15th August,1947");

Output

India got independence


on
15th August,1947

Question 4

System.out.print("The factorial of 5 is");


System.out.println("120");

Output

The factorial of 5 is120


Write short answers

Question 1

Name a Java package which is imported by default.

Answer

java.lang is imported by default in Java.

Question 2

Explain the significance of the following Java library packages.

(a) java.awt

(b) java.io

(c) java.net

Answer

(a) java.awt — java.awt package contains classes for supporting abstract window tool kit and managing
Graphical User Interface (GUI) components.

(b) java.io — It contains the classes that handle fundamental input and output operations in Java.

(c) java.net — It contains classes for supporting network operations in Java.


Question 3(a)

Java interpreter is called Java Virtual machine. Explain.

Answer

Java interpreter enables a computer to execute a Java program as well as a program written in other language
compiled into Java byte code. Hence, java interpreter is called Java Virtual machine.

Question 3(b)

Name two ways of writing Java programs.

Answer

Two ways of writing Java programs are:

1. Java Application
2. Java Applet

Question 4

Define the terms:

(a) Source code

(b) Machine code

(c) Byte code

Answer

(a) Source code — A set of statements written in a High-Level programming language like Java, C++, Python,
etc. is called as Source Code.

(b) Machine code — Machine code is a low-level programming language. Instructions in machine code are
written as a sequence of 0s and 1s. It is directly understood and executed by the processor.

(c) Byte code — Java compiler converts Java source code into an intermediate binary code called Byte code.
Byte code can't be executed directly on the processor. It needs to be converted into Machine Code first.

Question 5

What is BlueJ? What are the features of BlueJ?

Answer

BlueJ is an integrated development environment for Java. It was created for teaching Object Oriented
programming to computer science students. Features of BlueJ include a simple beginner friendly graphical user
interface to develop Java programs. It allows creating objects of the class dynamically, invoking their methods
and also supplying data to the method arguments if present.

Question 6

Write down the syntax of output statement in Java with an example.

Answer
We commonly use two output statements in Java. Their syntax is as follows:

1. System.out.println(<output value>);
This statement displays the output of the program on the screen in different lines. The letters 'ln' in the
statement act as a line feed which directs the cursor to move to the next line.
2. System.out.print(<output value>);
This statement is used to display the value enclosed within its braces. It leaves the cursor in the same
line on the screen.

As an example, the below statements will generate the following output:

System.out.println("JVM stands for");


System.out.print("Java ");
System.out.print("Virtual ");
System.out.print("Machine");

Output

JVM stands for


Java Virtual Machine

Question 7

What is meant by Java reserved words? Name five Java reserved words which are commonly used in Java
programming.

Answer

There are some words that carry special meaning to the system compiler. These words can't be used as variable
names in the program. Such words are called Keywords or reserved words.

Five commonly used Java reserved words are:

1. public
2. class
3. int
4. double
5. char

Question 8

Differentiate between the output statements System.out.println() and System.out.print().

Answer

System.out.println() System.out.print()

It prints data to the console and places the It prints data to the console but the cursor remains at the
cursor in the next line. end of the data in the same line.

Next printing takes place from next line. Next printing takes place from the same line.
Question 9

A Java program uses a Compiler as well as an Interpreter. Explain.

Answer

Java compiler compiles Java source code to Byte code. Byte code cannot run on the processor directly as
processor only understands machine code. Java Virtual Machine (JVM) takes this byte code as input and
converts it into machine code line by line. So, JVM acts as an interpreter for converting byte code to machine
code. In this way, a Java program uses both a compiler as well as an interpreter to get executed on the
processor.

Question 10

Write a package that is used for input/output operation in Java

Answer

java.io package is used for input/output operation in Java.

Chapter 1 - Unit 5b

Input in Java

Multiple Choice Questions

Question 1

Which of the following is the right way to use a comment in Java program?

1. /* comment */
2. /* comment
3. // comment //
4. */ comment */

Answer

/* comment */

Reason — /* comment */ is used to write multi line comments.

Question 2

Given: int p=55/0;


Name the type of error in the given statement:

1. Syntax
2. Logical
3. Runtime
4. Executional
Answer

Runtime

Reason — Division by 0 will result in an infinite value, which is a runtime error.

Question 3

The ............... method will accept a character using stream class.

1. in.read( )
2. (char)(in.read( ))
3. in.readline( )
4. character.read( )

Answer

(char)(in.read( ))

Reason — (char)(in.read( )) method will accept a character using stream class.

Question 4

Which of the following method will accept a string by using scanner object?

1. next( )
2. next.read( )
3. next.String( )
4. next.char( )

Answer

next( )

Reason — next( ) method will accept a string by using scanner object.

Question 5

Which of the following is a method of Java Scanner class?

1. nextline( )
2. nextLine( )
3. Nextline( )
4. NextLine( )

Answer

nextLine( )

Reason — nextLine( ) is a method of Java Scanner class.


Fill in the blanks

Question 1

The package needed to import StreamReader class is java.io.

Question 2

nextInt() function accepts an integer by using scanner object.

Question 3

The package needed to import Scanner class is java.util.

Question 4

The keyword import is used to include a package in a program.

Question 5

Assigning a value of 24.3 to a variable that is defined as int type is syntax error.

Question 6

input statement is used to accept value at run time.

Question 7

Scanner ob = new Scanner(System.in).

Question 8

The command line argument accepts the data value as an array of Strings.

Explain the following functions

Question 1

Integer.parseInt(in.readLine());

Answer

This statement accepts an integer from the user using Stream class and parses it into int data type using
Integer.parseInt() method.

Question 2

(char)(in.read());

Answer

This statement reads a character using Stream class and casts it explicitly into char data type.
Question 3

next();

Answer

next() method accepts a string from the user as a word using Scanner class.

Question 4

public static void main(int b)

Answer

The given function accepts an integer value from the user at the time of execution of the program. The value for
variable b must be provided as arguments to the main() function.

Question 5

nextLine();

Answer

nextLine() method accepts a string from the user as a line of text using Scanner class.

Answer the following

Question 1

What are the different ways to give input in a Java Program?

Answer

Java provides the following ways to give input in a program:

1. Using Function Argument


2. Using InputStreamReader class
3. Using Scanner class
4. Using Command Line Arguments

Question 2

What is a package? Give an example.

Answer

In Java, a package is used to group related classes. Packages are of 2 types:

1. Built-In packages — These are provided by Java API


2. User-Defined packages — These are created by the programmers to efficiently structure their code.

For example, java.util, java.lang are built-in packages.


Question 3

What is the use of the keyword 'import' in Java programming?

Answer

'import' keyword is used to import built-in and user-defined packages into our Java programs.

Question 4

What is a Runtime error? Explain with an example.

Answer

Errors that occur during the execution of the program primarily due to the state of the program which can only
be resolved at runtime are called Runtime errors.
Consider the below example:

import java.util.Scanner;
class RunTimeError
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = in.nextInt();
int result = 100 / n;
System.out.println("Result = " + result);
}
}
This program will work fine for all non-zero values of n entered by the user. When the user enters zero, a run-
time error will occur as the program is trying to perform an illegal mathematical operation of division by 0.
When we are compiling the program, we cannot say if division by 0 error will occur or not. It entirely depends
on the state of the program at run-time.

Question 5

What are the different types of errors that take place during the execution of a program? Name them.

Answer

Logical errors and Run-Time errors occur during the execution of the program.

Question 6

Give two differences between Syntax error and Logical error.

Answer

Syntax error Logical error

Syntax errors occur when we violate the rules of writing Logical errors occur due to our mistakes in
the statements of the programming language. programming logic.
Syntax error Logical error

Program compiles and executes but doesn't


Program fails to compile and execute.
give the desired output.

Logical errors need to be found and corrected


Syntax errors are caught by the compiler.
by people working on the program.

Solutions to Unsolved Java Programs

Question 1

In an election, there are two candidates X and Y. On the election day, 80% of the voters go for polling, out of
which 60% vote for X. Write a program to take the number of voters as input and calculate:

1. number of votes received by X


2. number of votes received by Y

import java.util.Scanner;

public class KboatPolling


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the number of voters: ");


long totalVoters = in.nextLong();

long votedVoters = Math.round(0.8 * totalVoters);


long xVotes = Math.round(0.6 * votedVoters);
long yVotes = votedVoters - xVotes;

System.out.println("Total Votes: " + votedVoters);


System.out.println("Votes of X: " + xVotes);
System.out.println("Votes of Y: " + yVotes);
}
}
Output

Question 2

A shopkeeper offers 10% discount on the printed price of a mobile phone. However, a customer has to pay 9%
GST on the remaining amount. Write a program in Java to calculate the amount to be paid by the customer
taking printed price as an input.

import java.util.Scanner;

public class KboatInvoice


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the MRP: ");


double mrp = in.nextDouble();

double priceAfterDiscount = mrp - (0.1 * mrp);


double priceWithGST = priceAfterDiscount + (priceAfterDiscount * 0.09);

System.out.println("Price after 10% discount and 9% GST: " +


priceWithGST);
}
}
Output

Question 3

A man spends (1/2) of his salary on food, (1/15) on rent, (1/10) on miscellaneous activities. Rest of the salary is
his saving. Write a program to calculate and display the following:

1. money spent on food


2. money spent on rent
3. money spent on miscellaneous activities
4. money saved

Take the salary as an input.

import java.util.Scanner;

public class KboatSalary


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the Salary: ");


float salary = in.nextFloat();

float foodSpend = salary / 2;


float rentSpend = salary / 15;
float miscSpend = salary / 10;
float savings = salary - (foodSpend + rentSpend + miscSpend);

System.out.println("Money spent on food: " + foodSpend);


System.out.println("Money spent on rent: " + rentSpend);
System.out.println("Money spent on miscellaneous: " + miscSpend);
System.out.println("Money saved: " + savings);
}
}
Output

Question 4

Write a program to input time in seconds. Display the time after converting them into hours, minutes and
seconds.
Sample Input: Time in seconds: 5420
Sample Output: 1 Hour 30 Minutes 20 Seconds

import java.util.Scanner;

public class KboatTime


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Time in seconds: ");


int inputTime = in.nextInt();

int hrs = inputTime / 3600;


int mins = (inputTime % 3600) / 60;
int secs = (inputTime % 3600) % 60;

System.out.println(hrs
+ " Hours "
+ mins
+ " Minutes "
+ secs
+ " Seconds");
}
}
Output

Question 5

The driver took a drive to a town 240 km at a speed of 60 km/h. Later in the evening, he drove back at 20 km/h
less than the usual speed. Write a program to calculate:

1. the total time taken by the driver


2. the average speed during the whole journey

[Hint: average speed = total distance / total time]

public class KboatJourney


{
public static void main(String args[]) {

int distance = 240;


float speed = 60.0f;
float returnSpeed = speed - 20;

float time2Reach = distance / speed;


float time2Return = distance / returnSpeed;
float totalTime = time2Reach + time2Return;

float avgSpeed = (distance * 2) / totalTime;

System.out.println("Total time: " + totalTime);


System.out.println("Average speed: " + avgSpeed);
}
}
Output

Question 6

Write a program to input two unequal numbers. Display the numbers after swapping their values in the
variables without using a third variable.
Sample Input: a = 76, b = 65
Sample Output: a = 65, b = 76

import java.util.Scanner;

public class KboatNumberSwap


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println("Please provide two unequal numbers");

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


int firstNum = in.nextInt();

System.out.print("Enter the second number: ");


int secondNum = in.nextInt();

if (firstNum == secondNum) {
System.out.println("Invalid Input. Numbers are equal.");
return;
}

firstNum = firstNum + secondNum;


secondNum = firstNum - secondNum;
firstNum = firstNum - secondNum;

System.out.println("First Number: " + firstNum);


System.out.println("Second Number: " + secondNum);
}
}

Output

Question 7

A certain amount of money is invested for 3 years at the rate of 6%, 8% and 10% per annum compounded
annually. Write a program to calculate:

1. the amount after 3 years.


2. the compound interest after 3 years.

Accept certain amount of money (Principal) as an input.


Hint: A = P * (1 + (R1 / 100))T * (1 + (R2 / 100))T * (1 + (R3 / 100))T and CI = A - P

import java.util.Scanner;

public class KboatCompoundInterest


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the principal: ");


double principal = in.nextDouble();
System.out.println(principal);

float r1 = 6.0f, r2 = 8.0f, r3 = 10.0f;

double amount = principal * (1 + (r1 / 100)) * (1 + (r2 / 100)) * (1 +


(r3 / 100));
double ci = amount - principal;

System.out.println("Amount after 3 years: " + amount);


System.out.println("Compound Interest: " + ci);
}
}

Output

Question 8

The co-ordinates of two points A and B on a straight line are given as (x1,y1) and (x2,y2). Write a program to
calculate the slope (m) of the line by using formula:
Slope = (y2 - y1) / (x2 - x1)
Take the co-ordinates (x1,y1) and (x2,y2) as input.

import java.util.Scanner;

public class KboatLineSlope


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter x coordinate of point A: ");


int x1 = in.nextInt();

System.out.print("Enter y coordinate of point A: ");


int y1 = in.nextInt();

System.out.print("Enter x coordinate of point B: ");


int x2 = in.nextInt();

System.out.print("Enter y coordinate of point B: ");


int y2 = in.nextInt();

float lineSlope = (y2 - y1) / (float)(x2 - x1);

System.out.println("Slope of line: " + lineSlope);


}
}

Output

Question 9

A dealer allows his customers a discount of 25% and still gains 25%. Write a program to input the cost of an
article and display its selling price and marked price.

Hint: SP = ((100 + p%) / 100) * CP and MP = (100 / (100 - d%)) * SP

import java.util.*;

public class KboatCalculatePrice


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);

System.out.print("Enter cost price of article:");


double cp = in.nextDouble();

int disc = 25, profit = 25;


double sp = 0.0, mp = 0.0;

sp = ((100 + profit) / 100.0) * cp;


System.out.println("Selling price of article = Rs. " + sp);

mp = (100.0 / (100 - disc)) * sp;


System.out.println("Marked price of article = Rs. " + mp);
}
}
Output

Chapter 1 - Unit 6

Mathematical Library Methods

Multiple Choice Questions

Question 1

Given: double a = -8.35;


double p = Math.abs(Math.floor(a));
What will be the final value stored in the variable p?

1. 9.0
2. 8.0
3. 7.0
4. 8.5

Answer

9.0

Reason — Math.floor() method returns the largest double value that is less than or equal to the argument and is
equal to a mathematical integer. As -9.0 is the largest mathematical integer less than -8.35 so it is returned in
this case. Math.abs() returns the absolute value of its argument so the final output is 9.0. The expression is
solved as follows:

p = Math.abs(Math.floor(a));
⇒ p = Math.abs(Math.floor(-8.35));
⇒ p = Math.abs(-9.0);
⇒ p = 9.0

Question 2

Given: double m = Math.max(Math.ceil(14.55),15.5);


What will be the final value stored in the variable m?

1. 15.0
2. 14.0
3. 15.5
4. 14.5

Answer

15.5

Reason — ceil() returns the whole number greater than or equal to the number and max() returns the greater
number between its arguments. So, the expression is solved as follows:

m = Math.max(Math.ceil(14.55),15.5);
⇒ m = Math.max(15.0,15.5);
⇒ m = 15.5

Question 3

Given: d = Math.min(-15.5, -19.5);


What data type will you refer for the variable d?

1. int
2. float
3. double
4. None

Answer

double

Reason — The return data type of Math.min() function depends on its arguments. Here, the arguments are of
double data type hence, Math.min() will return a double value. So, data type of variable d will be double.

Question 4

Given: double k = Math.rint(-9.4) + Math.sqrt(9.0);


What will be the final value stored in the variable k?

1. -5.0
2. -6.0
3. -6.4
4. -5.4

Answer

-6.0
Reason — Math.rint(-9.4) will give -9.0 as it is nearest integer to -9.4. Math.sqrt(9.0) will give 3.0. So, the
expression is solved as follows:

k = Math.rint(-9.4) + Math.sqrt(9.0);
⇒ k = -9.0 + 3.0
⇒ k = -6.0

Question 5

Given double b = Math.ceil(3.4) + Math.pow(2,3);


What will be the final value stored in the variable b?

1. 12.0
2. 11.0
3. 11.4
4. 11.5

Answer

12.0

Reason — Math.ceil() returns the smallest whole number greater than or equal to its argument. Math.pow(a,b)
returns the value ab. So, the final value of b will be:

b = Math.ceil(3.4) + Math.pow(2,3);
⇒ b = 4.0 + 8.0
⇒ b = 12.0

State True or False

Question 1

The return data type of Math.log() is double.


True

Question 2

Java.Math class is used for different mathematical functions.


True

Question 3

The output of Math.abs(-99.99) is 100.00.


False

Question 4

Math.sqrt(-225) can't be defined.


True

Question 5

The output of Math.cbrt(-3) will be -27.


False
Question 6

Math.round() returns the value in float data type.


False

Write down the syntax for the following functions

Question 1

To find the natural log of q.

Answer

Math.log(q)

Question 2

To find the cube root of a number m.

Answer

Math.cbrt(m)

Question 3

To find the round-off of a number k.

Answer

Math.round(k)

Question 4

To find the absolute value of a number y.

Answer

Math.abs(y)

Question 5

To find the exponent of a number p.

Answer

Math.exp(p)

Explain the following functions

Question 1

Math.random()

Answer

It returns a positive double value, greater than or equal to 0.0 and less than 1.0.
Question 2

Math.pow()

Answer

It returns the value of the first argument raised to the power of the second argument. Data type of the two
arguments and the return type of this method is double.

Question 3

Math.cbrt()

Answer

It returns the cube root of its argument as a double value.

Question 4

Math.log()

Answer

It returns the natural logarithm of its argument. Both return type and argument is of double data type.

Distinguish between

Question 1

Math.ceil() and Math.floor()

Math.ceil( ) Math.floor( )

It returns the smallest double value that is greater It returns the largest double value that is less than
than or equal to the argument and is equal to a or equal to the argument and is equal to a
mathematical integer. mathematical integer.

double a = Math.ceil(65.5); double b = Math.floor(65.5);


In this example, a will be assigned the value of 66.0 In this example, b will be assigned the value of
as it is the smallest integer greater than 65.5. 65.0 as it is the largest integer smaller than 65.5.

Question 2

Math.rint() and Math.round()


Math.rint( ) Math.round( )

It rounds off its argument to the nearest It rounds off its argument to the nearest mathematical integer
mathematical integer and returns its and returns its value as an int or long type. If argument is float,
value as a double type. return type is int, if argument is double, return type is long.

At mid-point, it returns the integer that


At mid-point, it returns the higher integer.
is even

double a = Math.rint(1.5); long a = Math.round(1.5);


double b =Math.rint(2.5); long b = Math.round(2.5);
Both, a and b will have a value of 2.0 a will have a value of 2 and b will have a value of 3

Solutions to Unsolved Java Programs

Question 1

Write a program to calculate the value of the given expression:


1/a2 + 2/b2 + 3/c2
Take the values of a, b and c as input from the console. Finally, display the result of the expression to its nearest
whole number.

import java.util.Scanner;

public class KboatExpression


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the value of a: ");


int a = in.nextInt();

System.out.print("Enter the value of b: ");


int b = in.nextInt();

System.out.print("Enter the value of c: ");


int c = in.nextInt();

double exp = (1 / Math.pow(a, 2)) + (2 / Math.pow(b, 2)) + (3 /


Math.pow(c, 2));
long roundedExp = Math.round(exp);

System.out.println("Result rounded to whole number: " + roundedExp);


}
}
Output

Question 2

For every natural number m>1; 2m, m2-1 and m2+1 form a Pythagorean triplet. Write a program to input the
value of 'm' through console to display a 'Pythagorean Triplet'.
Sample Input: 3
Then 2m=6, m2-1=8 and m2+1=10
Thus 6, 8, 10 form a 'Pythagorean Triplet'.

import java.util.Scanner;

public class KboatPythagoreanTriplet


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the value of m: ");


int m = in.nextInt();

if (m < 2) {
System.out.println("Invalid Input, m should be greater than 1");
return;
}

int firstTriplet = 2 * m;
int secondTriplet = (int)(Math.pow(m, 2) - 1);
int thirdTriplet = (int)(Math.pow(m, 2) + 1);

System.out.println("Pythagorean Triplets: "


+ firstTriplet
+ ", "
+ secondTriplet
+ ", "
+ thirdTriplet);

}
}

Output

Question 3

Write a program to input a number. Calculate its square root and cube root. Finally, display the result by
rounding it off.
Sample Input: 5
Square root of 5= 2.2360679
Rounded form= 2
Cube root of 5 = 1.7099759
Rounded form= 2

import java.util.Scanner;

public class KboatRoots


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

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


int num = in.nextInt();

double sqrtValue = Math.sqrt(num);


double cbrtValue = Math.cbrt(num);
long roundSqrt = Math.round(sqrtValue);
long roundCbrt = Math.round(cbrtValue);

System.out.println("Square root of " + num + " = " + sqrtValue);


System.out.println("Rounded form = " + roundSqrt);
System.out.println("Cube root of " + num + " = " + cbrtValue);
System.out.println("Rounded form = " + roundCbrt);
}
}

Output

Question 4

The volume of a sphere is calculated by using formula:


v = (4/3)*(22/7)*r3
Write a program to calculate the radius of a sphere by taking its volume as an input.
Hint: radius = ∛(volume * (3/4) * (7/22))

import java.util.Scanner;

public class KboatSphere


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter volume of sphere: ");


double v = in.nextDouble();

double r = Math.cbrt(v * (3 / 4.0) * (7 / 22.0));


System.out.println("Radius of sphere = " + r);
}
}
Output

Question 5

A trigonometrical expression is given as:


(Tan A - Tan B) / (1 + Tan A * Tan B)
Write a program to calculate the value of the given expression by taking the values of angles A and B (in
degrees) as input.
Hint: radian= (22 / (7 * 180)) * degree

import java.util.Scanner;

public class KboatTrigExp


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter angle A in degrees: ");


double angleADeg = in.nextDouble();

System.out.print("Enter angle B in degrees: ");


double angleBDeg = in.nextDouble();

double angleARad = (22 * angleADeg) / (7 * 180);


double angleBRad = (22 * angleBDeg) / (7 * 180);

double numerator = Math.tan(angleARad) - Math.tan(angleBRad);


double demoninator = 1 + Math.tan(angleARad) * Math.tan(angleBRad);
double trigExp = numerator / demoninator;

System.out.println("tan(A - B) = " + trigExp);


}
}
Output

Question 6

The standard form of quadratic equation is represented as:


ax2 + bx + c = 0
where d= b2 - 4ac, known as 'Discriminant' of the equation.
Write a program to input the values of a, b and c. Calculate the value of discriminant and display the output to
the nearest whole number.

import java.util.Scanner;

public class KboatQuadEq


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter a: ");
int a = in.nextInt();

System.out.print("Enter b: ");
int b = in.nextInt();

System.out.print("Enter c: ");
int c = in.nextInt();

double d = Math.pow(b, 2) - (4 * a * c);


long roundedD = Math.round(d);

System.out.println("Discriminant to the nearest whole number = " +


roundedD);
}

}
Output

Question 7

The sum of first n odd natural numbers can be calculated as n2, where n is the number of odd natural.
For example,
Sum = 1 + 3 + 5 + 7; number of odd natural = 4
Therefore, Sum = 42 = 16
Write a program to input number of odd natural terms and display sum of the given series:
(a) 1 + 3 + 5 + ................... + 29 + 31
(b) 1 + 3 + 5 + 7 + ................... + 47 + 49

import java.util.*;

public class KboatCalculateSum


{

public static void main(String args[])


{
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of odd natural terms: ");
int num = in.nextInt();

System.out.println("Number of odd natural terms = " + num);

double sum = Math.pow(num,2);


System.out.println("Sum = " + sum);

}
}
Output

Question 8

Write a program to input the sum. Calculate and display the compound interest in 3 years, when the rates for the
successive years are r1%, r2% and r3% respectively.

Hint: [A = P * (1 + (r1 / 100)) * (1 + (r2 / 100)) * (1 + (r3 / 100)) and CI = A - P ]

import java.util.*;

public class KboatCompoundInterest


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);

System.out.print("Enter principal: ");


double p = in.nextDouble();

System.out.print("Enter interest rate for 1st year: ");


float r1 = in.nextFloat();
System.out.print("Enter interest rate for 2nd year: ");
float r2 = in.nextFloat();
System.out.print("Enter interest rate for 3rd year: ");
float r3 = in.nextFloat();

double amt = p * (1 + (r1 / 100))


* (1 + (r2 / 100))
* (1 + (r3 / 100));
double ci = amt - p;

System.out.println("Amount after 3 years: Rs. " + amt);


System.out.println("Compound Interest: Rs. " + ci);
}
}

Output

Chapter 1 - Unit 8

Iterative Constructs in Java

Multiple Choice Questions

Question 1

Which of the following statements will terminate the premature execution of a program?

1. System.exit(0)
2. break
3. stop
4. end

Answer

System.exit(0)

Reason — As soon as System.exit(0) function is invoked, it terminates the execution, ignoring the rest of the
statements of the program.
Question 2

Which of the following for loop will not be an infinite loop?

1. for(; ;)
2. for(a = 0; a < 1; a--)
3. for(a = 0; ; a++)
4. for(a = -1; a < 1; a++)

Answer

for(a = -1; a < 1; a++)

Reason — In the selected for loop, the initial value of a (-1) will be incremented by 1 every time and eventually
the condition (a < 1) will become false and the loop will terminate.

Question 3

Choose the odd one out from the following:

1. return
2. break
3. continue
4. if-else

Answer

if-else

Reason — if-else is a conditional statement while return, break and continue are jump statements.

Question 4

The while statement repeats the execution of a block only when the given condition is:

1. False
2. True
3. 1
4. 0

Answer

True

Reason — The while statement repeats the execution of a block only when the given condition is true.

Question 5

Which of the following is not a part of the looping construct?

1. close
2. for
3. break
4. continue
Answer

close

Reason — Close is not a part of the looping construct.

Fill in the blanks

Question 1

When the statements are repeated sequentially a number of times in a program, the construct is known as loop.

Question 2

For loop is also known as entry controlled loop.

Question 3

do-while loop is called an exit controlled loop.

Question 4

do-while loop executes at least once, if the condition is false.

Question 5

while loop checks the condition first before its execution.

Question 6

To find the sum of any ten numbers, the loop will run ten times.

Predict the output

Question 1

The following is a segment of a program.

x = 1; y = 1;
if(n > 0)
{
x = x + 1;
y = y + 1;
}
What will be the value of x and y, if n assumes a value:

(a) 1 (b) 0

Answer

(a) When n = 1

Output

x = 2
y = 2

Explanation

As n is 1, so if condition is true. x and y are incremented by 1 so both become 2.


(a) When n = 0

Output

x = 1
y = 1

Explanation

As n is 1, so if condition is false. Values of both x and y remain unchanged.

Question 2

Analyze the following program segment and determine how many times the body of the loop will be executed
(show the working).

x = 5; y = 50;
while(x <= y)
{
y = y / x;
System.out.println(y);
}
Answer

Output

10
2
The loop will execute 2 times.

Explanation

x y Remarks

5 50 Initial values

5 10 After 1st iteration

5 2 After 2nd iteration

After 2 iterations y becomes less than x so condition of while loop becomes false and it stops executing.

Question 3

What will be the output of the following code?

int m = 2;
int n = 15;
for(int i = 1 ; i < 5 ; i++)
m++;
--n;
System.out.println(" m = " + m);
System.out.println(" n = " + n);
Answer

Output

m = 6
n = 14

Explanation

As there are no curly braces after the for loop so only the statement m++; is inside the loop. Loop executes 4
times so m becomes 6. The next statement --n; is outside the loop so it is executed only once and n becomes 14.

Question 4

Analyze the following program segment and determine how many times the loop will be executed. What will
be the output of the program segment?

int k = 1, i = 2;
while(++i < 6)
k *= i;
System.out.println(k);
Answer

Output

60

Explanation

This table shows the change in values of i and k as while loop iterates:

i k Remarks

2 1 Initial values

3 3 1st Iteration

4 12 2nd Iteration

5 60 3rd Iteration

6 60 Once i becomes 6, condition is false and loop stops iterating.

Notice that System.out.println(k); is not inside while loop. As there are no curly braces so only the
statement k *= i; is inside the loop. The statement System.out.println(k); is outside the while loop, it is
executed once and prints value of k which is 60 to the console.
Question 5

Give the output of the following program segment and also mention the number of times the loop is executed.

int a , b;
for(a = 6 ; b = 4; a <= 4; a = a + 6)
{
if(a % b == 0)
break;
}
System.out.println(a);
Answer

Output

6
The loop executes 0 times.

Explanation

a is initialized to 6 and as the loop condition is false before the first iteration itself so the loop doesn't execute.

Question 6

Give the output of the following program segment and also mention how many times the loop is executed.

int i;
for(i = 5 ; i > 10 ; i++)
System.out.println(i);
System.out.println(i * 4);
Answer

Output

20
The loop executes 0 times.

Explanation

i is initialized to 5 and as the loop condition is false before the first iteration itself so the loop doesn't execute.
The statement System.out.println(i * 4); is outside the loop so it gets executed once, printing 20 to the
console.
Rewrite the following programs

Question 1

Using for loop:

int i = 1;
int d = 5;
do
{
d = d * 2;
System.out.println(d);
i++;
}
while (i <= 5);
Answer

int d = 5;
for (int i = 1 ; i <= 5 ; i++) {
d = d * 2;
System.out.println(d);
}

Question 2

Using while loop:

import java.util.*;
class Number
{
public static void main(String args[])
{
int n , r;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
n = in.nextInt();
do
{
r = n % 10;
n = n / 10;
System.out.println(r);
}
while(n != 0);
}
}
Answer

import java.util.*;
class Number
{
public static void main(String args[])
{
int n , r;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
n = in.nextInt();
while (n != 0) {
r = n % 10;
n = n / 10;
System.out.println(r);
}
}
}
Answer the following questions

Question 1

What is for loop? What are the parameters used in for loop?
Answer

The for loop is used when number of iterations is fixed and known. It is also referred to as a fixed or known
iterative looping construct.

The following parameters are commonly used in a for loop:

1. An initial value for the loop control variable.


2. A condition—loop will iterate as long as this condition remains true.
3. An update expression to modify the loop control variable after every iteration.
4. Body of the loop which consists of the statements that needs to be repeatedly executed.

Below is an example of for loop, it prints the table of 2 till 12:

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


int a = 2 * i;
System.out.println("2 x " + i + "\t= " + a);
}

Question 2

Define the following with their constructs:

(a) Entry controlled loop

(b) Exit controlled loop

Answer

(a) Entry controlled loop — An entry-controlled loop checks the condition at the time of entry. Only if the
condition is true, the program control enters the body of the loop. for and while loops are entry-controlled
loops.

(b) Exit controlled loop — An exit-controlled loop checks the condition after executing its body. If the
condition is true, loop will perform the next iteration otherwise program control will move out of the loop. do-
while loop is an exit-controlled loop.

Question 3

Write down the syntax of:

(a) do - while

(b) while loop

Answer

(a) Syntax of do - while

do {
//loop-body
} while (condition);
(b) Syntax of while loop

while (condition) {
//loop-body
}
Question 4

What is the purpose of using:

(a) break statement

(b) continue statement

in a program

Answer

(a) break statement — break statement is used when the user would like to terminate the loop before its
completion and send the control to exit the loop, if certain condition is true.

(b) continue statement — When continue statement is invoked, the control goes back to check the condition of
the loop by ignoring rest of the statements of the loop.

Question 5

Distinguish between while and do-while loop.

Answer

while do-while

It is an entry-controlled loop. It is an exit-controlled loop.

It is helpful in situations where number of iterations are It is suitable when we need to display a menu
not known. to the user.

Question 6

What is meant by an infinite loop? Give an example.

Answer

A loop that repeats for infinite number of iterations is known as infinite loop or endless loop.

Consider the example given below. Since all the parameters are missing in for loop, it will repeat for infinite
number of times.

for ( ; ; )
System.out.println("Infinite Loop");

Question 7

State one difference and one similarity between while loop and do-while loop.

Answer

Similarity — Both while and do-while are suitable in situations where numbers of iterations is not known.

Difference — while is an entry-controlled loop whereas do-while is an exit-controlled loop.


Solutions to Unsolved Java Programs

Question 1

Write the programs in Java to display the first ten terms of the following series:

(a) 0, 1, 2, 3, 6,

public class KboatTribonacci


{
public void displaySeries() {

int a = 0, b = 1, c = 2;

System.out.print(a + ", " + b + ", " + c);

for (int i = 0; i < 7; i++) {


int n = a + b + c;
System.out.print(", " + n);
a = b;
b = c;
c = n;
}
}
}

Output

(b) 1, -3, 5, -7, 9,

public class KboatSeriesB


{
public void displaySeries() {

int term = 1;
System.out.print(term);
for (int i = 2; i <= 10; i++) {

term += 2;

if (i % 2 == 0)
System.out.print(", " + (-term));
else
System.out.print(", " + term);
}
}
}

Output

(c) 0, 3, 8, 15,

public class KboatSeries


{
public void generateSeries() {

int term = 0;
System.out.print(term);
for (int i = 3; i < 20; i = i + 2) {
term += i;
System.out.print(", " + term);
}
}
}
Output

(d) 1, 11, 111, 1111,

public class KboatSeries


{
public void generateSeries() {
int term = 1;

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


System.out.print(term + ", ");
term = term * 10 + 1;
}
}
}

Output

(e) 1, 12, 123, 1234,

public class KboatSeries


{
public void generateSeries() {

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


for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.print(", ");
}

}
}

Output

Question 2

Write the programs in Java to find the sum of the following series:

(a) S = 1 + 1 + 2 + 3 + 5 + ....... to n terms

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter n: ");
int n = in.nextInt();

int a = 1, b = 1;
int sum = a + b;

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


int term = a + b;
sum += term;
a = b;
b = term;
}
System.out.println("Sum=" + sum);
}

Output

(b) S = 2 - 4 + 6 - 8 + ....... to n

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter n: ");
int n = in.nextInt();

int sum = 0;

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


if (i % 2 == 0) {
sum -= j;
}
else {
sum += j;
}
}

System.out.println("Sum=" + sum);
}
}

Output

(c) S = 1 + (1+2) + (1+2+3) + ....... + (1+2+3+ ....... + n)

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0, term = 0;

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


term += i;
sum += term;
}

System.out.println("Sum=" + sum);
}
}
Output

(d) S = 1 + (1*2) + (1*2*3) + ....... + (1*2*3* ....... * n)

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter n: ");
int n = in.nextInt();
long sum = 0, term = 1;

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


term *= i;
sum += term;
}

System.out.println("Sum=" + sum);
}
}
Output

(e) S = 1 + (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + ....... + (1 + 2 + 3 ....... + n) / (1 * 2 * 3 * ....... * n)

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter n: ");
int n = in.nextInt();
double seriesSum = 0.0;
int sum = 0;
double prod = 1.0;

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


sum += i;
prod *= i;
double term = sum / prod;
seriesSum += term;
}

System.out.println("Sum=" + seriesSum);
}
}
Output

Question 3

Write the programs to find the sum of the following series:

(a) S = a + a2 + a3 + ....... + an

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;

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


sum += Math.pow(a, i);
}

System.out.println("Sum=" + sum);
}
}
Output

(b) S = (a+1) + (a+2) + (a+3) + ....... + (a+n)

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;

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


sum += a + i;
}

System.out.println("Sum=" + sum);
}
}
Output

(c) S = (a/2) + (a/5) + (a/8) + (a/11) + ....... + (a/20)

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter a: ");
int a = in.nextInt();
double sum = 0;

for (int i = 2; i <= 20; i = i + 3) {


sum += a / (double)i;
}

System.out.println("Sum=" + sum);
}
}
Output

(d) S = (1/a) + (2/a2) + (3/a3) + ....... to n

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0;

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


sum += (i / Math.pow(a, i));
}

System.out.println("Sum=" + sum);
}
}
Output

(e) S = a - a3 + a5 - a7 + ....... to n

import java.util.Scanner;

public class KboatSeries


{
public void computeSeriesSum() {

Scanner in = new Scanner(System.in);


System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;

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


if (j % 2 == 0)
sum -= Math.pow(a, i);
else
sum += Math.pow(a, i);
}

System.out.println("Sum=" + sum);
}
}
Output

Question 4

Write a program to enter two numbers and check whether they are co-prime or not.
[Two numbers are said to be co-prime, if their HCF is 1 (one).]
Sample Input: 14, 15
Sample Output: They are co-prime.

import java.util.Scanner;

public class KboatCoprime


{
public void checkCoprime() {

Scanner in = new Scanner(System.in);


System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter b: ");
int b = in.nextInt();

int hcf = 1;

for (int i = 1; i <= a && i <= b; i++) {


if (a % i == 0 && b % i == 0)
hcf = i;
}

if (hcf == 1)
System.out.println(a + " and " + b + " are co-prime");
else
System.out.println(a + " and " + b + " are not co-prime");
}
}
Output

Question 5

Write a program to input a number. Display the product of the successors of even digits of the number entered
by user.
Input: 2745
Output: 15
[Hint: The even digits are: 2 and 4
The product of successor of even digits is: 3*5= 15]

import java.util.Scanner;

public class KboatEvenSuccessor


{
public void computeProduct() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = in.nextInt();
int orgNum = num;
int prod = 1;

while (num != 0) {
int digit = num % 10;
num /= 10;

if (digit % 2 == 0)
prod = prod * (digit + 1);
}

if (prod == 1)
System.out.println("No even digits in " + orgNum);
else
System.out.println("Product of even digits successors is "
+ prod);
}
}

Output

Question 6

Write a program to input a number and check and print whether it is a Pronic number or not. [Pronic number is
the number which is the product of two consecutive integers.]
Examples:
12 = 3 * 4
20 = 4 * 5
42 = 6 * 7

import java.util.Scanner;

public class KboatPronicNumber


{
public void pronicCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to check: ");
int num = in.nextInt();

boolean isPronic = false;

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


if (i * (i + 1) == num) {
isPronic = true;
break;
}
}

if (isPronic)
System.out.println(num + " is a pronic number");
else
System.out.println(num + " is not a pronic number");
}
}

Output

Question 7

A prime number is said to be 'Twisted Prime', if the new number obtained after reversing the digits is also a
prime number. Write a program to accept a number and check whether the number is 'Twisted Prime' or not.
Sample Input: 167
Sample Output: 761
167 is a 'Twisted Prime'.

import java.util.Scanner;

public class KboatTwistedPrime


{
public void twistedPrimeCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();

if (num == 1) {
System.out.println(num + " is not a twisted prime number");
}
else {
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) {

int t = num;
int revNum = 0;

while (t != 0) {
int digit = t % 10;
t /= 10;
revNum = revNum * 10 + digit;
}

for (int i = 2; i <= revNum / 2; i++) {


if (revNum % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime)
System.out.println(num + " is a twisted prime number");
else
System.out.println(num + " is not a twisted prime number" );
}

}
}
Output

Question 8

Write a program to input a number and check whether it is a prime number or not. If it is not a prime number
then display the next number that is prime.
Sample Input: 14
Sample Output: 17

import java.util.Scanner;

public class KboatPrimeCheck


{
public void primeCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();

boolean isPrime = true;


for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) {
System.out.println(num + " is a prime number");
}
else {
for (int newNum = num + 1; newNum <= Integer.MAX_VALUE; newNum++) {
isPrime = true;
for (int i = 2; i <= newNum / 2; i++) {
if (newNum % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("Next prime number = " + newNum);
break;
}
}
}
}
}

Output
Question 9

A number is said to be Duck if the digit zero is (0) present in it. Write a program to accept a number and check
whether the number is Duck or not. The program displays the message accordingly. (The number must not
begin with zero)
Sample Input: 5063
Sample Output: It is a Duck number.
Sample Input: 7453
Sample Output: It is not a Duck number.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class KboatDuckNumber


{
public void duckNumberCheck() throws IOException {

InputStreamReader reader = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(reader);
System.out.print("Enter number: ");
boolean isDuck = false;
boolean firstZero = false;
int c = 0, d;

/*
* 10 is the ASCII code of newline
* We will read from inputstream
* one character at a time till we
* encounter a newline i.e. enter
*/
while((d = in.read()) != 10) {

char ch = (char)d;

if (c == 0 && ch == '0' )
firstZero = true;

if (!firstZero && ch == '0')


isDuck = true;

c++;
}

if (isDuck)
System.out.println("Duck Number");
else
System.out.println("Not a Duck Number");
}
}
Output

Question 10

Write a program to input a number and display it into its Binary equivalent.
Sample Input: (21)10
Sample Output: (10101)2

import java.util.*;

public class KboatDecimaltoBinary


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the decimal number: ");
long decimal = in.nextLong();
long binary = 0, m = 1, rem = 0;

while(decimal > 0) {
rem = decimal % 2;
binary = binary + (rem * m);
m *= 10;
decimal /= 2;
}
System.out.println("Equivalent binary number: " + binary);
}
}
Output

Question 11

A computerised bus charges fare from each of its passengers based on the distance travelled as per the tariff
given below:

Distance (in km) Charges

First 5 km ₹80

Next 10 km ₹10/km

More than 15 km ₹8/km

As the passenger enters the bus, the computer prompts 'Enter distance you intend to travel'. On entering the
distance, it prints his ticket and the control goes back for the next passenger. At the end of journey, the
computer prints the following:

1. the number of passenger travelled


2. total fare received

Write a program to perform the above task.


[Hint: Perform the task based on user controlled loop]

import java.util.Scanner;

public class KboatBusTravel


{
public void busTravel() {

Scanner in = new Scanner(System.in);


int dist, tf = 0, tp = 0;
System.out.println("Enter distance as -1 to complete the journey");
while (true) {
System.out.print("Enter distance you intend to travel: " );
dist = in.nextInt();
int f = 0;
if (dist == -1) {
break;
}
else if (dist <= 5) {
f = 80;
}
else if (dist <= 15) {
f = 80 + ((dist - 5) * 10);
}
else {
f = 80 + 100 + ((dist - 15) * 8);
}

tf += f;
tp++;

System.out.println("Your fare is " + f);


}

System.out.println("Total Passengers: " + tp);


System.out.println("Total Fare: " + tf);
}
}
Output

Question 12

A special two-digit number is such that when the sum of its digits is added to the product of its digits, the result
is equal to the original two-digit number.

Example: Consider the number 59.


Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59

Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits. If the value
is equal to the number input, then display the message "Special two—digit number" otherwise, display the
message "Not a special two-digit number".

import java.util.Scanner;

public class KboatSpecialNumber


{
public void checkNumber() {

Scanner in = new Scanner(System.in);

System.out.print("Enter a 2 digit number: ");


int orgNum = in.nextInt();

int num = orgNum;


int count = 0, digitSum = 0, digitProduct = 1;

while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
digitProduct *= digit;
count++;
}

if (count != 2)
System.out.println("Invalid input, please enter a 2-digit number");
else if ((digitSum + digitProduct) == orgNum)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");

}
}

Output

Question 13

An abundant number is a number for which the sum of its proper divisors (excluding the number itself) is
greater than the original number. Write a program to input number and check whether it is an abundant number
or not.
Sample input: 12
Sample output: It is an abundant number.
Explanation: Its proper divisors are 1, 2, 3, 4 and 6
Sum = 1 + 2 + 3 + 4 + 6 = 16
Hence, 12 is an abundant number.

import java.util.Scanner;

public class KboatAbundantNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = in.nextInt();
int sum = 0;

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


if (n % i == 0)
sum += i;
}

if (sum > n)
System.out.println(n + " is an abundant number.");
else
System.out.println(n + " is not an abundant number." );
}
}

Output

Question 14

Write a program to accept a number and check whether it is a 'Spy Number' or not. (A number is spy if the sum
of its digits equals the product of its digits.)
Example: Sample Input: 1124
Sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1*1*2*4 = 8

import java.util.Scanner;

public class KboatSpyNumber


{
public void spyNumCheck() {

Scanner in = new Scanner(System.in);

System.out.print("Enter Number: ");


int num = in.nextInt();

int digit, sum = 0;


int orgNum = num;
int prod = 1;

while (num > 0) {


digit = num % 10;

sum += digit;
prod *= digit;
num /= 10;
}

if (sum == prod)
System.out.println(orgNum + " is Spy Number");
else
System.out.println(orgNum + " is not Spy Number");

}
}
Output

Question 15

Write a program to input a number and check whether it is a Harshad Number or not. [A number is said to be
Harshad number, if it is divisible by the sum of its digits. The program displays the message accordingly.]
For example;
Sample Input: 132
Sum of digits = 6 and 132 is divisible by 6.
Output: It is a Harshad Number.
Sample Input: 353
Output: It is not a Harshad Number.

import java.util.*;

public class KboatHarshadNumber


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = in.nextInt();
int x = num, rem = 0, sum = 0;

while(x > 0) {
rem = x % 10;
sum = sum + rem;
x = x / 10;
}

int r = num % sum;


if(r == 0)
System.out.println(num + " is a Harshad Number.");
else
System.out.println(num + " is not a Harshad Number.");
}
}

Output

Question 16

Write a program to display all Pronic numbers in the range from 1 to n.


Hint: A Pronic number is a number which is the product of two consecutive numbers in the form of n * (n + 1).
For example;
2, 6, 12, 20, 30,...........are Pronic numbers.

import java.util.Scanner;

public class KboatPronicNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = in.nextInt();

System.out.println("Pronic numbers from 1 to " + n + " :");

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


for(int j = 1; j <= i-1; j++) {
if (j * (j + 1) == i) {
System.out.print(i + " ");
break;
}
}
}
}
}

Output

Question 17

You can multiply two numbers 'm' and 'n' by repeated addition method.
For example, 5 * 3 = 15 can be performed by adding 5 three times ⇒ 5 + 5 + 5 = 15

Similarly, successive subtraction of two numbers produces 'Quotient' and 'Remainder' when a number 'a' is
divided by 'b' (a>b).
For example, 5/2 ⇒ Quotient = 2 and Remainder = 1
Follow steps shown below:

Process Result Counter

5-2 3 1

3-2 1 2

Sample Output: The last counter value represents 'Quotient' ⇒ 2


The last result value represents 'Remainder' ⇒ 1

Write a program to accept two numbers. Perform multiplication and division of the numbers as per the process
shown above by using switch case statement.

import java.util.Scanner;

public class KboatArithmetic


{
public void computeResult() {

Scanner in = new Scanner(System.in);


System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
System.out.println("1. Multiplication");
System.out.println("2. Division");
System.out.print("Enter your choice: ");
int ch = in.nextInt();

switch (ch) {
case 1:
int rMul = 0;
for (int i = 1; i <= b; i++) {
rMul += a;
}
System.out.println("Multiplication result = " + rMul);
break;

case 2:
int count = 0, t = a;
while (t > b) {
t -= b;
count++;
}
System.out.println("Divison Result");
System.out.println("Quotient = " + count);
System.out.println("Remainder = " + t);
break;

default:
System.out.println("Incorrect Choice");
break;
}
}

}
Output
Question 18

Using a switch statement, write a menu driven program to:

(a) generate and display the first 10 terms of the Fibonacci series
0, 1, 1, 2, 3, 5
The first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two.

(b) find the sum of the digits of an integer that is input by the user.
Sample Input: 15390
Sample Output: Sum of the digits = 18
For an incorrect choice, an appropriate error message should be displayed.

import java.util.Scanner;

public class KboatFibonacciNDigitSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Fibonacci Series");
System.out.println("2. Sum of digits");
System.out.print("Enter your choice: ");
int ch = in.nextInt();

switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
/*
* i is starting from 3 below
* instead of 1 because we have
* already printed 2 terms of
* the series. The for loop will
* print the series from third
* term onwards.
*/
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;

case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;

default:
System.out.println("Incorrect choice");
break;
}
}
}

Output
Question 19

Using switch statement, write a menu driven program for the following:

(a) To find and display the sum of the series given below:

S = x1 - x2 + x3 - x4 + x5 - ....................... - x20

(b) To find and display the sum of the series given below:
S = 1/a2 + 1/a4 + 1/a6 + 1/a8 + ....................... to n terms

For an incorrect option, an appropriate error message should be displayed.

import java.util.Scanner;

public class KboatSeriesSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Sum of x^1 - x^2 + .... - x^20");
System.out.println("2. Sum of 1/a^2 + 1/a^4 + .... to n terms" );
System.out.print("Enter your choice: ");
int ch = in.nextInt();

switch (ch) {
case 1:
System.out.print("Enter the value of x: ");
int x = in.nextInt();
long sum1 = 0;
for (int i = 1; i <= 20; i++) {
int term = (int)Math.pow(x, i);
if (i % 2 == 0)
sum1 -= term;
else
sum1 += term;
}
System.out.println("Sum = " + sum1);
break;

case 2:
System.out.print("Enter the number of terms: " );
int n = in.nextInt();
System.out.print("Enter the value of a: ");
int a = in.nextInt();
int c = 2;
double sum2 = 0;
for(int i = 1; i <= n; i++) {
sum2 += (1/Math.pow(a, c));
c += 2;
}
System.out.println("Sum = " + sum2);
break;

default:
System.out.println("Incorrect choice");
break;
}
}
}
Output

Question 20

Write a menu driven program to perform the following tasks:

(a) Tribonacci numbers are a sequence of numbers similar to Fibonacci numbers, except that a number is
formed by adding the three previous numbers. Write a program to display the first twenty Tribonacci numbers.
For example;
1, 1, 2, 4, 7, 13, ......................

(b) Write a program to display all Sunny numbers in the range from 1 to n.
[Hint: A number is said to be sunny number if square root of (n+1) is an integer.]
For example,
3, 8, 15, 24, 35,......................are sunny numbers.

For an incorrect option, an appropriate error message should be displayed.

import java.util.Scanner;
public class KboatTribNSunNos
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Tribonacci numbers");
System.out.println("2. Sunny numbers");
System.out.print("Enter your choice: ");
int ch = in.nextInt();

switch (ch) {
case 1:
int a = 1, b = 1, c = 2;

System.out.print(a + " " + b + " " + c);

for (int i = 4; i <= 20; i++) {


int term = a + b + c;
System.out.print(" " + term);
a = b;
b = c;
c = term;
}
break;

case 2:
System.out.print("Enter n: ");
int n = in.nextInt();

double sqRoot, temp;

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


sqRoot = Math.sqrt(i + 1);
temp = sqRoot - Math.floor(sqRoot);
if (temp == 0)
System.out.print(i + " ");
}
break;

default:
System.out.println("Incorrect choice");
break;
}
}
}
Output

Chapter 1 - Unit 9

Nested Loop
Multiple Choice Questions

Question 1

A loop within another loop is called a:

1. double loop
2. embedded loop
3. circular loop
4. nested loop

Answer

nested loop

Reason — A loop within another loop is called a nested loop.

Question 2

The ............... break is used to terminate the outer loop from the block of inner loop.

1. level
2. labelled
3. unlabelled
4. forced

Answer

labelled

Reason — The labelled break is used to terminate the outer loop from the block of inner loop.

Question 3

Which of the following keywords can be used to terminate a switch case as well as a loop construct?

1. continue
2. void
3. break
4. stop

Answer

break

Reason — break can be used to terminate a switch case as well as a loop construct.

Question 4

Given: for(i = 0 ; i < 4 ; i++)


for(j = 1 ; j < 4 ; j++)
...............
Statement
...............
How many times the above nested loop will iterate?

1. 12 times
2. 8 times
3. 4 times
4. 16 times

Answer

12 times

Reason — The outer loop will execute 4 times. For each iteration of outer loop, the inner loop will execute 3
times. Therefore, total iterations of nested loop will be 4 x 3 = 12 times. The below table summarizes the
iteration of nested loops:

Value of i Value of j

0 1

1 1

2 1

3 1

Question 5

Which of the following statements is not valid for a nested loop?

1. The break statement can be used to terminate inner as well as outer loop.
2. The outer loop can be terminated from the block of inner loop.
3. The inner loop can be terminated from the block of outer loop.
4. The inner loop repeats the execution a number of times for each iteration of the outer loop.

Answer

The inner loop can be terminated from the block of outer loop.

Reason — The inner loop cannot be terminated from the block of outer loop.

State True or False

Question 1

Nested loop contains a single loop.


False

Question 2

When break statement is applied, it terminates the loop.


True

Question 3

The outer loop follows next iteration when iterations of inner loop is over.
True

Question 4

Nested loop means the using of two or more loops in a program.


False

Question 5

Labelled break statement allows the next iteration of the loop from any place of looping structure.
False

Question 6

In a nested loop, break and continue can be used simultaneously.


False

Answer the following questions

Question 1

What is a nested loop?

Answer

When we use a loop within another loop, it is said to be a nested loop. The inner loop repeats a number of times
for each repetition of the outer loop.
Question 2

Write down the syntax of a nested for loop.

Answer

The syntax of nested loop is as follows:

for (<initial value>; <test condition>; <update value>) {

for (<initial value>; <test condition>; <update value>) {

executable statement(s)

Question 3

What action will you take to terminate an outer loop from the block of an inner loop?

Answer

An outer loop can be terminated from the block of an inner loop by using labelled break statement as shown in
the example given below:

outer: for (int i = 1; i <= 5; i++) {


for (int j = 1; j <= 10; j++) {
System.out.println(j);
if (i == 3)
break outer;
}
}
System.out.println("Outside outer loop");

Question 4

What is significance of break outer and continue outer in a nested loop?

Answer

break outer will terminate the loop that is labelled as outer in a nested loop and transfer the program control to
the statement just after the loop labelled as outer.

continue outer will skip the remaining statements of the nested loop and start the next iteration of the loop that
is labelled as outer.

Question 6

Write down the constructs (syntax) of:

(a) Nested do-while loop

(b) Nested while loop


Answer

(a) Construct of Nested do-while loop

do {
//statements of outer do-while loop
..
..
do {
//statements of inner do-while loop
} while (<condition>);
..
..
} while (<condition>);
(b) Construct of Nested while loop

while (<condition>) {
//statements of outer while loop
..
..
while (<condition>) {
//statements of inner while loop
}
..
..
}
Solutions to Unsolved Java Programs

Question 1

Write programs to find the sum of the following series:

(a) S = 1 + (3/2!) + (5/3!) + (7/4!) + ....... to n

import java.util.Scanner;

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 1, j = 1; i <= n; i++, j = j + 2) {
double f = 1;
for (int k = 1; k <= i; k++) {
f *= k;
}
sum += j / f;
}
System.out.println("Sum=" + sum);
}
}
Output

(b) S = a + (a/2!) + (a/3!) + (a/4!) + ....... + (a/n!)

import java.util.Scanner;

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0;

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


double f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
sum += a / f;
}
System.out.println("Sum=" + sum);

}
}
Output

(c) S = a - (a/2!) + (a/3!) - (a/4!) + ....... to n

import java.util.Scanner;

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0;

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


double f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
if (i % 2 == 0)
sum -= a / f;
else
sum += a / f;
}
System.out.println("Sum=" + sum);

}
}
Output

(d) S = (a/2!) - (a/3!) + (a/4!) - (a/5!) + ....... + (a/10!)

import java.util.Scanner;

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
double sum = 0;

for (int i = 2; i <= 10; i++) {


double f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
if (i % 2 == 0)
sum += a / f;
else
sum -= a / f;
}
System.out.println("Sum=" + sum);

}
}
Output

(e) S = (2/a) + (3/a2) + (5/a3) + (7/a4) + ....... to n

import java.util.Scanner;

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0;
int lastPrime = 1;

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


for (int j = lastPrime + 1; j <= Integer.MAX_VALUE; j++) {
boolean isPrime = true;
for (int k = 2; k <= j / 2; k++) {
if (j % k == 0) {
isPrime = false;
break;
}
}

if (isPrime) {
sum += j / Math.pow(a, i);
lastPrime = j;
break;
}
}
}
System.out.println("Sum=" + sum);
}
}

Output

Question 2

Write a program to input two numbers and check whether they are twin prime numbers or not.
Hint: Twin prime numbers are the prime numbers whose difference is 2.
For example: (5,7), (11,13), ....... and so on.

import java.util.Scanner;

public class KboatTwinPrime


{
public void twinPrimeCheck() {

Scanner in = new Scanner(System.in);

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


int a = in.nextInt();

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


int b = in.nextInt();

boolean isAPrime = true;

for (int i = 2; i <= a / 2; i++) {

if (a % i == 0) {
isAPrime = false;
break;
}

if (isAPrime && Math.abs(a - b) == 2) {

boolean isBPrime = true;

for (int i = 2; i <= b / 2; i++) {

if (b % i == 0) {
isBPrime = false;
break;
}

if (isBPrime)
System.out.println(a + " and " + b + " are twin prime");
else
System.out.println(a + " and " + b + " are not twin prime");
}
else
System.out.println(a + " and " + b + " are not twin prime");
}
}
Output

Question 3

Write a program to display all the numbers between 100 and 200 which don't contain zeros at any position.
For example: 111, 112, 113, ....... , 199

public class KboatNoZero


{
public void display() {

int count = 0;
for (int i = 100; i <= 200; i++) {

boolean isNoZero = true;


int t = i;
while (t > 0) {
if (t % 10 == 0) {
isNoZero = false;
break;
}

t /= 10;
}
if (isNoZero) {
System.out.print(i + " ");
count++;
}

//This will print 10 numbers per line


if (count == 10) {
System.out.println();
count = 0;
}
}

}
}

Output

Question 4

Write a program to display all prime palindrome numbers between 10 and 1000.
[Hint: A number which is prime as well a palindrome is said to be 'Prime Palindrome' number.]
For example: 11, 101, 131, 151,

public class KboatPrimePalindrome


{
public void displayPrimePalindrome() {

int count = 0;

for (int i = 10; i <= 1000; i++) {


int num = i, revNum = 0;
while (num != 0) {
int digit = num % 10;
num /= 10;
revNum = revNum * 10 + digit;
}

if (revNum == i) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {

if (i % j == 0) {
isPrime = false;
break;
}

}
if (isPrime) {
System.out.print(i + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
}
}
}

Output
Question 5

In an entrance examination, students have been appeared in English, Maths and Science papers. Write a
program to calculate and display average marks obtained by all the students. Take number of students appeared
and marks obtained in all three subjects by every student along with the name as inputs.
Display the name, marks obtained in three subjects and the average of all the students.

import java.util.Scanner;

public class KboatStudentMarks


{
public void studentMarks() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students: ");
int studentCount = in.nextInt();

String names[] = new String[studentCount];


int engMarks[] = new int[studentCount];
int sciMarks[] = new int[studentCount];
int mathsMarks[] = new int[studentCount];
double avgMarks[] = new double[studentCount];
double totalMarks = 0.0;

for (int i = 0; i < studentCount; i++) {


System.out.println("Enter details of student " + (i + 1));
System.out.print("Name: ");
in.nextLine();
names[i] = in.nextLine();
System.out.print("Marks in English: ");
engMarks[i] = in.nextInt();
System.out.print("Marks in Science: ");
sciMarks[i] = in.nextInt();
System.out.print("Marks in Maths: ");
mathsMarks[i] = in.nextInt();
avgMarks[i] = (engMarks[i] + sciMarks[i] + mathsMarks[i]) / 3.0;
totalMarks += avgMarks[i];
}

System.out.println();

for (int i = 0; i < studentCount; i++) {


System.out.println("Details of student " + (i + 1));
System.out.println("Name: " + names[i]);
System.out.println("English: " + engMarks[i]);
System.out.println("Science: " + sciMarks[i]);
System.out.println("Maths: " + mathsMarks[i]);
System.out.println("Average: " + avgMarks[i]);
}

double classAvg = totalMarks / studentCount;


System.out.println("\nAverage of all students is " + classAvg);
}
}
Output

Question 6

Write a program in Java to enter a number containing three digits or more. Arrange the digits of the entered
number in ascending order and display the result.
Sample Input: Enter a number 4972
Sample Output: 2, 4, 7, 9

import java.util.Scanner;

public class KboatDigitSort


{
public void sortDigits() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number having 3 or more digits: ");
int OrgNum = in.nextInt();

for (int i = 0; i <= 9; i++) {


int num = OrgNum;
int c = 0;
while (num != 0) {
if (num % 10 == i)
c++;
num /= 10;
}
for (int j = 1; j <= c; j++) {
System.out.print(i + ", ");
}
}

System.out.println();
}
}

Output
Question 7

Write a program to input a number and check whether it is 'Magic Number' or not. Display the message
accordingly.
A number is said to be a magic number if the eventual sum of digits of the number is one.
Sample Input : 55
Then, 5 + 5 = 10, 1 + 0 = 1
Sample Output: Hence, 55 is a Magic Number.
Similarly, 289 is a Magic Number.

import java.util.Scanner;

public class KboatMagicNum


{

public static void main(String args[]) {

Scanner in = new Scanner(System.in);


System.out.print("Enter number to check: ");
int num = in.nextInt();
int n = num;

while (n > 9) {
int sum = 0;
while (n != 0) {
int d = n % 10;
n /= 10;
sum += d;
}
n = sum;
}

if (n == 1)
System.out.println(num + " is Magic Number");
else
System.out.println(num + " is not Magic Number");

}
}
Output

Question 8

A number is said to be Multiple Harshad number, when divided by the sum of its digits, produces another
'Harshad Number'. Write a program to input a number and check whether it is a Multiple Harshad Number or
not.
(When a number is divisible by the sum of its digit, it is called 'Harshad Number').
Sample Input: 6804
Hint: 6804 ⇒ 6+8+0+4 = 18 ⇒ 6804/18 = 378
378 ⇒ 3+7+8= 18 ⇒ 378/18 = 21
21 ⇒ 2+1 = 3 ⇒ 21/3 = 7
Sample Output: Multiple Harshad Number

import java.util.Scanner;

public class KboatMultipleHarshad


{
public void checkMultipleHarshad() {

Scanner in = new Scanner(System.in);


System.out.print("Enter number to check: ");
int num = in.nextInt();
int dividend = num;
int divisor;
int count = 0;

while (dividend > 1) {


divisor=0;
int t = dividend;
while (t > 0) {
int d = t % 10;
divisor += d;
t /= 10;
}

if (dividend % divisor == 0 && divisor != 1) {


dividend = dividend / divisor;
count++;
}
else {
break;
}
}

if (dividend == 1 && count > 1)


System.out.println(num + " is Multiple Harshad Number");
else
System.out.println(num + " is not Multiple Harshad Number");
}
}

Output

Question 9

Write the programs to display the following patterns:

(a)

1
31
531
7531
97531

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i < 10; i = i + 2) {
for (int j = i; j > 0; j = j - 2) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

Output

(b)

1 2 3 4 5
6 7 8 9
10 11 12
13 14
15

public class KboatPattern


{
public void displayPattern() {
int a = 1;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
}
}
Output

(c)

15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

public class KboatPattern


{
public void displayPattern() {
int a = 15;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(a-- + "\t");
}
System.out.println();
}
}
}
Output

(d)

1
10
101
1010
10101

public class KboatPattern


{
public void displayPattern() {
int a = 1, b = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print(b + " ");
else
System.out.print(a + " ");
}
System.out.println();
}
}
}
Output

(e)

55555
4444
333
22
1

public class KboatPattern


{
public void displayPattern() {
for (int i = 0; i < 5; i++) {

for (int j = i; j > 0; j--) {


System.out.print(" ");
}

for (int k = 5 - i; k > 0; k--) {


System.out.print((5 - i) + " ");
}

System.out.println();
}
}
}
Output

(f)

12345
22345
33345
44445
55555

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {

for (int j = 1; j < i; j++)


System.out.print(i + " ");

for (int k = i; k <= 5; k++)


System.out.print(k + " ");

System.out.println();
}
}
}
Output

(g)

*
*#
*#*
*#*#
*#*#*

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print("# ");
else
System.out.print("* ");
}
System.out.println();
}
}
}
Output

(h)

54321
5432
543
54
5

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(i)

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

public class KboatPattern


{
public void displayPattern() {
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
}
}
Output

Question 10

Write a program to generate a triangle or an inverted triangle till n terms based upon the user's choice.

Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter the number of terms 5
Sample Output:
1
22
333
4444
55555

Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter the number of terms 6
Sample Output:
666666
55555
4444
333
22
1

import java.util.Scanner;

public class KboatPattern


{
public void choosePattern() {

Scanner in = new Scanner(System.in);


System.out.println("Type 1 for a triangle");
System.out.println("Type 2 for an inverted triangle");

System.out.print("Enter your choice: ");


int ch = in.nextInt();

System.out.print("Enter the number of terms: ");


int n = in.nextInt();

switch (ch) {
case 1:
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
break;

case 2:
for (int i = n; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
break;

default:
System.out.println("Incorrect Choice");
}
}
}
Output

Question 11

Using the switch statement, write a menu driven program for the following:
(a) To print the Floyd's triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

(b) To display the following pattern:


I
IC
ICS
ICSE

For an incorrect option, an appropriate error message should be displayed.

import java.util.Scanner;

public class KboatPattern


{
public void choosePattern() {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Floyd's triangle");
System.out.println("Type 2 for an ICSE pattern");

System.out.print("Enter your choice: ");


int ch = in.nextInt();

switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
break;

case 2:
String s = "ICSE";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(s.charAt(j) + " ");
}
System.out.println();
}
break;

default:
System.out.println("Incorrect Choice");
}
}
}
Output

Question 12

Using the switch case statement, write a menu driven program for the following:
(a) To input a number and display only those factors of the numbers which are prime.
Sample Input: 84
Sample Output: 2, 3, 7

(b) A program that displays the multiplication table from 1 to 10, as shown:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
...................................
...................................
...................................
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

import java.util.Scanner;

public class KboatPrimeFactorsNTables


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);

System.out.println("Enter 1 for prime factors");


System.out.println("Enter 2 for multiplication tables");

System.out.print("Enter your choice: ");


int ch = in.nextInt();

switch (ch) {
case 1:
System.out.print("Enter a number: ");
int num = in.nextInt();

for(int i = 2; i <= num/2; i++) {


int c = 0;
if(num % i == 0) {
for (int j = 1; j <= i; j++) {
if(i % j == 0)
c++;
}
if(c == 2)
System.out.print(i + " ");
}
}
break;

case 2:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++)
System.out.print((i * j) + " ");
System.out.println();
}
break;

default:
System.out.println("Incorrect Choice");
}
}
}

Output
Chapter 1 - Case Study

Case Study based questions from revision of Class IX Syllabus

Case Study based Questions

Question 1

Generally, a computer language uses either compiler or interpreter (a set of


programs) to convert source code into object code. But Java, a case sensitive
language, uses both the translators (i.e., compiler as well as interpreter).
Firstly, compiler converts the Java source code into an intermediate code
which is further converted into machine code with the help of an interpreter.

Based on the above discussion, answer the following questions:

(a) Which of the following statement is true?

1. Java compiler is a hardware.


2. Java compiler is a software but interpreter is a hardware.
3. Both the translators are hardware.
4. Both the translators are software.

(b) The intermediate code is referred to as:

1. Byte code
2. Assembly code
3. ASCII code
4. Unicode

(c) Java interpreter is also known as:

1. Artificial machine
2. Virtual machine
3. Real machine
4. Normal machine

(d) What is meant by a case sensitive language?

1. It understands only lowercase letters.


2. It understands only uppercase letters.
3. It distinguishes between lowercase and uppercase letters.
4. It doesn't distinguish between lowercase and uppercase letters.

Answer

(a) Both the translators are software.

(b) Byte code

(c) Virtual machine

(d) It distinguishes between lowercase and uppercase letters.

Question 2

An operator is basically a symbol which performs arithmetical and logical


operations to yield meaningful results. There are three types of operators
used to perform any operation in Java programming. They are arithmetical,
relational and logical operators. The arithmetical operators are used to
perform arithmetical calculations. They are unary, binary and ternary
operators. The syntax of using ternary operator is:
variable = (condition) ? expression 1 : expression 2;
Based on the above discussion, answer the following questions:

(a) A/An ............... operator works on a single operand.

1. binary
2. relational
3. unary
4. ternary

(b) Which of the following is not a logical operator?

1. ++
2. &&
3. ||
4. !

(c) Which of the following constructs is equivalent to the ternary operator in


Java language?

1. if
2. if-else
3. nested if
4. switch-case

(d) Which of the following is a relational operator?

1. &
2. $
3. !=
4. !

Answer

(a) unary

(b) ++

(c) if-else

(d) !=

Question 3

Functions are the built-in modules that can be used in our program to
perform a specific operation. There are some mathematical functions that are
used for specific functions. For example, we can use Math.sqrt( ) function to
return square root of a positive number, Math.random( ) and Math.ceil( ) to return
random number in a range of numbers to return the next higher integer
number.
Based on the above discussion, answer the following questions:

(a) What will be displayed, if the following statement is executed?


System.out.println(Math.sqrt(-25));

1. Infinite
2. -5.2
3. NaN
4. Logical error

(b) Math.random( ) function returns a random number in the range:

1. between 0 and 1
2. between -1 to 0
3. between -1 to 1
4. None of the above

(c) Which of the following function will return the next higher integer number?

1. Math.max( )
2. Math.min( )
3. Math.floor( )
4. Math.ceil( )

(d) Which of the following statement is true for Math.max( )?

1. It will always result in int type value.


2. It will always result in double type value.
3. The resultant data type will depend upon the type of arguments.
4. It will return float type, if arguments are double type.

Answer

(a) NaN

(b) between 0 and 1

(c) Math.ceil( )

(d) The resultant data type will depend upon the type of arguments.

Question 4

Java, like all other programming languages uses some statements that allow
us to check a condition and execute certain parts of a code depending on
whether the condition is true or false. Such statements are called conditional
statements. We can also use a conditional statement within another
conditional statement. The inner conditional statement is executed only when
the outer condition is true. The conditional statement can also be a multiple
branching statement.

Based on the above discussion, answer the following questions:

(a) Which of the following is not a decision making statement?

1. if - else
2. if
3. break
4. if-else-if

(b) A conditional statement used within another conditional statement is


known as ...............

1. nested conditional statement


2. embedded conditional statement
3. accumulated conditional statement
4. None of the above

(c) Which of the following is called as multiple branching statement?

1. if and only if
2. switch
3. control
4. shift

(d) Which of the following is not a component of multiple branching


statement?

1. break
2. default
3. case
4. pause

Answer

(a) break

(b) nested conditional statement

(c) switch

(d) pause

Question 5

The following program segment calculates the norm of a number. The norm of
a number is the square root of sum of squares of all the digits of the number.
Sample Input: 68
Sample Output: The norm of 68 is 10
[Hint: 6x6 + 8x8 = 36 + 64 = 100
The square root of 100 is 10. Hence, norm of 68 is 10]
There are some places in the program left blank marked with ?1?, ?2?, ?3? and
?4? to be filled with variable/function/expression.
Scanner in = new Scanner(System.in);
int num;
int d, s = 0;
num = ......?1?......
while (......?2?......)
{
d = num % 10;
s = ......?3?......
num = num / 10;
}
System.out.println("The norm of " + num + " is " + ......?4?......);
Based on the above discussion, answer the following questions:

(a) Which of the following will be filled in place of ?1?

1. in.nextInteger;
2. in.NextInt( );
3. in.nextInt( );
4. in.nextint( );

(b) What will you fill in place of ?2?

1. num > 0
2. num < 0
3. num > 1
4. num = 0

(c) What will you fill in place of ?3?

1. s + d * d
2. s * d + d
3. s * s + d
4. s + d

(d) What will you fill in place of ?4?

1. Math.sqrt(s)
2. Math.SQRT(s)
3. Math.sqrt(n)
4. Math.sqrt(num)

Answer

(a) in.nextInt( );

(b) num > 0

(c) s + d * d

(d) Math.sqrt(s)

The completed program is given below for reference:


Scanner in = new Scanner(System.in);
int num;
int d, s = 0;
num = in.nextInt( );
while (num > 0)
{
d = num % 10;
s = s + d * d;
num = num / 10;
}
System.out.println("The norm of " + num + " is " + Math.sqrt(s));

You might also like