Class 9 Computer

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

Chapter 1 - Unit 1

Principles of Object Oriented


Programming
Class 9 - APC Understanding Computer
Applications with BlueJ

Fill in the blanks

Question 1

An act of using essential features without including background details is called Data
Abstraction.

Question 2

In an Object Oriented Programming, the stress is given on data.

Question 3

Wrapping of data and function together as a single unit is called Encapsulation.

Question 4

An object has unique identity through which it may differ with some characteristics and
behaviour.

Question 5

The objects may communicate with each other through function.

Question 6

In POP, the global data are loosely attached to the function.

Question 7

The process by which a class acquires the property of another class is known as inheritance.
Question 8

In Object Oriented Programming, using a function for many purposes is termed


as polymorphism.

State whether the given statements are TRUE or FALSE

Question 1

In assembly level language, the instructions are given in terms of 0's and 1's.
False

Question 2

PASCAL is a structure oriented programming language.


True

Question 3

Machine level language requires a translator to convert input instructions to be understood by


the machine.
False

Question 4

Compilers and Interpreters are referred to as Language processors.


True

Question 5

A process according to which a class acquires the characteristics from another class is
Encapsulation.
False

Question 6

Procedure oriented program stresses on data.


False

Question 7

C++ is also an object oriented programming language.


True

Question 8

An object is identified by its characteristics.


True
Question 9

Function is a set of objects that share the common state and behaviour.
False

Question 10

Encapsulation keeps data safe from outside interference.


True

Name the following

Question 1

Two categories of Low Level languages

(a) Assembly Language


(b) Machine Language

Question 2

Two Procedure Oriented Languages

(a) BASIC
(b) COBOL

Question 3

Two structure oriented programming languages

(a) PASCAL
(b) ALGOL

Question 4

Two examples of Data Abstraction in your daily life

(a) Electrical Switchboard


(b) ATM

Question 5

Two examples of real world objects

(a) Television
(b) Car
Question 6

Two basic principles of Object Oriented Programming

(a) Encapsulation
(b) Inheritance

Write short notes with an example (if applicable)

Question 1

Object Oriented Programming

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.

Question 2

Data Abstraction

Data Abstraction is the act of representing the essential features without knowing the
background details. Example of Data Abstraction is given here.

Question 3

Encapsulation

Wrapping of data and functions that operate on that data into a single unit is called
Encapsulation. Example of Encapsulation is given here.

Question 4

Machine Level language

For the processor to perform any computation, we need to give the instructions and
data as a sequence of 0's & 1's. This binary sequence that a processor understands is
known as its Machine Level language. Machine Level language is made up of
instructions and data that are all binary numbers. Machine Level language of a
processor differs from vendor to vendor. So programs written in Machine Level
language of one type of processors will not work on a different type of processor.

Question 5

Polymorphism

In object-oriented programming, Polymorphism provides the means to perform a single


action in multiple different ways. Example of Polymorphism is given here.
Question 6

Procedure Oriented Programming

Procedure Oriented Programming basically consists of a list of instructions for the


computer to follow and these are organized into groups known as functions. In
Procedure Oriented Programming, most of the functions share global data and this data
moves more openly around the system from one function to the other.

Question 7

Inheritance

Inheritance enables new classes to receive or inherit the properties and methods of
existing classes. Example of Inheritance is given here.

Question 8

Assembly Level language

In Assembly Level language, instructions are written in more english like words knowns
as mnemonics. These instructions are not understood by the processor directly. They
are converted into equivalent Machine Level instructions through a translator program
called Assembler. Assembly Level language is machine dependent that makes it
unsuitable for writing portable programs that can execute across machines.

Distinguish between

Question 1

Object Oriented Programming and Procedure Oriented Programming

Object Oriented Programming Procedure Oriented Programming

The stress is put on data rather than functions. The stress is put on function rather than data.

The data is restricted, to be used in a specific It allows data to flow freely throughout the
program area. program.

It follows bottom-up programming approach. It follows top-down programming approach.


Question 2

High Level language and Low Level language

High Level language Low Level language

High Level language is machine independent. Low Level language is machine dependent.

High Level language is human friendly so it is Low Level language is machine friendly so it is
easy to understand for programmers. difficult to understand for programmers.

High Level language needs a compiler or Low Level language might need a assembler for
interpreter for translation to machine code. translation to machine code.

Programs written in High Level language are Programs written in Low Level language are hard
easier to modify and debug. to modify and debug.

Question 3

Compiler and Interpreter

Compiler Interpreter

It converts the whole source program into the It converts the source program into the object program, one
object program at once. line at a time.

It displays the errors for the whole program It displays the error one line at a time and only after fixing
together, after the compilation. that error the control goes to the next line.

Answer the following questions

Question 1

Enlist the features of Object Oriented Programming.

Some of the features of Object Oriented Programming are:

1. It gives stress on data items rather than functions.


2. It makes the complete program/problem simpler by dividing it into number of
objects.
3. The objects can be used as a bridge to have data flow from one function to
another.
4. The concept of data hiding enhances security in programs.
5. It is highly beneficial to solve complex programs.

Question 2

Which OOP principle implements function overloading? Explain

Polymorphism implements function overloading. It is the process of using a


function/method for more than one purpose. In function overloading, we write more
than one function with the same name but differing in the number and types of their
arguments to perform different tasks. This way we get different behaviours using the
same function name.

Question 3

Write three benefits of Object Oriented Programming.

Three benefits of Object Oriented Programming are:

1. The reusability of the program code is enhanced.


2. Data abstraction makes the software easier to handle.
3. Software for complex tasks can be easily developed.

Question 4

Mention two limitations of:

(a) Procedure Oriented Programming

1. No restriction on data values so managing changes is difficult as it impacts the


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

(b) Object Oriented Programming

1. Requires intensive testing processes.


2. Solving problems takes more time as compared to Procedure Oriented
Programming.
Question 5

How is Encapsulation useful in Object Oriented Programming? Explain

Encapsulation restricts the free flow of data from one object to another. The data and
functions are wrapped together in an object in such a way that the data of a particular
object can only be used in associated functions. Thus, Encapsulation helps in protecting
the data from unauthorised access.

Question 6

What are the advantages of High Level languages?

1. High Level languages are machine independent.


2. High Level languages are human readable as instructions are written using
English like words and phrases.
3. It is easier to understand and develop the program logic in High Level
languages.
4. The error detection and correction is easier.

Chapter 1 - Unit 2

Introduction to Java
Class 9 - APC Understanding Computer
Applications with BlueJ

Write True or False

Question 1

Java application is a Java program which is developed by users.


True

Question 2

James Gosling developed Java programming language.


True

Question 3
Machine codes are expressed using alphanumeric characters.
False

Question 4

Byte code is the program in binary form.


True

Question 5

JVM is Java Visual Management.


False

Fill in the blanks with appropriate words

Question 1

Java is a case sensitive language.

Question 2

In Java, the package used to find power raised to any base is java.lang.

Clarification: Math class inside java.lang package contains Math.pow that is used to find
power raised to any base. The official documentation is provided here.
It should not be confused with java.math package which contains BigDecimal, BigInteger
and MathContext classes.

Question 3

The words which are preserved with the system are called keywords/reserved words, that can
not be used as variable names in Java programming.

Question 4

A single line comment is represented by the symbol // in Java programming.

Question 5

BlueJ is a window based platform to operate Java program.


Answer the following questions

Question 1

Who developed Java? What was it initially called?

James Gosling developed Java programming language. It was initially called Oak.

Question 2

Give a brief historical development of Java.

In 1991, at Sun Microsystems, Green team led by James Gosling started working on a
new technology for consumer electronic devices. Over the next 18 months, in 1992 the
team created a new programming language which they called “Oak”. By 1994 the team
refocussed their efforts towards internet programming with Oak as it didn't find much
traction in consumer electronics space. Oak was renamed to Java and on 23rd of May
1995, Sun microsystems made its first public release.

Question 3

Mention at least four features of Java.

Four features of Java are:

1. It is an Object Oriented Programming Language.


2. It is platform independent. It provides us Write Once, Run Anywhere (WORA) feature.
3. It uses a compiler as well as an interpreter.
4. It is case sensitive.

Question 4

Define the following:

(a) A compiler

A compiler is a program that translates a source program written in some high-level


programming language into a target program in another low-level programming
language without changing the meaning of the program. The compiler processes the
complete source program at once and if there are compilation errors, they are all
reported together at once.

(b) An interpreter

An interpreter is a program that reads a source program line by line, converts each line
into its equivalent machine code and executes it. As it reads the program line by line so
the errors are reported one by one.

(c) Byte code


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

Question 5

What is Java Virtual Machine (JVM)?

Java Virtual Machine (JVM) is a software that takes Bytecode as input, converts it into
Machine code of the specific platform it is running on and executes it. JVM is platform
specific, each platform has its own JVM.

Question 6

Name three packages of Java Class Library.

Three packages of Java Class Library are:

1. java.lang
2. java.io
3. java.util

Question 7

What are Java reserved words? Name any five.

In Java, a reserved word is a word that has a predefined meaning in the language. Due
to this, reserved words can’t be used as names for variables, methods, classes or any
other identifier. Reserved words are also known as keywords. Five commonly used Java
reserved words are:

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

Question 8

Distinguish between:

(a) Source code and Object code


Source code Object code

It is a set of statements in a High-Level programming It is a set of statements in Machine


language. Language.

It is understood by human/programmer. It is understood by the processor.

(b) Compiler and Interpreter

Compiler Interpreter

It translates the whole source program into target It translates the source program into target
program at once. program one line at a time.

All the errors found during compilation are Errors are displayed line by line as each line is
displayed together at once. translated and executed.

(c) JDK 1.3 and BlueJ

JDK 1.3 BlueJ

JDK or Java Development Kit is the set of tools BlueJ is an IDE or Integrated Development
required to compile and run Java programs Environment for developing Java programs.

JDK includes tools like Compiler, Interpreter, Java BlueJ provides tools like Code Editor, Debugger,
libraries, etc. Syntax Highlighting, etc.

IDE isn't essential for developing Java programs but


JDK is essential for developing Java programs.
it makes the process easier and efficient.

Question 9

A compiler is specific to a language. Give your comments.

A compiler translates a source program written in some high-level programming


language into a target program in another low-level programming language. As low-
level programming languages are platform specific hence a compiler is specific to a
language.

Question 10

What is the basic format of a Java Program? Explain with an example.

The basic format of a Java program with example is explained here.

Question 11

What is BlueJ?

BlueJ is an integrated development environment for Java. It was created for teaching
Object Oriented programming to computer science students.

Question 12

Mention five features of BlueJ.

Five features of BlueJ are:

1. Simple beginner friendly graphical user interface.


2. It allows creating objects of the class dynamically, invoking their methods and also
supplying data to the method arguments if present.
3. It supports syntax highlighting. (Syntax highlighting means showing the different tokens of
the program like keywords, variables, separators, etc. in different colours so that they
show up more clearly.)
4. It facilitates easier debugging as lines causing compilation errors are marked clearly and
the error is displayed at the bottom of the window.
5. It provides a code editor, compiler and debugger integrated into a single tool.

Question 13

Name a package that is invoked by default.

java.lang

Question 14

What are the points to be taken care while naming a class in a Java program?

A class name should be a valid Java identifier i.e. it should follow the below three rules:

1. Name of the class should be a sequence of alphabets, digits, underscore and dollar sign
characters only.
2. It should not start with a digit.
3. It should not be a keyword or a boolean or null literal.

Question 15

Java is a case sensitive. Explain.

Java is case sensitive means that it distinguishes between upper case and lower case
characters. Consider the below code snippet:

int studentMarks;
StudentMarks = 85;
This will give a compilation error as Java will treat studentMarks and StudentMarks as
two different variables because the case of the characters is not same in both.

Question 16

The main function in a Java program is declared as:


public static void main (String args[])
What is the significance of the words public, static and void?
public — The public keyword is an access specifier. It controls the visibility of class
members. We can access public class members outside the class where we declare them.
We need to make the main method public because it will be called by code outside of its
class when the program is started.

static — When we declare a method inside a class as static, we can call it without
creating the object of that class. We need to make the main method static because Java
Virtual Machine (JVM) will call it to start the program even before any objects of the
class are created.

void — The void keyword tells the compiler that the main method will not return any
value.

Question 17

What does the term 'Compilation' mean?

The process of converting a source program written in some high-level programming


language into a target program in another low-level programming language without
changing the meaning of the program is called Compilation.

Question 18

Java program uses compiler as well as interpreter. Explain.


Java compiler compiles Java source code to Bytecode. Bytecode cannot run on the
processor directly as processor only understands Machine Code. Java Virtual Machine
(JVM) takes this Bytecode as input and converts it into Machine Code line by line. So,
JVM acts as an interpreter for converting Bytecode 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 19

Design a program in Java to display the following information on the output screen:
Name:
Class:
Roll No.:
Subject:
School:

Answer

class StudentInfo {
public static void main(String args[]) {
System.out.println("Name: Akshay Anand");
System.out.println("Class: 10");
System.out.println("Roll No.: 5");
System.out.println("Subject: Computer Applications");
System.out.println("School: KnowledgeBoat");
}
}

Question 20
You want to display your bio-data on the output screen. Write a program in Java to perform
the task in the given format:
Name:
Father's Name:
Date of birth:
Blood Group:
Aadhar Card No.:
State:

Answer

class BioData {
public static void main(String args[]) {
System.out.println("Name: Shweta Nayak");
System.out.println("Father's Name: Arvind Nayak");
System.out.println("Date of birth: 12/12/2005");
System.out.println("Blood Group: O+");
System.out.println("Aadhar Card No.: 4321 8756 9978");
System.out.println("State: Karnataka");
}
}
Chapter 2

Elementary Concept of Object and


Classes
Class 9 - APC Understanding Computer
Applications with BlueJ

Fill in the blanks

Question 1

A Class is also considered as an object factory.

Question 2

The Object of a class differs on various characteristics.

Question 3

The object of a class is represented through the attributes.

Question 4

The term instantiation is used for creating various objects.

Question 5

Class is a blueprint of the objects.

Question 6

new keyword indicates an operator for dynamic allocation of an object.

Question 7

Objects are also termed as class tags or entities.

Question 8

Different objects of a class have common behaviour.


Answer the following questions

Question 1

Define Object with an example.

Answer

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


behavior. Taking a car as an example of an object, it has characteristics like colour,
model, version, registration number, etc. It has behaviours like start the engine, stop the
engine, accelerate the car, apply the brakes, etc.

Question 2

Mention five states (characteristics) and two methods for the following Classes:

(a) Class Employee

Answer

Characteristics Methods

Name computeSalary()

Employee Number computeTax()

Pan Number

Salary

Income Tax
(b) Class Bank

Answer

Characteristics Methods

Bank Name openAccount()

Bank Address depositMoney()

IFSC Code

MICR Code

Accounts

(c) Class School

Answer

Characteristics Methods

School Name admitStudent()

School Address conductExams()

Classes

Students

Teachers

(d) Class Book

Answer

Characteristics Methods

Book Name buyBook()


Characteristics Methods

ISBN Number readBook()

Price

Author

Publisher

(e) Class Park

Answer

Characteristics Methods

Park Name openPark()

Park Address closePark()

Ticket Price

Opening Time

Closing Time

(f) Class Medicine

Answer

Characteristics Methods

Name buyMedicine()

Quantity sellMedicine()

Manufacturing Date

Expiry Date
Characteristics Methods

Price

(g) Class Computer

Answer

Characteristics Methods

Model startComputer()

Serial Number shutdownComputer()

Processor

RAM

Hard Disk

(h) Class Camera

Answer

Characteristics Methods

Model takePicture()

Serial Number adjustZoom()

Colour

Price

Resolution

Question 3

What is an Object? Give five examples of real world objects.


Answer

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


behavior. Examples — car, bottle, mobile phone, computer, student.

Question 4

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 5

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 6

A class is also referred 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 can create objects of itself with different characteristics and common behaviour
just like a factory can produce similar items based on a particular design. Hence, class
is also referred to as 'Object Factory'.

Question 7

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 8

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

Answer

A class can create objects of itself with different characteristics and common behaviour.
So, we can say that an Object represents a specific state of the class. For these reasons,
an Object is called an Instance of a Class.

Question 9

Why is a class known as composite data type?

Answer

A class can contain data members of various primitive and reference data types. Hence,
class is known as composite data type.

Question 10

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

Answer

Computer Keyboard = new Computer();

Question 11

Consider a real world object as 'Cricket Ball'. Now, mention two behaviours and methods
each by taking the 'Cricket Ball' as a software Object.

Answer

Characteristics — Colour, Condition


Behaviours/Methods — throw(), stop()

Question 12

Refer a class structure as shown below:


class MySchool {
Name
Address
Principal's name
AcceptData();
PrintData();
}

With reference to the above class declaration, indicate whether the following statements are
True/False:

1. Acceptdata( ) is the characteristic of the class.


False

2. Address is behaviour of the class.


False

3. Acceptdata( ) and PrintData( ) are the common behaviour of the objects of class
'MySchool'.
True

4. Behaviours are the medium of inter-object communication.


True

5. Creating multiple objects of class 'MySchool' is not possible.


False

Question 13

You want to create a class 'Football'. Choose the elements to be used as characteristics and
behavior from the list given below:
Ball, Goalkeeper, Making a goal, Defender, Forward player, passing ball, Referee, hitting
corner, making fault

Answer

Characteristics Behaviours

Ball Making a goal

Goalkeeper passing ball

Defender hitting corner

Forward player making fault


Characteristics Behaviours

Referee

Question 14

Write a program by using a class 'Picnic' without any data members but having only functions
as per the specifications given below:
class name : Picnic
void display1( ): To print venue, place and reporting time.
void display2( ): To print number of students, name of the teacher accompanying and bus
number.
Write a main class to create an object of the class 'Picnic' and call the functions display1()
and display2( ).

Answer

class Picnic
{
public void display1() {
System.out.println("Venue: Botanical Garden");
System.out.println("Place: MG Road");
System.out.println("Reporting Time: 9:00 AM");
}

public void display2() {


System.out.println("Number of Students: 50");
System.out.println("Name of teacher: Mr. Nagabhushan");
System.out.println("Bus Number: KA 01 1234");
}

public static void main(String args[]) {


Picnic obj = new Picnic();
obj.display1();
obj.display2();
}
}
Chapter 3

Values and Data Types


Class 9 - APC Understanding Computer
Applications with BlueJ

Multiple Choice Questions

Question 1

A constant which gives the exact representation of data is called

1. Variable
2. Literal ✓
3. Identifier
4. Character

Question 2

A word used in a high level language which has a special meaning attached to it is called

1. Class
2. Identifier
3. Keyword ✓
4. Literal

Question 3

A character literal is assigned to a:

1. Char variable ✓
2. Char type literal
3. String variable
4. String literal
Question 4

A character literal is enclosed in:

1. ''✓
2. ""
3. ::
4. {}

Question 5

A set of characters is assigned to:

1. String variable ✓
2. Static variable
3. Boolean variable
4. None

Question 6

The ASCII codes of upper case alphabets range from:

1. 65 - 90 ✓
2. 60 - 85
3. 65 - 91
4. 97 - 122

Question 7

Which of the following results in integer type?

1. 11.4F/3.2D
2. 13.8F/4.6F;
3. 12/3 ✓
4. none

Question 8

Which of the following is non-primitive data?

1. char
2. long
3. object ✓
4. short
Question 9

Which of the following type is an exact representation of fractional values?

1. char
2. double ✓
3. byte
4. String

Question 10

Boolean Data is used to test a particular condition i.e. true or false. Which of the following is
a correct representation?

1. boolean m=true ✓
2. boolean m='true'
3. boolean m="true"
4. none

Fill in the blanks

Question 1

The character sets of Java is like alphabets of English language.

Question 2

A standard encoding system way of representing characters is Unicode.

Question 3

ASCII code is decimal number to represent a character.

Question 4

Each individual component of a Java statement is known as token.

Question 5

In Java, the constants are also called literals.

Question 6

Assignment operator is used to store a value in the variable.


Question 7

The comma, exclamation, question mark etc., are termed as Tokens in Java language.

Question 8

An element of Java program that is used to identify a class, function or value is called
as identifier.

Question 9

Integer type value occupies 4 bytes in the memory.

Question 10

A Java expression that contains all the elements of same data type is pure expression.

Write short answers

Question 1

What do you mean by data type?

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

Question 2

Define variable with an example.

A variable represents a memory location through a symbolic name which holds a


known or unknown value of a particular data type. This name of the variable is used in
the program to refer to the stored value.
Example:
int mathScore = 95;

Question 3

What do you mean by constant? Explain with an example.

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;
Question 4

State two kinds of data types.

Two kinds of data types are:

1. Primitive Datatypes.
2. Non-Primitive Datatypes.

Question 5

What do you understand by Token? Name different types of tokens.

A token is the smallest element of a program that is meaningful to the compiler. The
different types of tokens in Java are:

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

Question 6

What are the rules to assign a variable in a Java programming?

1. Name of the variable should be a sequence of alphabets, digits, underscore and dollar sign
characters only.
2. It should not start with a digit.
3. It should not be a keyword or a boolean or null literal.

Question 7

Explain the term 'type casting'?

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

Question 8

Perform the following:

(a) Assign the value of pie (3.142) to a variable with the requisite data type.

double pi = 3.142;

(b) Assign the value of (1.732) to a variable with the requisite data type.

double x = 1.732;
Question 9

Distinguish between:

(a) Integer and floating constant

Integer Constant Floating Constant

Integer Constants represent whole number values Floating Constants represent fractional numbers
like 2, -16, 18246, 24041973, etc. like 3.14159, -14.08, 42.0, 675.238, etc.

Integer Constants are assigned to variables of Floating Constants are assigned to variables of data
data type — byte, short, int, long, char type — float, double

(b) Token and Identifier

Token Identifier

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

Tokens in Java are categorised into 5 types —


Keywords, Identifiers, Literals, Punctuators, Identifier is a type of token in Java.
Operators.

(c) Character and String constant

Character Constant String Constant

Character Constants are written by enclosing a String Constants are written by enclosing a set of
character within a pair of single quotes. characters within a pair of double quotes.

Character Constants are assigned to variables of String Constants are assigned to variables of type
type char. String.
(d) 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
boolean values represented by the words true
character within a pair of single quotes.
or false.

Character literals can be assigned to variables of


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

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

Question 10

Write down the data type of the following:

(a) Integer
int

(b) Long Integer


long

(c) A fractional number


double

(d) A special character


char

Question 11

What do you understand by Boolean type data? Explain with an example.

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;
Question 12

What do you understand by primitive data type? Give two examples.

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,
boolean.

Question 13

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

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

Question 14

Define the following with an example each:

(a) Implicit type conversion

In implicit type 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. Example:

int a = 10;
float b = 25.5f, c;
c = a + b;
(b) Explicit type conversion

In 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 15

Define 'Coercion' with reference to type conversion.

In a mixed-mode expression, the process of promoting a data type into its higher most
data type available in the expression without any intervention by the user is known as
Coercion.
Example:

byte b = 42;
int i = 50000;
double result = b + i;
Question 16

What do you mean by type conversion? How is implicit conversion different from explicit
conversion?

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 17

In what way is static declaration different from dynamic declaration?

In static declaration, 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 declaration, the initial value of the variable is the result of an expression or
the return value of a method call. Dynamic declaration 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 18

What do you mean by non-primitive data type? Give examples.

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 19

Predict the return data type of the following:

(i)

int p; double q;
r = p+q;
System.out.println(r);

Answer

Return data type is double.

(ii)

float m;
p = m/3*(Math.pow(4,3));
System.out.println(p);

Answer

Return data type is double.

Question 20

What are the resultant data types if the following implicit conversions are performed? Show
the result with flow lines.
int i; float f; double d; char c; byte b;
(a) i + c/b;

Answer

i + c/b;
⇒ int + char / byte
⇒ int + char
⇒ int

(b) f/d + c*f;

Answer

f/d + c*f;
⇒ float / double + char * float
⇒ double + float
⇒ double

(c) i + f - b*c;
Answer

i + f - b*c;
⇒ int + float - byte * char
⇒ int + float - char
⇒ float - char
⇒ float

(d) (f/i)*c + b;

Answer

(f/i)*c + b;
⇒ (float / int) * char + byte
⇒ float * char + byte
⇒ float + byte
⇒ float

(e) i + f- c + b/d;

Answer

i + f- c + b/d;
⇒ int + float - char + byte / double
⇒ int + float - char + double
⇒ float - char + double
⇒ float + double
⇒ double

(f) i/c + f/b;

Answer

i/c + f/b
⇒ int / char + float / byte
⇒ int + float
⇒ float
Chapter 4

Operators in Java
Class 9 - APC Understanding Computer
Applications with BlueJ

Multiple Choice Questions

Question 1

The statement n += 4 is equivalent to:

1. ++n
2. n=n+4 ✓
3. n+1
4. none

Question 2

What will be the output of a & b in the following, if int a, b; a=10; b=a++;

1. 10,10
2. 10,11
3. 11,10 ✓
4. 11,11

Question 3

What will be the output of a++ when int a = -1;

1. 1
2. -1
3. 0 ✓
4. none
Question 4

If int a = 25, b = 5, c = 0; what value is stored in c? When c = a % b;

1. 5.0
2. 5
3. 0 ✓
4. none

Question 5

What is the result of the following in Java statement?

int m=8;
m*=8;
System.out.println("The output =" + m);

1. 8
2. 64 ✓
3. 16
4. 88

Question 6

double c;
int x, y, z;
x = 5; y = 10; z = 11;
c = x*y+z/2;
The value stored in c is:

1. 55.0 ✓
2. 55.5
3. 55
4. none

Explanation

c=x*y+z/2
⇒ c = 5 * 10 + 11 / 2
⇒ c = 5 * 10 + 5
⇒ c = 50 + 5
⇒ c = 55.0
Question 7

int m, p;
m = 5;
p = 0;
p = m-- + --m;
The output will be:

1. 11
2. 10
3. 8 ✓
4. 12

Explanation

p = m-- + --m;
⇒p=5+3
⇒p=8

Question 8

int a=7, p=0, q=0;


p= ++a + --a;
q -= p;
The output of q will be:

1. 13
2. 14
3. 15
4. -15 ✓

Explanation

p = ++a + --a
⇒p=8+7
⇒ p = 15

q -= p
⇒q=q-p
⇒ q = 0 - 15
⇒ q = -15
Write the Java expressions for the following:

Question 1

p = a2 + bc

Answer

p=a*a+b*c

Question 2

m = a2 - b2 / (ab)

Answer

m = (a * a - b * b) / (a * b)

Question 3

s = ut + (1/2)at2

Answer

s = u * t + (1.0 / 2) * a * t * t

Question 4

f = uv / (u + v)

Answer

f = u * v / (u + v)

Question 5

(a + b)2 + b

Answer

(a + b) * (a + b) + b
Question 6

y = 2(lb + bh + lh)

Answer

y = 2 * (l * b + b * h + l * h)

Question 7

a2 + b2

Answer

a*a+b*b

Question 8

z = x3 + y3 - xy / 3

Answer

z=x*x*x+y*y*y-x*y/3

Answer the following questions

Question 1

What is an operator?

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


programming.

Question 2

Name the different types of operators.

The different types of operators are Arithmetical, Logical and Relational.


Question 3

Explain the following:

(a) Arithmetical operator


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


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


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) Unary operator


Operators that act on one operand are called as Unary operators. Unary +, unary -, ++,
--, etc. are some unary operators in Java.

(e) New operator


new operator is used to instantiate an object by dynamically allocating memory for it.

(f) Binary operator


Operators that act on two operands are called as Binary operators.
Question 4

What is a Ternary operator? Explain with the help of an example.


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 5

Differentiate between the following:

(a) Arithmetical operator and Logical operator

Arithmetical Operator Logical Operator

Logical operators operate on boolean expressions to


Arithmetic operators are used to
combine the results of these boolean expression into a
perform mathematical operations.
single boolean value.

+, -, *, /, etc. are a few examples of


&&, ||, ! are a few examples of Logical Operators
Arithmetic operators.

(b) Binary operator and Ternary operator

Binary operator Ternary operator

Binary operators work on two operands. Ternary operator work on three operands.

+, -, *, /, etc. are a few examples of Binary The conditional operator ? : is a Ternary


operators. operator.
(c) Logical AND (&&) and Logical OR(||)

Logical AND (&&) Logical OR(||)

It evaluates to true only if both of its It evaluates to true if one or both of its
operands are true. operands are true.

Example: Example:
int a = 8, b = 13, c = 0; int a = 8, b = 13, c = 0;
if (a > 10 && b > 10) if (a > 10 || b > 10)
c = 10; c = 10;
else else
c = 5; c = 5;
Here, value of c will be 5 as one of the Here, value of c will be 10 as at least one of the
operands is false. operands is true.

(d) Prefix operator and Postfix operator

Prefix Operator Postfix Operator

It works on the principle of CHANGE-THEN-


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

It is written before the operand. It is written after the operand.

Example: Example:
int a = 99; int a = 99;
int b = ++a; int b = a++;
After the execution of these two After the execution of these two statements, a will
statements, both a and b will have the have the value of 100 and b will have the value of
value of 100. 99.
(e) System.out.print( ) and System.out.println( )

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

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

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

Question 6

Differentiate between an operator and an expression.

An operator is a symbol or sign used to specify an operation to be performed whereas


an expression is a set of variables, constants and operators i.e. an expression is a
combination of operators and operands.

Question 7

If m=5 and n=2 then what will be the output of m and n after execution that will store in (a)
& (b)?

(a) m -= n;

Answer

m -= n
⇒m=m-n
⇒m=5-2
⇒m=3

(b) n = m + m/n;

Answer

n = m + m/n
⇒n=5+5/2
⇒n=5+2
⇒n=7
Question 8

State the difference between = and ==.

= ==

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

E.g. if (a == 10) checks if variable a is equal to 10 or


E.g. int a = 10; assigns 10 to variable a.
not.

Question 9

What will be the output for the following program segment?

int a=0,b=10,c=40;
a = --b + c++ +b;
System.out.println(" a = " + a);

Output

a = 58

Explanation

a = --b + c++ + b
⇒ a = 9 + 40 + 9
⇒ a = 58

Question 10

What will be the output of the following?


if x =5

(a) 5* ++x;

Answer

5 * ++x
⇒5*6
⇒ 30
(b) 5* x++;

Answer

5 * x++
⇒5*5
⇒ 25

Question 11

Evaluate the following expressions, if the values of the variables are:


a = 2, b = 3, and c = 9

(a) a - (b++) * (--c);

Answer

a - (b++) * (--c)
⇒2-3*8
⇒2-3*8
⇒ 2 - 24
⇒ -22

(b) a * (++b) % c;

Answer

a * (++b) % c
⇒ a * (++b) % c
⇒ 2 * (4) % 9
⇒8%9
⇒8

Question 12

If a = 5, b = 9, calculate the value of:


a += a++ - ++b + a;

Answer

a += a++ - ++b + a
⇒ a = a + (a++ - ++b + a)
⇒ a = 5 + (5 - 10 + 6)
⇒a=5+1
⇒a=6
Question 13

Give the output of the program snippet.

int a = 10, b =12;


if(a>=10)
a++;
else
++b;
System.out.println(" a = " + a + " and b = " +b);

Output

a = 11 and b = 12

Explanation

The condition if(a>=10) is true so a++ increments a to 11. b remains the same.

Question 14

Rewrite the following using ternary operator.

if(income<=100000)
tax = 0;
else
tax = (0.1*income);

Answer

tax = income <= 100000 ? 0 : (0.1*income);

Question 15

Rewrite the following using ternary operator.

if(p>5000)
d = p*5/100;
else
d = 2*p/100;

Answer

d = p > 5000 ? p * 5 / 100 : 2 * p / 100;


Solutions to Unsolved Java Programs

Question 1

Write a program to find and display the value of the given expressions:

(a) (x + 3) / 6 - (2x + 5) / 3; taking the value of x = 5

public class KboatExpression


{
public static void main(String args[]) {
int x = 5;
double value = ((x + 3) / 6.0) - ((2 * x + 5) / 3.0);
System.out.println("Result = " + value);
}
}

Output

(b) a2 + b2 + c2 / abc; taking the values a=5,b=4,c=3

public class KboatExpression


{
public static void main(String args[]) {
int a = 5, b = 4, c = 3;
double value = (a * a + b * b + c * c) / (double)(a * b *
c);
System.out.println("Result = " + value);
}
}

Output
Question 2

A person is paid ₹350 for each day he works and fined ₹30 for each day he remains absent.
Write a program to calculate and display his monthly income, if he is present for 25 days and
remains absent for 5 days.

public class KboatSalary


{
public static void main(String args[]) {
int salary = 25 * 350;
int fine = 5 * 30;
int netSalary = salary - fine;
System.out.println("Monthly Income = " + netSalary);
}
}

Output

Question 3

In a competitive examination, there were 150 questions. One candidate got 80% correct and
the other candidate 72% correct. Write a program to calculate and display the correct answers
each candidate got.

public class KboatCompetitiveExam


{
public static void main(String args[]) {
int totalQuestions = 150;
int c1 = (int)(80 / 100.0 * totalQuestions);
int c2 = (int)(72 / 100.0 * totalQuestions);
System.out.println("Correct Answers of Candidate 1 = " +
c1);
System.out.println("Correct Answers of Candidate 2 = " +
c2);
}
}

Output
Question 4

Write a program to find and display the percentage difference, when:

(a) a number is updated from 80 to 90

public class KboatPercentIncrease


{
public static void main(String args[]) {
int orgNum = 80;
int newNum = 90;
int inc = newNum - orgNum;
double p = inc / (double)orgNum * 100;
System.out.println("Percentage Difference = " + p + "%");
}
}

Output

(b) a number is updated from 7.5 to 7.2

public class KboatPercentIncrease


{
public static void main(String args[]) {
double orgNum = 7.5;
double newNum = 7.2;
double inc = newNum - orgNum;
double p = inc / orgNum * 100;
System.out.println("Percentage Difference = " + p + "%");
}
}

Output
Question 5

The normal temperature of human body is 98.6°F. Write a program to convert the
temperature into degree Celsius and display the output.
Hint: c / 5 = f - 32 / 9

public class KboatCelsius


{
public static void main(String args[]) {
double f = 98.6;
double c = 5 * (f - 32) / 9.0;
System.out.println("Temperature in Degree Celsius = " + c);
}
}

Output

Question 6

The angles of a quadrilateral are in the ratio 3:4:5:6. Write a program to find and display all
of its angles. [Hint: The sum of angles of a quadrilateral = 360°]

public class KboatQuadRatio


{
public static void main(String args[]) {
int r1 = 3, r2 = 4, r3 = 5, r4 = 6;
double x = 360 / (double)(r1 + r2 + r3 + r4);
double a = r1 * x;
double b = r2 * x;
double c = r3 * x;
double d = r4 * x;
System.out.println("Angle A = " + a);
System.out.println("Angle B = " + b);
System.out.println("Angle C = " + c);
System.out.println("Angle D = " + d);
}
}

Output
Chapter 5

Input In Java
Class 9 - APC Understanding Computer
Applications with BlueJ

Name the following

Question 1

a package needed to import scanner class


java.util

Question 2

a method that accepts a character through scanner object


charAt()

Question 3

a package needed to import Stream Reader Class


java.io

Question 4

a method to accept an exponential value through scanner object


nextDouble()

Question 5

a method that accepts an integer token through scanner object


nextInt()
Write down the syntax with reference to Java
Programming

Question 1

to accept an integral value 'p' through Stream Class

InputStreamReader read = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(read);
int p = Integer.parseInt(in.readLine());

Question 2

to accept a fractional value (float) 'm' through Scanner Class

Scanner in = new Scanner(System.in);


float m = in.nextFloat();

Question 3

to accept a character 'd' through Stream Class

InputStreamReader read = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(read);
char d = (char)in.read();

Question 4

to accept a fraction value 'n' in double data type through Stream Class

InputStreamReader read = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(read);
double n = Double.parseDouble(in.readLine());

Question 5

to accept a word 'wd' through Stream Class

InputStreamReader read = new InputStreamReader(System.in);


BufferedReader in = new BufferedReader(read);
String wd = in.readLine();

Question 6

to create a scanner object

Scanner in = new Scanner(System.in);


Differentiate between the following

Question 1

nextInt( ) and nextFloat( ) methods

nextInt( ) nextFloat( )

Scans the next token of input as an int Scans the next token of input as a float

Question 2

Syntax and logical errors

Syntax Errors Logical Errors

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

Program compiles and executes but doesn't


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

Logic errors need to be found and corrected


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

Answer the following

Question 1

What do you mean by scanner class?


Scanner class is used to get user input. It is present in java.util package.

Question 2

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


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 3

What is the use of the keyword import?


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

Question 4

What is a package? Give an example.


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.
java.util, java.lang are a couple of examples of built-in packages.

Question 5

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


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

Question 6

What is a compound statement? Give an example.


Two or more statements can be grouped together by enclosing them between opening
and closing curly braces. Such a group of statements is called a compound statement.

if (a < b) {

/*
* All statements within this set of braces
* form the compound statement
*/

System.out.println("a is less than b");


a = 10;
b = 20;
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);

}
Question 7

Write down the syntax to input a character through scanner class with an example.

Syntax:

char <variable name> = <Scanner Object>.next().charAt(0);


Example:

Scanner in = new Scanner(System.in);


char ch = in.next().charAt(0);

Question 8

What do you understand by 'Run Time' error? Explain with an example


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 Run Time 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 9

What are the different types of errors that take place during the execution of a program?
Logical errors and Run-Time errors occur during the execution of the program.
Question 10

Distinguish between:
(a) Testing and Debugging

Testing Debugging

In the process of Testing, we check if the program is In the process of Debugging, we correct
working as expected and find out the errors if it is not the errors that were found during
giving the expected output. testing.

(b) Syntax error and Logical error

Syntax Error Logical Error

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

Program compiles and executes but doesn't


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

Logical errors need to be found and


Syntax Errors are caught by the compiler. corrected by people working on the
program.
Solutions to Unsolved Java Programs

Question 1

The time period of a Simple Pendulum is given by the formula:

T = 2π√(l/g)

Write a program to calculate the time period of a Simple Pendulum by taking length and
acceleration due to gravity (g) as inputs.

import java.util.Scanner;

public class KboatSimplePendulum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter length: ");
double l = in.nextDouble();
System.out.print("Enter g: ");
double g = in.nextDouble();
double t = 2 * (22.0 / 7.0) * Math.sqrt(l/g);
System.out.println("T = " + t);
}
}

Output
Question 2

Write a program by using class 'Employee' to accept Basic Pay of an employee. Calculate the
allowances/deductions as given below.

Allowance / Deduction Rate

Dearness Allowance (DA) 30% of Basic Pay

House Rent Allowance (HRA) 15% of Basic Pay

Provident Fund (PF) 12.5% of Basic Pay

Finally, find and print the Gross and Net pay.


Gross Pay = Basic Pay + Dearness Allowance + House Rent Allowance
Net Pay = Gross Pay - Provident Fund

import java.util.Scanner;

public class Employee


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Basic Pay: ");
double bp = in.nextDouble();
double da = 0.3 * bp;
double hra = 0.15 * bp;
double pf = 0.125 * bp;
double gp = bp + da + hra;
double np = gp - pf;
System.out.println("Gross Pay = " + gp);
System.out.println("Net Pay = " + np);
}
}

Output
Question 3

A shopkeeper offers 10% discount on the printed price of a Digital Camera. However, a
customer has to pay 6% 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 KboatCameraPrice


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter printed price of Digital
Camera:");
double mrp = in.nextDouble();
double disc = mrp * 10 / 100.0;
double price = mrp - disc;
double gst = price * 6 / 100.0;
price += gst;
System.out.println("Amount to be paid: " + price);
}
}

Output

Question 4

A shopkeeper offers 30% discount on purchasing articles whereas the other shopkeeper offers
two successive discounts 20% and 10% for purchasing the same articles. Write a program in
Java to compute and display the discounts.
Take the price of an article as the input.

import java.util.Scanner;

public class KboatDiscounts


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter price of article: ");
double price = in.nextDouble();

double d1 = price * 30 / 100.0;


double amt1 = price - d1;
System.out.println("30% discount = " + d1);
System.out.println("Amount after 30% discount = " + amt1);

double d2 = price * 20 / 100.0;


double amt2 = price - d2;
double d3 = amt2 * 10 / 100.0;
amt2 -= d3;
System.out.println("20% discount = " + d2);
System.out.println("10% discount = " + d3);
System.out.println("Amount after successive discounts = " +
amt2);
}
}

Output

Question 5

Mr. Agarwal invests certain sum at 5% per annum compound interest for three years. Write a
program in Java to calculate:

(a) the interest for the first year


(b) the interest for the second year
(c) the amount after three years.

Take sum as an input from the user.


Sample Input: Principal = ₹5000, Rate =10%, Time = 3 yrs
Sample Output: Interest for the first year: ₹500
Interest for the second year: ₹550
Interest for the third year: ₹605

import java.util.Scanner;

public class KboatCompoundInterest


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter sum of money: ");
double p = in.nextDouble();
double interest = p * 5 * 1 / 100.0;
System.out.println("Interest for the first year = " +
interest);
p += interest;
interest = p * 5 * 1 / 100.0;
System.out.println("Interest for the second year = " +
interest);
p += interest;
interest = p * 5 * 1 / 100.0;
System.out.println("Interest for the third year = " +
interest);
}
}
Output

Question 6

A businessman wishes to accumulate 3000 shares of a company. However, he already has


some shares of that company valuing ₹10 (nominal value) which yield 10% dividend per
annum and receive ₹2000 as dividend at the end of the year. Write a program in Java to
calculate the number of shares he has and how many more shares to be purchased to make his
target.
Hint: No. of share = (Annual dividend * 100) / (Nominal value * div%)

public class KboatShares


{
public static void main(String args[]) {
int sharesHeld = (2000 * 100)/(10 * 10);
System.out.println("No. of shares held currently = "
+ sharesHeld);
int sharesRequired = 3000 - sharesHeld;
System.out.println("No. of shares to purchase = "
+ sharesRequired);
}
}

Output

Question 7

Write a program to input the 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 KboatTimeConvert


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter time in seconds: ");
long secs = in.nextLong();
long hrs = secs / 3600;
secs %= 3600;
long mins = secs / 60;
secs %= 60;
System.out.println(hrs + " Hours " + mins
+ " Minutes " + secs + " Seconds");
}
}

Output

Question 8

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 = 23, b = 56
Sample Output: a = 56, b = 23

import java.util.Scanner;

public class KboatNumberSwap


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter two unequal numbers");
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a + " b = " + b);
}
}

Output

Question 9

A certain amount is invested at the rate 10% per annum for 3 years. Find the difference
between Compound Interest (CI) and Simple Interest (SI). Write a program to take amount as
an input.
Hint: SI = (P * R * T) / 100
A = P * (1 + (R/100))T
CI = A - P

import java.util.Scanner;
public class KboatInterestDifference
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Amount: ");
double p = in.nextDouble();
double si = p * 10 * 3 / 100;
double ciAmt = p * Math.pow(1 + (10/100.0), 3);
double ci = ciAmt - p;
System.out.print("Difference between CI & SI: " + (ci -
si));
}
}

Output

Question 10

A shopkeeper sells two calculators for the same price. He earns 20% profit on one and suffers
a loss of 20% on the other. Write a program to find his total cost price of the calculators by
taking selling price as input.
Hint: CP = (SP / (1 + (profit / 100))) (when profit)
CP = (SP / (1 - (loss / 100))) (when loss)

import java.util.Scanner;

public class KboatShopkeeper


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the selling price: ");
double sp = in.nextDouble();
double cp1 = (sp / (1 + (20 / 100.0)));
double cp2 = (sp / (1 - (20 / 100.0)));
double totalCP = cp1 + cp2;
System.out.println("Total Cost Price = " + totalCP);
}
}

Output
Chapter 6

Mathematical Library Methods


Class 9 - APC Understanding Computer
Applications with BlueJ

Choose the correct answer

Question 1

Which of the following is false to find square of a number?

1. Math.pow(a,2)
2. a*a
3. Math.sqrt(a,2) ✓
4. All of the above

Question 2

What type of value is returned by Math.sqrt( )?

1. int
2. float
3. double ✓
4. All

Question 3

Which of the following syntax is true to find the square root of a number?

1. sqrt(a)
2. Math.sqrt(a) ✓
3. Squareroot(a)
4. None
Question 4

Name the class that is used for different Mathematical functions.

1. Java.Math ✓
2. Java.Power
3. Java.Sqrt
4. None

Question 5

Give the output of the Math.abs(x); when x = -9.99

1. -9.99
2. 9.99 ✓
3. 0.99
4. None

Question 6

Give the output of Math.sqrt(x); when x = 9.0

1. 3
2. 3.0 ✓
3. 3.00
4. all

Predict the output

Question 1

System.out.println(Math.sqrt(10.24));

Output

3.2

Explanation

Math.sqrt method gives the square root of a positive number. Square root of 10.24 is 3.2 so it
is the output.
Question 2

System.out.println(Math.rint(-99.4));

Output

-99.0

Explanation

Math.rint method rounds off its argument to the nearest mathematical integer and returns its
value as a double type. The nearest integer to -99.4 is -99.0 so that is the output. Math.rint
method behaves in a particular way at the mid-point i.e. when the decimal part of the
argument is 0.5. In such cases, the result is the integer value that is even. Let's understand this
with an example. Math.rint(1.5) and Math.rint(2.5) will both return 2.0. In the case of 1.5,
both 1.0 and 2.0 are equally close to 1.5. Math.rint choses the integer that is even so 2.0 is
returned. In the case of 2.5, both 2.0 and 3.0 are equally close to 2.5. Math.rint again choses
the integer that is even so 2.0 is returned.

Question 3

System.out.println(Math.cbrt(42.875));

Output

3.5

Explanation

Math.cbrt method returns the cube root of its argument as a double value. Cube root of
42.875 is 3.5 so it is the output.

Question 4

System.out.println(Math.min(-25.5, -12.5));

Output

-25.5

Explanation

Math.min method returns the smaller of its 2 arguments. As -25.5 is smaller than -12.5 so it is
the output.
Question 5

System.out.println(Math.ceil(-0.95));

Output

-0.0

Explanation

Math.ceil method returns the smallest double value that is greater than or equal to the
argument and is equal to a mathematical integer. If the argument value is less than zero but
greater than -1.0, then the result is negative zero which is the case in this question.

Question 6

System.out.println(Math.round(-18.51));

Output

-19

Explanation

Math.round method rounds off its argument to the nearest mathematical integer and returns
its value as an int or long type. At the mid-point i.e. when the decimal part of the argument is
0.5, Math.round method rounds up to the higher integer. In this case, the nearest integer to -
18.51 is -19 so it is the output.

Question 7

System.out.println(Math.max(-77.66, -87.45));

Output

-77.66

Explanation

Math.max method returns the greater of its 2 arguments. As -77.66 is greater than -87.45 so it
is the output.
Question 8

System.out.println(Math.floor(-0.88));

Output

-1.0

Explanation

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 -1.0 is the largest mathematical integer less than -
0.88 so it is the output.

Question 9

System.out.println(Math.rint(98.5));

Output

98.0

Explanation

Math.rint method rounds off its argument to the nearest mathematical integer and returns its
value as a double type. This method behaves in a particular way at the mid-point i.e. when the
decimal part of the argument is 0.5. In such cases, the result is the integer value that is even.
Let's understand this with an example. Math.rint(97.5) and Math.rint(98.5) will both return
98.0. In the case of 97.5, both 97.0 and 98.0 are equally close to 97.5. Math.rint choses the
integer that is even so 98.0 is returned. In the case of 98.5, both 98.0 and 99.0 are equally
close to 98.5. Math.rint again choses the integer that is even so 98.0 is returned.

Question 10

System.out.println(Math.ceil(65.5));

Output

66.0

Explanation

Math.ceil method returns the smallest double value that is greater than or equal to the
argument and is equal to a mathematical integer. Here 66.0 is the smallest mathematical
integer greater than 65.5 so it is the output.
Write down the syntax for the following functions

Question 1

To find the smaller between two numbers p and q

Answer

Math.min(p, q)

Question 2

To find the absolute value of a number m

Answer

Math.abs(m)

Question 3

To find the exponent of a number k

Answer

Math.exp(k)

Question 4

To find the square root of a number d

Answer

Math.sqrt(d)

Question 5

To find the rounded-off of a number b

Answer

Math.round(b)
Predict the return data type of the following functions

Question 1

Math.sqrt( );

Answer

double

Question 2

Math.rint( );

Answer

double

Question 3

Math.ceil( );

Answer

double

Question 4

Math.round( );

Answer

int or long

Question 5

Math.floor( );

Answer

double

Question 6

Math.log( )

Answer

double
Explain the following functions

Question 1

Math.random( )

Answer

Returns a positive double value, greater than or equal to 0.0 and less than 1.0.

Question 2

Math.max( )

Answer

Returns the greater of its 2 arguments. Its return type is same as the type of its
arguments.

Question 3

Math.cbrt( )

Answer

Returns the cube root of its argument as a double value.

Question 4

Math.abs( )

Answer

Returns the absolute value of its argument. Its return type is same as the type of its
arguments.

Question 5

Math.log( )

Answer

Returns the natural logarithm of its argument. Both return type and argument is of
double data type.
Distinguish between them with suitable examples

Question 1

Math.ceil( ) and Math.floor( )

Answer

Math.ceil( ) Math.floor( )

Returns the smallest double value that is greater Returns the largest double value that is less than or
than or equal to the argument and is equal to a 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 65.0
as it is the smallest integer greater than 65.5. as it is the largest integer smaller than 65.5.

Question 2

Math.rint( ) and Math.round( )

Answer

Math.rint( ) Math.round( )

Rounds off its argument to the nearest Rounds off its argument to the nearest mathematical integer and
mathematical integer and returns its returns its value as an int or long type. If argument is float, return
value as a double type. 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 in Java to input three numbers and display the greatest and the smallest of
the two numbers.
Hint: Use Math.min( ) and Math.max( )
Sample Input: 87, 65, 34
Sample Output: Greatest Number 87
Smallest number 34

import java.util.Scanner;

public class KboatGreatestNumber


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

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.print("Enter Third Number: ");
int c = in.nextInt();

int g = Math.max(a, b);


g = Math.max(g, c);

int s = Math.min(a, b);


s = Math.min(s, c);

System.out.println("Greatest Number = " + g);


System.out.println("Smallest Number = " + s);
}
}

Output

Question 2

Write a program in Java to calculate and display the hypotenuse of a Right-Angled Triangle
by taking perpendicular and base as inputs.
Hint: h = √p2 + b2

import java.util.Scanner;
public class KboatHypotenuse
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Perpendicular: ");
double p = in.nextDouble();
System.out.print("Enter Base: ");
double b = in.nextDouble();

double h = Math.sqrt(Math.pow(p, 2) + Math.pow(b, 2));

System.out.println("Hypotenuse = " + h);


}
}

Output

Question 3

Write a program to input a number and evaluate the results based on the number entered by
the user:
(a) Natural logarithm of the number
(b) Absolute value of the number
(c) Square root of the number
(d) Cube of the number
(e) Random numbers between 0 (zero) and 1 (one).

import java.util.Scanner;

public class KboatMathMethods


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Number: ");
double n = in.nextDouble();

System.out.println("Natural logarithm = " + Math.log(n));


System.out.println("Absolute value = " + Math.abs(n));
System.out.println("Square root = " + Math.sqrt(n));
System.out.println("Cube root= " + Math.cbrt(n));
System.out.println("Random number = " + Math.random());
}
}

Output
Question 4

In an examination, you have appeared for three subjects i.e. Physics, Chemistry and Biology.
Write a program in Java to calculate the average mark obtained and finally display the marks
in rounded-off form.
Take Physics, Chemistry. and Biology marks as inputs.

import java.util.Scanner;

public class KboatAvgMarks


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Marks");
System.out.print("Physics: ");
int p = in.nextInt();
System.out.print("Chemistry: ");
int c = in.nextInt();
System.out.print("Biology: ");
int b = in.nextInt();

double avg = (p + c + b) / 3.0;


long roundAvg = Math.round(avg);

System.out.println("Rounded Off Avg Marks = " + roundAvg);


}
}

Output
Question 5

You want to calculate the radius of a circle by using the formula:


Area = (22/7) * r2; where r = radius of a circle
Hence the radius can be calculated as:
r = √((7 * area) / 22)
Write a program in Java to calculate and display the radius of a circle by taking area as an
input.

import java.util.Scanner;

public class KboatCircleRadius


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Area of Circle: ");
double area = in.nextDouble();
double r = Math.sqrt(7 * area / 22);
System.out.print("Radius of Circle = " + r);
}
}

Output
Chapter 7

Conditional Statements In Java


Class 9 - APC Understanding Computer
Applications with BlueJ

Multiple Choice Questions

Question 1

In a switch case, when the switch value does not respond to any case then the execution
transfers to:

1. a break statement
2. a default case ✓
3. a loop
4. none

Question 2

Which of the following is a compound statement?

1. p=Integer.parseInt(in.readLine());
2. c=++a;
3. if(a>b) a++; b- - ; ✓
4. a=4;

Question 3

Condition is essentially formed by using:

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. All ✓
Question 4

If(a>b)&&(a>c)), then which of the statement is true?

1. b is the smallest number


2. b is the greatest number
3. a is the greatest number ✓
4. all of the above

Question 5

if(a>b)
c=a;
else
c=b;
It can be written as:

1. c= (b>a)?a:b;
2. c= (a!=b)?a:b;
3. c= (a>b)?b:a;
4. None ✓

Question 6

If a, b and c are the sides of a triangle then which of the following statement is true for:
if(a!=b && a!=c && b!=c)?

1. Equilateral triangle
2. Scalene triangle ✓
3. Isosceles triangle
4. All of the above

Question 7

Two arithmetic expressions can be compared with if statement, using:

1. Arithmetic operator
2. Relational operator ✓
3. Ternary operator
4. None
Question 8

Which of the following is a conditional statement?

1. if ✓
2. goto
3. for
4. none

Question 9

Which of the following statements accomplishes 'fall through'?

1. for statement
2. switch statement ✓
3. if-else
4. none

Question 10

A Java program executes but doesn't give the desired output. It is due to:

1. the logical error in the program ✓


2. the syntax error in the program
3. the run time error in the program
4. none

Answer the Following Questions

Question 1

Name the different ways to manage the flow of control in a program.

Answer

Normal flow of control, Bi-directional flow of control, Multiple branching of control

Question 2

Mention one statement each to achieve:

(a) Bi-directional flow of control

Answer

if-else statement
(b) Multiple branching of control

Answer

switch statement

Question 3

Explain the following statements with their constructs:

(a) nested if

Answer

We can write an if-else statement within another if-else statement. We call this nested if.
It has the following syntax:

if (condition 1) {
if (condition 2) {
Statement a;
Statement b;
..
}
else {
Statement c;
Statement d;
..
}
}
else {
if (condition 3) {
Statement e;
Statement f;
..
}
else {
Statement g;
Statement h;
..
}
}
(b) if - else

Answer

if - else statement is used to execute one set of statements when the condition is true and
another set of statements when the condition is false. It has the following syntax:

if (condition 1) {
Statement a;
Statement b;
..
}
else {
Statement c;
Statement d;
..
}
(c) if - else - if

Answer

if - else - if ladder construct is used to test multiple conditions and then take a decision.
It provides multiple branching of control. It has the following syntax:

if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
..
..
else
statement;

Question 4

Differentiate between if and switch statement.

Answer

Following are the difference between if and switch statement:

1. switch can only test for equality whereas if can test for any Boolean expression.
2. switch tests the same expression against constant values while if-else-if ladder can use
different expression involving unrelated variables.
3. switch expression must only evaluate to byte, short, int, char, String or an enum. if doesn’t
have such limitations.
4. A switch statement will run much faster than the equivalent program written using the if-
else-if ladder
Question 5

What is the purpose of switch statement in a program?

Answer

switch statement in a program, is used for multi-way branch. It compares its expression
to multiple case values for equality and executes the case whose value is equal to the
expression of switch. If none of the cases match, default case is executed. If default case
is absent then none of the statements from switch are executed.

Question 6

Explain with the help of an example, the purpose of default in a switch statement.

Answer

When none of the case values are equal to the expression of switch statement then
default case is executed. In the example below, value of number is 4 so case 0, case 1 and
case 2 are not equal to number. Hence sopln of default case will get executed printing
"Value of number is greater than two" to the console.

int number = 4;

switch(number) {

case 0:
System.out.println("Value of number is zero");
break;

case 1:
System.out.println("Value of number is one");
break;

case 2:
System.out.println("Value of number is two");
break;

default:
System.out.println("Value of number is greater than two");
break;

}
Question 7

Is it necessary to use 'break' statement in a switch case statement? Explain.

Answer

Use of break statement in a switch case statement is optional. Omitting break statement
will lead to fall through where program execution continues into the next case and
onwards till end of switch statement is reached.

Question 8

Explain 'Fall through' with reference to a switch case statement.

Answer

break statement at the end of case is optional. Omitting break leads to program
execution continuing into the next case and onwards till a break statement is
encountered or end of switch is reached. This is termed as Fall Through in switch case
statement.

Question 9

What is a compound statement? Give an example.

Answer

Two or more statements can be grouped together by enclosing them between opening
and closing curly braces. Such a group of statements is called a compound statement.

if (a < b) {

/*
* All statements within this set of braces
* form the compound statement
*/

System.out.println("a is less than b");


a = 10;
b = 20;
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);

}
Question 10

Explain with an example the if-else-if construct.

Answer

if - else - if ladder construct is used to test multiple conditions and then take a decision.
It provides multiple branching of control. Below is an example of if - else - if:

if (marks < 35)


System.out.println("Fail");
else if (marks < 60)
System.out.println("C grade");
else if (marks < 80)
System.out.println("B grade");
else if (marks < 95)
System.out.println("A grade");
else
System.out.println("A+ grade");

Question 11

Name two jump statements and their use.

Answer

break statement, it is used to jump out of a switch statement or a loop. continue


statement, it is used to skip the current iteration of the loop and start the next iteration.

Question 12

Give two differences between the switch statement and the if-else statement.

Answer

switch if-else

switch can only test if the expression is equal if-else can test for any boolean expression like less than,
to any of its case constants greater than, equal to, not equal to, etc.

It is a multiple branching flow of control


It is a bi-directional flow of control statement
statement
Predict the Output of the Given Snippet, when Executed

Question 1

int a=1,b=1,m=10,n=5;
if((a==1)&&(b==0))
{
System.out.println((m+n));
System.out.println((m—n));
}
if((a==1)&&(b==1))
{
System.out.println((m*n));
System. out.println((m%n));
}

Output

50

Explanation

First if condition is false, second if condition is true. Statements inside the code block of
second if condition are executed.
m*n => 10 * 5 => 50
m%n => 10 % 5 => 0

Question 2

int 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 (i) 1 (ii) 0?

Output

(i) n = 1

x = 2

y = 2
(ii) n = 0

x = 1

y = 1

Explanation

When n = 1, if condition is true, its code block is executed adding 1 to both x and y. When n
= 0, if condition is false so x and y retain their original values.

Question 3

int b=3,k,r;
float a=15.15,c=0;
if(k==1)
{
r=(int)a/b;
System.out.println(r);
}
else
{
c=a/b;
System.out.println(c);
}

Output

Compile time error in the line if(k==1)

"variable k might not have been initialized"

Explanation

Assuming k to be a local variable declared inside a method, we are using k in the if condition
before initializing it i.e. before assigning any value to k. Due to this, the above code will
generate a compile time error.
Question 4

switch (opn)
{
case 'a':
System.out.println("Platform Independent");
break;
case 'b':
System.out.println("Object Oriented");
case 'c':
System.out.println("Robust and Secure");
break;
default:
System.out.println("Wrong Input");
}
When (i) opn = 'b' (ii) opn = 'x' (iii) opn = 'a'

Output

(i) opn = 'b'

Object Oriented

Robust and Secure

Explanation

case 'b' is matched, "Object Oriented" gets printed to the console. As there is no case
statement in case 'b', program control falls through to case 'c' printing "Robust and Secure" to
the console. case 'c' has a break statement which transfers the program control outside switch
statement.

(ii) opn = 'x'

Wrong Input

Explanation

None of the 3 cases match so default case is executed.

(ii) opn = 'a'

Platform Independent

Explanation

case 'a' is matched, "Platform Independent" gets printed to the console. break statement in
case 'a' transfers the program control outside switch statement.
Correct the errors in the given programs

Question 1

class public
{
public static void main(String args{})
{
int a=45,b=70,c=65.45;
sum=a+b;
diff=c-b;
System.out.println(sum,diff);
}
}

Explanation

1. public is a keyword so it can't be used as an identifier for naming the class. Change the class
name from public to any valid identifier, for example class Sample
2. Argument of main method is an array of Strings. Use square brackets instead of curly
brackets — String args[]
3. c is an int variable. We cannot assign a double literal 65.45 to it.
4. Variables sum & diff are not defined
5. The line System.out.println(sum,diff); should be written like
this System.out.println(sum + " " + diff);

Corrected Program

class Sample //1st correction


{
public static void main(String args[]) //2nd correction
{
int a=45,b=70,c=65; //3rd correction
int sum=a+b; //4th Correction
int diff=c-b;
System.out.println(sum + " " + diff); //5th Correction
}
}

Question 2

class Square
{
public static void main(String args[])
{
int n=289,r;
r=sqrt(n);
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}

Explanation

1. Variable r must be of double type as Math.sqrt method returns a double value.


2. The line r=sqrt(n); should be r=Math.sqrt(n);

Corrected Program

class Square
{
public static void main(String args[])
{
int n=289;
double r=Math.sqrt(n); //1st & 2nd correction
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}

Question 3

class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10,b=5,c=1,d=2;
c=a2+b2;
d=(a+b)2;
p=c/d;
System.out.println(c + " "+ " "+d+ " "+p);
}
}

Explanation

1. The line a=10,b=5,c=1,d=2; generates a compile time error. We will combine the
declaration and initialization of these variables.
2. The line c=a2+b2; is written in Java like this c = (int)(Math.pow(a, 2) + Math.pow(b, 2));
3. The line d=(a+b)2; is written in Java like this d=(int)Math.pow((a+b), 2);
4. Variable p is not defined

Corrected Program

class Simplify
{
public static void main(String args[])
{
int a=10,b=5,c=1,d=2; //1st correction
c = (int)(Math.pow(a, 2) + Math.pow(b, 2)); //2nd correction
d = (int)Math.pow((a+b), 2); //3rd correction
int p=c/d; //4th correction
System.out.println(c + " "+ " "+d+ " "+p);
}
}

Question 4

class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12;
if(n=25)
{
k=pow(p,2)
System.out.println("The value of"+p+ " = "+k);
}
else
{
r=Math.square root(n);
System.out.println("The value of"+n+ " = "+r);
}
}
}

Explanation

1. The line if(n=25) should be if(n==25)


2. The line k=pow(p,2) should be k=(float)Math.pow(p,2);
3. The line r=Math.square root(n); should be r=(float)Math.sqrt(n);
Corrected Program

class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12;
if(n==25) //1st correction
{
k=(float)Math.pow(p,2); //2nd correction
System.out.println("The value of"+p+ " = "+k);
}
else
{
r=(float)Math.sqrt(n); //3rd correction
System.out.println("The value of"+n+ " = "+r);
}
}
}
Solutions to Unsolved Java Programs

Question 1

Write a program to input three angles of a triangle and check whether a triangle is possible or
not. If possible then check whether it is an acute-angled triangle, right-angled or an obtuse-
angled triangle otherwise, display 'Triangle not possible'.
Sample Input: Enter three angles: 40, 50, 90
Sample Output: Right=angled Triangle

import java.util.Scanner;

public class KboatTriangleAngle


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first angle: ");
int a1 = in.nextInt();
System.out.print("Enter second angle: ");
int a2 = in.nextInt();
System.out.print("Enter third angle: ");
int a3 = in.nextInt();
int angleSum = a1 + a2 + a3;

if (angleSum == 180 && a1 > 0 && a2 > 0 && a3 > 0) {


if (a1 < 90 && a2 < 90 && a3 < 90) {
System.out.println("Acute-angled Triangle");
}
else if (a1 == 90 || a2 == 90 || a3 == 90) {
System.out.println("Right-angled Triangle");
}
else {
System.out.println("Obtuse-angled Triangle");
}
}
else {
System.out.println("Triangle not possible");
}
}
}

Output

Question 2

Write a program to input the cost price and the selling price of an article. If the selling price is
more than the cost price then calculate and display actual profit and profit per cent otherwise,
calculate and display actual loss and loss per cent. If the cost price and the selling price are
equal, the program displays the message 'Neither profit nor loss'.

import java.util.Scanner;

public class KboatProfit


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter cost price of the article: ");
double cp = in.nextDouble();
System.out.print("Enter selling price of the article: ");
double sp = in.nextDouble();
double pl = sp - cp;
double percent = Math.abs(pl) / cp * 100;
if (pl > 0) {
System.out.println("Profit = " + pl);
System.out.println("Profit % = " + percent);
}
else if (pl < 0) {
System.out.println("Loss = " + Math.abs(pl));
System.out.println("Loss % = " + percent);
}
else {
System.out.println("Neither profit nor loss");
}
}
}
Question 3

Write a program to input three numbers and check whether they are equal or not. If they are
unequal numbers then display the greatest among them otherwise, display the message 'All
the numbers are equal'.
Sample Input: 34, 87, 61
Sample Output: Greatest number: 87
Sample Input: 81, 81, 81
Sample Output: All the numbers are equal.

import java.util.Scanner;

public class Kboat3Numbers


{
public static void main(String args[]) {
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.print("Enter third number: ");
int c = in.nextInt();

if (a == b && b == c) {
System.out.println("All the numbers are equal");
}
else {
int g = a;

if (b > g)
g = b;

if (c > g)
g = c;

System.out.println("Greatest number: " + g);


}
}
}

Output
Question 4

Write a program to accept a number and check whether the number is divisible by 3 as well
as 5. Otherwise, decide:
(a) Is the number divisible by 3 and not by 5?
(b) Is the number divisible by 5 and not by 3?
(c) Is the number neither divisible by 3 nor by 5?
The program displays the message accordingly.

import java.util.Scanner;

public class Divisor


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

if (num % 3 == 0 && num % 5 == 0)


System.out.println("Divisible by 3 and 5");
else if (num % 3 == 0)
System.out.println("Divisible by 3 but not by 5");
else if (num % 5 == 0)
System.out.println("Divisible by 5 but not by 3");
else
System.out.println("Neither divisible by 3 nor by 5");
}
}

Output

Question 5

Write a program to input year and check whether it is:


(a) a Leap year (b) a Century Leap year (c) a Century year but not a Leap year
Sample Input: 2000
Sample Output: It is a Century Leap Year.

import java.util.Scanner;

public class KboatCenturyLeapYear


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the year to check: ");
int yr = in.nextInt();
if (yr % 4 == 0 && yr % 100 != 0)
System.out.println("It is a Leap Year");
else if (yr % 400 == 0)
System.out.println("It is a Century Leap Year");
else if (yr % 100 == 0)
System.out.println("It is a Century Year but not a Leap
Year");
else
System.out.println("It is neither a Century Year nor a
Leap Year");
}
}

Output

Question 6

Write a program to input two unequal positive numbers and check whether they are perfect
square numbers or not. If the user enters a negative number then the program displays the
message 'Square root of a negative number can't be determined'.
Sample Input: 81, 100
Sample Output: They are perfect square numbers.
Sample Input: 225, 99
Sample Output: 225 is a perfect square number.
99 is not a perfect square number.

import java.util.Scanner;

public class KboatPerfectSquare


{
public static void main(String args[]) {
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();

if (a < 0 || b < 0) {
System.out.println("Square root of a negative number
can't be determined");
}
else {
double sqrtA = Math.sqrt(a);
double sqrtB = Math.sqrt(b);
double isAPerfectSq = sqrtA - Math.floor(sqrtA);
double isBPerfectSq = sqrtB - Math.floor(sqrtB);
if (isAPerfectSq == 0 && isBPerfectSq == 0) {
System.out.println("They are perfect square
numbers.");
}
else if (isAPerfectSq == 0) {
System.out.println(a + " is a perfect square
number.");
System.out.println(b + " is not a perfect square
number.");
}
else if (isBPerfectSq == 0) {
System.out.println(a + " is not a perfect square
number.");
System.out.println(b + " is a perfect square
number.");
}
else {
System.out.println("Both are not perfect square
numbers.");
}
}
}
}

Output

Question 7

Without using if-else statement and ternary operators, accept three unequal numbers and
display the second smallest number.
[Hint: Use Math.max( ) and Math.min( )]
Sample Input: 34, 82, 61
Sample Output: 61

import java.util.Scanner;

public class Kboat2ndSmallestNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 unequal numbers");
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
System.out.print("Enter third number: ");
int c = in.nextInt();

int sum = a + b + c;
int big = Math.max(a, b);
big = Math.max(big, c);
int small = Math.min(a, b);
small = Math.min(small, c);
int result = sum - big - small;
System.out.println("Second Smallest Number = " + result);

}
}

Output

Question 8

Write a program to input three unequal numbers. Display the greatest and the smallest
number.
Sample Input: 28, 98, 56
Sample Output: Greatest Number: 98
Smallest Number: 28

import java.util.Scanner;

public class KboatMinMaxNumbers


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 unequal numbers");
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
System.out.print("Enter third number: ");
int c = in.nextInt();

int min = a, max = a;


min = b < min ? b : min;
min = c < min ? c : min;

max = b > max ? b : max;


max = c > max ? c : max;
System.out.println("Greatest Number: " + max);
System.out.println("Smallest Number: " + min);

}
}

Output

Question 9

A Pre-Paid taxi charges from the passenger as per the tariff given below:

Distance Rate

Up to 5 km ₹ 100

For the next 10 km ₹ 10/km

For the next 10 km ₹ 8/km

More than 25 km ₹ 5/km

Write a program to input the distance covered and calculate the amount paid by the
passenger. The program displays the printed bill with the details given below:
Taxi No. :
Distance covered :
Amount :

import java.util.Scanner;

public class KboatPrePaidTaxi


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Taxi Number: ");
String taxiNo = in.nextLine();
System.out.print("Enter distance travelled: ");
int dist = in.nextInt();

int fare = 0;
if (dist <= 5)
fare = 100;
else if (dist <= 15)
fare = 100 + (dist - 5) * 10;
else if (dist <= 25)
fare = 100 + 100 + (dist - 15) * 8;
else
fare = 100 + 100 + 80 + (dist - 25) * 5;

System.out.println("Taxi No: " + taxiNo);


System.out.println("Distance covered: " + dist);
System.out.println("Amount: " + fare);

}
}

Output

Question 10

A cloth showroom has announced festival discounts and the gifts on the purchase of items,
based on the total cost as given below:

Total Cost Discount Gift

Up to ₹ 2,000 5% Calculator

₹ 2,001 to ₹ 5,000 10% School Bag

₹ 5,001 to ₹ 10,000 15% Wall Clock

Above ₹ 10,000 20% Wrist Watch

Write a program to input the total cost. Compute and display the amount to be paid by the
customer along with the gift.

import java.util.Scanner;

public class KboatClothDiscount


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter total cost: ");
double cost = in.nextDouble();
String gift;
double amt;
if (cost <= 2000.0) {
amt = cost - (cost * 5 / 100);
gift = "Calculator";
}
else if (cost <= 5000.0) {
amt = cost - (cost * 10 / 100);
gift = "School Bag";
}
else if (cost <= 10000.0) {
amt = cost - (cost * 15 / 100);
gift = "Wall Clock";
}
else {
amt = cost - (cost * 20 / 100);
gift = "Wrist Watch";
}

System.out.println("Amount to be paid: " + amt);


System.out.println("Gift: " + gift);

}
}

Output

Question 11

Given below is a hypothetical table showing rate of income tax for an India citizen, who is
below or up to 60 years.

Taxable income (TI) in ₹ Income Tax in ₹

Up to ₹ 2,50,000 Nil

More than ₹ 2,50,000 and less than or equal to ₹ 5,00,000 (TI - 1,60,000) * 10%

More than ₹ 5,00,000 and less than or equal to ₹ 10,00,000 (TI - 5,00,000) * 20% + 34,000

More than ₹ 10,00,000 (TI - 10,00,000) * 30% + 94,000

Write a program to input the name, age and taxable income of a person. If the age is more
than 60 years then display the message "Wrong Category". If the age is less than or equal to
60 years then compute and display the income tax payable along with the name of tax payer,
as per the table given above.

import java.util.Scanner;

public class KboatIncomeTax


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = in.nextLine();
System.out.print("Enter age: ");
int age = in.nextInt();
System.out.print("Enter taxable income: ");
double ti = in.nextDouble();
double tax = 0.0;

if (age > 60) {


System.out.print("Wrong Category");
}
else {
if (ti <= 250000)
tax = 0;
else if (ti <= 500000)
tax = (ti - 160000) * 10 / 100;
else if (ti <= 1000000)
tax = 34000 + ((ti - 500000) * 20 / 100);
else
tax = 94000 + ((ti - 1000000) * 30 / 100);
}

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


System.out.println("Tax Payable: " + tax);
}
}

Output
Question 12

An employee wants to deposit certain sum of money under 'Term Deposit' scheme in
Syndicate Bank. The bank has provided the tariff of the scheme, which is given below:

No. of Days Rate of Interest

Up to 180 days 5.5%

181 to 364 days 7.5%

Exact 365 days 9.0%

More than 365 days 8.5%

Write a program to calculate the maturity amount taking the sum and number of days as
inputs.

import java.util.Scanner;

public class KboatTermDeposit


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter sum of money: ");
double sum = in.nextDouble();
System.out.print("Enter number of days: ");
int days = in.nextInt();
double interest = 0.0;

if (days <= 180)


interest = sum * 5.5 / 100.0;
else if (days <= 364)
interest = sum * 7.5 / 100.0;
else if (days == 365)
interest = sum * 9.0 / 100.0;
else
interest = sum * 8.5 / 100.0;

double amt = sum + interest;

System.out.print("Maturity Amount = " + amt);


}
}
Question 13

Mr. Kumar is an LIC agent. He offers discount to his policy holders on the annual premium.
However, he also gets commission on the sum assured as per the given tariff.

Sum Assured Discount Commission

Up to ₹ 1,00,000 5% 2%

₹ 1,00,001 and up to ₹ 2,00,000 8% 3%

₹ 2,00,001 and up to ₹ 5,00,000 10% 5%

More than ₹ 5,00,000 15% 7.5%

Write a program to input name of the policy holder, the sum assured and first annual
premium. Calculate the discount of the policy holder and the commission of the agent. The
program displays all the details as:
Name of the policy holder :
Sum assured :
Premium :
Discount on the first premium :
Commission of the agent :

import java.util.Scanner;

public class KboatLICPolicy


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = in.nextLine();
System.out.print("Enter Sum Assured: ");
double sum = in.nextDouble();
System.out.print("Enter First Premium: ");
double pre = in.nextDouble();
double disc = 0.0, comm = 0.0;

if(sum <= 100000){


disc = pre * 5.0 / 100.0;
comm = sum * 2.0 / 100.0;
}
else if(sum <= 200000){
disc = pre * 8.0 / 100.0;
comm = sum * 3.0 / 100.0;
}
else if(sum <= 500000){
disc = pre * 10.0 / 100.0;
comm = sum * 5.0 / 100.0;
}
else{
disc = pre * 15.0 / 100.0;
comm = sum * 7.5 / 100.0;
}

System.out.println("Name of the policy holder: " + name);


System.out.println("Sum assured: " + sum);
System.out.println("Premium: " + pre);
System.out.println("Discount on the first premium: " +
disc);
System.out.println("Commission of the agent: " + comm);

}
}

Output

Question 14

A company announces revised Dearness Allowance (DA) and Special Allowances (SA) for
their employees as per the tariff given below:

Basic Dearness Allowance (DA) Special Allowance (SA)

Up to ₹ 10,000 10% 5%

₹ 10,001 - ₹ 20,000 12% 8%

₹ 20,001 - ₹ 30,000 15% 10%

₹ 30,001 and above 20% 12%

Write a program to accept name and Basic Salary (BS) of an employee. Calculate and display
gross salary.
Gross Salary = Basic + Dearness Allowance + Special Allowance
Print the information in the given format:
Name Basic DA Spl. Allowance Gross Salary
xxx xxx xxx xxx xxx

import java.util.Scanner;
public class KboatSalary
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
String name = in.nextLine();
System.out.print("Enter basic salary: ");
double bs = in.nextDouble();
double da = 0.0, sa = 0.0;

if (bs <= 10000){


da = bs * 10.0 / 100.0;
sa = bs * 5.0 / 100.0;
}
else if (bs <= 20000){
da = bs * 12.0 / 100.0;
sa = bs * 8.0 / 100.0;
}
else if (bs <= 30000){
da = bs * 15.0 / 100.0;
sa = bs * 10.0 / 100.0;
}
else{
da = bs * 20.0 / 100.0;
sa = bs * 12.0 / 100.0;
}

double gs = bs + da + sa;
System.out.println("Name\tBasic\tDA\tSpl. Allowance\tGross
Salary");
System.out.println(name + "\t" + bs + "\t" + da + "\t" + sa
+ "\t" + gs);
}
}

Output

Question 15

Using a switch case statement, write a menu driven program to convert a given temperature
from Fahrenheit to Celsius and vice-versa. For an incorrect choice, an appropriate message
should be displayed.
Hint: c = 5/9*(f-32) and f=1.8*c+32
import java.util.Scanner;

public class KboatTemperature


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 to convert from Fahrenheit to
Celsius");
System.out.println("Type 2 to convert from Celsius to
Fahrenheit");
int choice = in.nextInt();
double ft = 0.0, ct = 0.0;

switch (choice) {
case 1:
System.out.print("Enter temperature in Fahrenheit:
");
ft = in.nextDouble();
ct = 5 / 9.0 * (ft - 32);
System.out.println("Temperature in Celsius: " + ct);
break;

case 2:
System.out.print("Enter temperature in Celsius: ");
ct = in.nextDouble();
ft = 1.8 * ct + 32;
System.out.println("Temperature in Fahrenheit: " +
ft);
break;

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

Output
Question 16

The volume of solids, viz. cuboid, cylinder and cone can be calculated by the formula:

1. Volume of a cuboid (v = l*b*h)


2. Volume of a cylinder (v = π*r2*h)
3. Volume of a cone (v = (1/3)*π*r2*h)

Using a switch case statement, write a program to find the volume of different solids by
taking suitable variables and data types.

import java.util.Scanner;

public class KboatMenuVolume


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Volume of cuboid");
System.out.println("2. Volume of cylinder");
System.out.println("3. Volume of cone");
System.out.print("Enter your choice: ");
int choice = in.nextInt();

switch(choice) {
case 1:
System.out.print("Enter length of cuboid: ");
double l = in.nextDouble();
System.out.print("Enter breadth of cuboid: ");
double b = in.nextDouble();
System.out.print("Enter height of cuboid: ");
double h = in.nextDouble();
double vol = l * b * h;
System.out.println("Volume of cuboid = " + vol);
break;

case 2:
System.out.print("Enter radius of cylinder: ");
double rCylinder = in.nextDouble();
System.out.print("Enter height of cylinder: ");
double hCylinder = in.nextDouble();
double vCylinder = (22 / 7.0) * Math.pow(rCylinder,
2) * hCylinder;
System.out.println("Volume of cylinder = " +
vCylinder);
break;

case 3:
System.out.print("Enter radius of cone: ");
double rCone = in.nextDouble();
System.out.print("Enter height of cone: ");
double hCone = in.nextDouble();
double vCone = (1 / 3.0) * (22 / 7.0) *
Math.pow(rCone, 2) * hCone;
System.out.println("Volume of cone = " + vCone);
break;

default:
System.out.println("Wrong choice! Please select from
1 or 2 or 3.");
}
}
}

Output

Question 17

A Mega Shop has different floors which display varieties of dresses as mentioned
below:

1. Ground floor : Kids Wear


2. First floor : Ladies Wear
3. Second floor : Designer Sarees
4. Third Floor : Men's Wear

The user enters floor number and gets the information regarding different items of the Mega
shop. After shopping, the customer pays the amount at the billing counter and the shopkeeper
prints the bill in the given format:

Name of the Shop: City Mart


Total Amount:
Visit Again!!

Write a program to perform the above task as per the user's choice.

import java.util.Scanner;

public class KboatMegaShop


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Ground floor");
System.out.println("2. First floor");
System.out.println("3. Second floor");
System.out.println("4. Third floor");

System.out.print("Select a floor: ");


int floor = in.nextInt();

boolean isFloorValid = true;

switch (floor) {
case 1:
System.out.println("Kids Wear");
break;
case 2:
System.out.println("Ladies Wear");
break;
case 3:
System.out.println("Designer Sarees");
break;
case 4:
System.out.println("Men's Wear");
break;
default:
isFloorValid = false;
System.out.println("Incorrect Floor");
break;
}

if (isFloorValid) {
System.out.print("Enter bill amount: ");
double amt = in.nextDouble();

System.out.println("Name of the Shop: City Mart");


System.out.println("Total Amount: " + amt);
System.out.println("Visit Again!!");
}
}
}

Output

Question 18

The equivalent resistance of series and parallel connections of two resistances are given by
the formula:
(a) R1 = r1 + r2 (Series)
(b) R2 = (r1 * r2) / (r1 + r2) (Parallel)

Using a switch case statement, write a program to enter the value of r1 and r2. Calculate and
display the equivalent resistances accordingly.

import java.util.Scanner;

public class KboatResistance


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Series");
System.out.println("2. Parallel");

System.out.print("Enter your choice: ");


int choice = in.nextInt();
boolean isChoiceValid = true;

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


double r1 = in.nextDouble();
System.out.print("Enter r2: ");
double r2 = in.nextDouble();
double eqr = 0.0;

switch (choice) {
case 1:
eqr = r1 + r2;
break;
case 2:
eqr = (r1 * r2) / (r1 + r2);
break;
default:
isChoiceValid = false;
System.out.println("Incorrect choice");
break;
}

if (isChoiceValid)
System.out.println("Equivalent resistance = " + eqr);
}
}

Output
Question 19

The Simple Interest (SI) and Compound Interest (CI) of a sum (P) for a given time (T) and
rate (R) can be calculated as:

(a) SI = (p * r * t) / 100 (b) CI = P * ((1 + (R / 100))T - 1)

Write a program to input sum, rate, time and type of Interest ('S' for Simple Interest and 'C'
for Compound Interest). Calculate and display the sum and the interest earned.

import java.util.Scanner;

public class KboatInterest


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sum: ");
double p = in.nextDouble();
System.out.print("Enter rate: ");
double r = in.nextDouble();
System.out.print("Enter time: ");
int t = in.nextInt();
System.out.println("Enter type of Interest");
System.out.print("('S'- Simple Interest 'C'- Compound
Interest): ");
char type = in.next().charAt(0);
boolean isTypeValid = true;

double interest = 0.0;

switch (type) {
case 'S':
interest = p * r * t / 100;
break;

case 'C':
interest = p * (Math.pow((1 + (r / 100)), t) - 1);
break;

default:
isTypeValid = false;
System.out.println("Incorrect Interest type");
break;
}

if (isTypeValid) {
double amt = p + interest;
System.out.println("Sum = " + p);
System.out.println("Interest = " + interest);
System.out.println("Sum + Interest = " + amt);
}
}
}

Output

Question 20

'Kumar Electronics' has announced the following seasonal discounts on purchase of certain
items.

Purchase Amount Discount on Laptop Discount on Desktop PC

Up to ₹ 25000 0.0% 5.0%

₹ 25,001 to ₹ 50,000 5% 7.5%

₹ 50,001 to ₹ 1,00,000 7.5% 10.0%

More than ₹ 1,00,000 10.0% 15.0%

Write a program to input name, amount of purchase and the type of purchase (`L' for Laptop
and 'D' for Desktop) by a customer. Compute and print the net amount to be paid by a
customer along with his name.
(Net amount = Amount of purchase - discount)

import java.util.Scanner;

public class KboatElectronicsSale


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = in.nextLine();
System.out.print("Enter Amount of Purchase: ");
double amt = in.nextDouble();
System.out.println("Enter Type of Purchase");
System.out.print("'L'- Laptop or 'D'- Desktop: ");
char type = in.next().charAt(0);
type = Character.toUpperCase(type);
double disc = 0.0;
if (amt <= 25000)
disc = type == 'L' ? 0.0 : 5.0;
else if (amt <= 50000)
disc = type == 'L' ? 5.0 : 7.0;
else if (amt <= 100000)
disc = type == 'L' ? 7.5 : 10.0;
else
disc = type == 'L' ? 10.0 : 15.0;

double netAmt = amt - (disc * amt / 100);

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


System.out.println("Net Amount: " + netAmt);
}
}

Output
Chapter 8

Iterative Constructs In Java


Class 9 - APC Understanding Computer
Applications with BlueJ

Multiple Choice Questions

Question 1

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

1. iteration ✓
2. sequence
3. selection
4. none

Question 2

Which of the following statement is exit controlled loop?

1. for
2. while
3. do-while ✓
4. if-else

Question 3

Which of the following loop does not execute even once if condition is false in the
beginning?

1. do-while
2. while ✓
3. for ✓
4. nested loop
Question 4

To execute a loop 10 times, which of the following statement satisfies:

1. for(i=6;i<=26;i=i+2)
2. for(i=3;i<=30;i=i+3) ✓
3. for(i=0;i<10;i=i++)
4. all of the above

Question 5

Which of the following statement uses multiple branches?

1. loop
2. continue
3. switch ✓
4. break

Question 6

Which of the following loop checks the condition first and then execution begins?

1. do-while
2. do
3. while loop ✓
4. for ✓

Question 7

To find the sum of whole numbers upto 10, a loop runs:

1. once
2. ten times
3. eleven times ✓
4. any number of times

Question 8

How many times the loop, for (i=1; ;i++), will execute, if there is no statement to terminate
the loop?

1. 1
2. 0
3. infinite ✓
4. none
Question 9

Which of the following statements uses a case called default?

1. do-while
2. while
3. switch ✓
4. all of the above

Question 10

A loop statement is given as:

for(i=10;i<10,i++)
{
Statement
}
For how many times will the given loop statement be executed:

1. never ✓
2. 1 time
3. 10 times
4. infinite

Answer the Following Questions

Question 1

What do you understand by iterative process? How can it be resolved by using loop?
Iterative process means repeating a set of actions a certain number of times to perform
some task. Loops in programming languages like Java enable us to repeat a single
statement or a set of statements as long as the desired condition remains true.

Question 2

Explain for loop with an example.


for loop is an entry-controlled loop. Below is an example of for loop:

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


int a = 2 * i;
System.out.println("2 x " + i + "\t= " + a);
}
This for loop prints the table of 2 till 12. int i = 1 is the initialization part of the for
loop, it is executed only once when the loop gets executed for the first time. i <= 12 is
the condition part of the for loop, it is executed before the start of each iteration. Loop
iterates as long as this condition remains true. Once it becomes false, execution of the
loop is stopped. i++ is the update part of the for loop. It is executed at the end of each
iteration.
Question 3

Name the different types of loop statements.

1. for
2. while
3. do-while

Question 4

What are the parameters needed to create a for loop?


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.

Question 5

Define the following with their constructs:


(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 6

Write down the general format of:


(a) for loop

for (initialization; condition; update) {


//loop-body
}
(b) do - while

do {
//loop-body
} while (condition);
(c) while loop

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

What is the purpose of using:


(a) break statement
break statement is used to unconditionally jump out of the loop
(b) continue statement
continue statement is used to unconditionally jump to the next iteration of the loop,
skipping the remaining statements of the current iteration.

Question 8

What do you understand by inter-conversion of loops?


We can convert the repetitive logic written using one type of loop into any of the other 2
types. For example, if some repetitive logic is coded using a for loop, we can convert that
for loop into while or do-while loop. This is termed inter-conversion of loops.

Question 9

What are the different ways to inter-convert the loops? Name them.

1. for loop to while loop


2. for loop to do-while loop
3. do-while loop to while loop
4. do-while loop to for loop
5. while loop to do-while loop
6. while loop to for loop

Question 10

Define the following:


(a) Finite loop
A loop which iterates for a finite number of iterations is termed as a finite loop.

(b) Delay loop


A loop which is used to pause the execution of the program for some finite amount of
time is termed as Delay loop. Delay loops have an empty loop body.

(c) Infinite loop


A loop which continues iterating indefinitely and never stops is termed as infinite loop.

(d) Null loop


A loop which has an empty loop body is termed as a null loop.
Question 11

Distinguish between:

(a) for and while loop

1. for loop is a suitable choice when we know the number of iterations beforehand. while
loop is helpful in situations where numbers of iterations is not known.
2. Omitting the condition in for loop will lead to an infinite loop whereas if condition is not
provided in while loop, it will cause a compilation error.

(b) while and do-while loop

1. while is an entry-controlled loop whereas do-while is an exit-controlled loop


2. while loop is helpful in situations where numbers of iterations is not known. do-while is
suitable when we need to display a menu to the user.

Question 12

State one difference and one similarity between while and do-while loop
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

Question 13

State one similarity and one difference between while and for loop.
Similarity — Both for and while are entry-controlled loops
Difference — for loop is a suitable choice when we know the number of iterations
beforehand. while loop is helpful in situations where numbers of iterations is not known.

Question 14

Give two differences between Step loop and Continuous loop.


In Continuous loop, loop control variable is incremented or decremented by 1 in each
iteration whereas in Step loop the loop control variable is incremented or decremented
by more than 1 in each iteration.

Predict the Output of the following Programs

Question 1

class dkl
{
public static void main(String args[])
{
int i;
for(i = -1;i<10;i++)
{
System.out.println(++i);
}
}
}

Output

10

Explanation

This table shows the changes in the value of i as the for loop iterates:

i Remarks

-1 Initial value

0 1st Iteration — i is -1, ++i makes it 0

2 2nd Iteration — i becomes 1, ++i makes it 2

4 3rd Iteration — i becomes 3, ++i makes it 4

6 4th Iteration — i becomes 5, ++i makes it 6

8 5th Iteration — i becomes 7, ++i makes it 8

10 6th Iteration — i becomes 9, ++i makes it 10

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


Question 2

class dk2
{
public static void main(String args[])
{
int i=2,k=1;
while (++i<6)
k *= i;
System.out.println(k);
}
}

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 3

class dk3
{
public static void main(String args[])
{
int m=2,n=15;
for(int i=1;i<=5;i++)
{
m++;--n;
System.out.println("m="+m);
System.out.println("n="+n);
}
}
}

Output

m=3

n=14

m=4

n=13

m=5

n=12

m=6

n=11

m=7

n=10

Explanation

This table shows the change in values of m, n and i as the for loop iterates:

m n i Remarks

2 15 — Initial values

3 14 1 1st Iteration

4 13 2 2nd Iteration

5 12 3 3rd Iteration

6 11 4 4th Iteration
m n i Remarks

7 10 5 5th Iteration

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

Question 4

Determine how many times the body of the loop will be executed.

class dk4
{
public static void main(String args[])
{
int x=5,y=50;
while(x<=y)
{
y=y/x;
System.out.println(y);
}
}
}

Output

10

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.
Rewrite the following Programs

Question 1

Using do while:

class Test
{
public static void main(String args[])
{
int x,c;
for(x=10,c=20;c>=10;c=c-2)
{
x++;
System.out.println(x);
}
}
}

Solution

class Test
{
public static void main(String args[])
{
int x=10, c=20;
do {
x++;
System.out.println(x);
c=c-2;
} while (c>=10);
}
}

Question 2

Using do while:

class Pattern
{
public static void main(String args[])
{
int i,j;
for(i=5;i>=1;i--)
{
System.out.print(i);
}
System.out.println();
}
}

Solution

class Pattern
{
public static void main(String args[])
{
int i=5,j;
do {
System.out.print(i);
i--;
} while (i>=1);
System.out.println();
}
}

Question 3

Using do while:

class Number
{
public static void main(String args[])
{
int i,n=191,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c=c+1;
}
if(c==2)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}

Solution

class Number
{
public static void main(String args[])
{
int i=1,n=191,c=0;
do {
if(n%i==0)
c=c+1;
i++;
} while (i<=n);
if(c==2)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}

Question 4

Using while loop:

import java.io.*;
class Sample
{
public static void main(String args[]) throws IOException
{
int n,r;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("Enter a number");
n=Integer.parseInt(in.readLine());
do
{
r=n%10;
n=n/10;
System.out.println(r);
}
while(n!=0);
}
}

Solution

import java.io.*;
class Sample
{
public static void main(String args[]) throws IOException
{
int n,r;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("Enter a number");
n=Integer.parseInt(in.readLine());
while(n!=0)
{
r=n%10;
n=n/10;
System.out.println(r);
}
}
}
Solutions to Unsolved Java Programs

Question 1

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

(a) 1, 4, 9, 16,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 1; i <= 10; i++) {
System.out.print(i * i + " ");
}
}
}

Output
(b) 1, 2, 4, 7, 11,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
int term = 1 + ((i * (i + 1)) / 2);
System.out.print(term + " ");
}
}
}

Output

(c) 3, 6, 9, 12,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 3; i <= 30; i = i + 3) {
System.out.print(i + " ");
}
}
}
Output

(d) 4, 8, 16, 32,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 2; i <= 11; i++) {
System.out.print((int)(Math.pow(2, i)) + " ");
}
}
}
Output

(e) 1.5, 3.0, 4.5, 6.0,

public class KboatSeries


{
public static void main(String args[]) {
float term = 1.5f;
for (int i = 1; i <= 10; i++) {
System.out.print(term + " ");
term += 1.5f;
}
}
}
Output

(f) 0, 7, 26,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 1; i <= 10; i++) {
int term = (int)(Math.pow(i, 3) - 1);
System.out.print(term + " ");
}
}
}
Output

(g) 1, 9, 25, 49,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 1; i <= 19; i = i + 2) {
System.out.print((i * i) + " ");
}
}
}
Output

(h) 4, 16, 36, 64,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 2; i <= 20; i = i + 2) {
System.out.print((i * i) + " ");
}
}
}
Output

(i) 0, 3, 8, 15,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 1; i <= 10; i++) {
System.out.print((i * i - 1) + " ");
}
}
}
Output

(j) 24, 99, 224, 399,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 5; i <= 50; i = i + 5) {
int term = (int)(Math.pow(i, 2) - 1);
System.out.print(term + " ");
}
}
}
Output

(k) 2, 5, 10, 17,

public class KboatSeries


{
public static void main(String args[]) {
for (int i = 1; i <= 10; i++) {
System.out.print((i * i + 1) + " ");
}
}
}
Output

Question 2

Write a program to input any 50 numbers (including positive and negative).


Perform the following tasks:
(a) Count the positive numbers
(b) Count the negative numbers
(c) Sum of positive numbers
(d) Sum of negative numbers

import java.util.Scanner;

public class KboatIntegers


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int pSum = 0, pCount = 0, nSum = 0, nCount = 0;
System.out.println("Enter 50 numbers");

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


int n = in.nextInt();
if (n >= 0) {
pSum += n;
pCount++;
}
else {
nSum += n;
nCount++;
}
}

System.out.println("Positive Count = " + pCount);


System.out.println("Positive Sum = " + pSum);
System.out.println("Negative Count = " + nCount);
System.out.println("Negative Sum = " + nSum);
}
}
Output
Question 3

Write a program to calculate the sum of all odd numbers and even numbers between a range
of numbers from m to n (both inclusive) where m < n. Input m and n (where m<n).

import java.util.Scanner;

public class KboatOddEvenSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter m: ");
int m = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
long sumOdd = 0, sumEven = 0;

if (m > n) {
System.out.println("m should be less than n");
}
else {
for (int i = m; i <=n; i++) {
if (i % 2 == 0)
sumEven += i;
else
sumOdd += i;
}

System.out.println("Even Sum: " + sumEven);


System.out.println("Odd Sum: " + sumOdd);
}
}
}
Output

Question 4

Write a program to enter any 50 numbers and check whether they are divisible by 5 or not. If
divisible then perform the following tasks:
(a) Display all the numbers ending with the digit 5.
(b) Count those numbers ending with 0 (zero).

import java.util.Scanner;

public class KboatDivisibleBy5


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n, c = 0;
System.out.println("Enter 50 numbers");
for (int i = 1; i <= 50; i++) {
n = in.nextInt();
if (n % 5 == 0) {
if (n % 10 == 5)
System.out.println("Number end with the digit
5");
if (n % 10 == 0)
c++;
}
}
System.out.println("Count of numbers ending with 0: " + c);
}
Question 5

Write a program to display all the numbers between m and n input from the keyboard (where
m<n, m>0, n>0), check and print the numbers that are perfect square. e.g. 25, 36, 49, are said
to be perfect square numbers.

import java.util.Scanner;

public class KboatPerfectSquare


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

if (m < n && m > 0 && n > 0) {


for (int i = m; i <= n; i++) {
System.out.println("Number = " + i);
double sroot = Math.sqrt(i);
if (sroot == Math.floor(sroot))
System.out.println(i + " is a perfect square");
}
}
else {
System.out.println("Invalid input");
}
}
}
Output

Question 6
Write a program to display all the 'Buzz Numbers' between p and q (where p<q). A 'Buzz
Number' is the number which ends with 7 or is divisible by 7.

import java.util.Scanner;

public class KboatBuzzNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter p: ");
int p = in.nextInt();
System.out.print("Enter q: ");
int q = in.nextInt();
if (p < q) {
System.out.println("Buzz Numbers between "
+ p + " and " + q);
for (int i = p; i <= q; i++) {
if (i % 10 == 7 || i % 7 == 0)
System.out.println(i);
}
}
else {
System.out.println("Invalid Inputs!!!");
System.out.println("p should be less than q");
}

}
}

Output
Question 7

Write a program to input marks in English, Maths and Science of 40 students who have
passed ICSE Examination 2014. Now, perform the following tasks:
(a) Number of students, who have secured 95% or more in all the subjects.
(b) Number of students, who have secured 90% or more in English, Maths and Science.

import java.util.Scanner;

public class KboatExamResult


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int ta = 0, te = 0, tm = 0, ts = 0;
for (int i = 1; i <= 40; i++) {
System.out.println("Enter marks of student " + i);
System.out.print("English: ");
int eng = in.nextInt();
System.out.print("Maths: ");
int maths = in.nextInt();
System.out.print("Science: ");
int sci = in.nextInt();

if (eng >= 95 && maths >= 95 && sci >= 95)


ta++;

if (eng >= 90)


te++;

if (maths >= 90)


tm++;

if (sci >= 90)


ts++;
}
System.out.println("No. of students >= 95% in all subjects:
" + ta);
System.out.println("No. of students >= 90% in English: " +
te);
System.out.println("No. of students >= 90% in Maths: " +
tm);
System.out.println("No. of students >= 90% in Science: " +
ts);
}
}
Question 8

Write a program in Java to find the sum of the given series :


(a) 1 + 4 + 9 + ...... + 400

public class KboatSeries


{
public static void main(String args[]) {
int sum = 0;
for (int i = 1; i <= 20; i++)
sum += (i*i);
System.out.println("Sum = " + sum);
}
}

Output

(b) 1 + (1/2) + (1/3) + ...... + (1/20)

public class KboatSeries


{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 1; i <= 20; i++)
sum += (1.0 / i);
System.out.println("Sum = " + sum);
}
}
Output

(c) 1 + (1/3) + (1/5) + ...... + (1/19)

public class KboatSeries


{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 1; i <= 19; i = i + 2)
sum += (1.0 / i);
System.out.println("Sum = " + sum);
}
}
(d) (1/2) + (2/3) + (3/4) + ...... + (19/20)

public class KboatSeries


{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 1; i <= 19; i++)
sum += (i / (double)(i + 1));
System.out.println("Sum = " + sum);
}
}

Output

(e) 2 - 4 + 6 - 8 + ...... - 20

public class KboatSeries


{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0)
sum -= i * 2;
else
sum += i * 2;
}
System.out.println("Sum = " + sum);
}
}
Output

(f) (1*2) + (2*3) + ...... + (19*20)

public class KboatSeries


{
public static void main(String args[]) {
int sum = 0;
for (int i = 1; i <= 19; i++)
sum += i * (i + 1);
System.out.println("Sum = " + sum);
}
}
Question 9

Write a program to input a number and count the number of digits. The program further
checks whether the number contains odd number of digits or even number of digits.
Sample Input: 749
Sample Output: Number of digits=3
The number contains odd number of digits.

import java.util.Scanner;

public class KboatDigitCount


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

while (n != 0) {
dc++;
n /= 10;
}

System.out.println("Number of digits = " + dc);

if (dc % 2 == 0)
System.out.println("The number contains even number of
digits");
else
System.out.println("The number contains odd number of
digits");
}
}
Output

Question 10

Write a program to input a number and display the new number after reversing the digits of
the original number. The program also displays the absolute difference between the original
number and the reversed number.
Sample Input: 194
Sample Output: 491
Absolute Difference= 297

import java.util.Scanner;

public class KboatDigitReverse


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

Scanner in = new Scanner(System.in);


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

int copyNum = orgNum;


int revNum = 0;

while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
int diff = revNum - orgNum;
System.out.println("Reversed Number = " + revNum);
System.out.println("Absolute Difference = " +
Math.abs(diff));
}
}

Output

Question 11

The Greatest Common Divisor (GCD) of two integers is calculated by the continued division
method. Divide the larger number by the smaller, the remainder then divides the previous
divisor. The process repeats unless the remainder reaches to zero. The last divisor results in
GCD.
Sample Input: 45, 20
Sample Output: GCD=5

import java.util.Scanner;

public class KboatGCD


{
public static void main(String args[]) {
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();
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
System.out.println("GCD=" + a);
}
}

Output

Question 12

Write a program in Java to find the sum of the given series :

(a) S = a2 + a2 / 2 + a2 / 3 + ...... + a2 / 10

import java.util.Scanner;

public class KboatSeries


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= 10; i++)
sum += Math.pow(a, 2) / i;
System.out.println("Sum = " + sum);
}
}
Output

(b) S = a + a2 / 2 + a3 / 3 + ...... + a10 / 10

import java.util.Scanner;

public class KboatSeries


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= 10; i++)
sum += Math.pow(a, i) / i;
System.out.println("Sum = " + sum);
}
}
Output

(c) S = (a*2) + (a*3) + ...... + (a*20)

import java.util.Scanner;

public class KboatSeries


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
long sum = 0;
for (int i = 2; i <= 20; i++)
sum += a * i;
System.out.println("Sum = " + sum);
}
}
Output

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

import java.util.Scanner;

public class KboatSeries


{
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 n: ");
int n = in.nextInt();
long sum = 0;
for (int i = 1; i <= n; i++)
sum += Math.pow(a, i);
System.out.println("Sum = " + sum);
}
}
Output

(e) S = 1 + 22 / a + 33 / a2 + ...... to n terms

import java.util.Scanner;

public class KboatSeries


{
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 n: ");
int n = in.nextInt();
double sum = 1.0;
for (int i = 2; i <= n; i++)
sum += Math.pow(i, i) / Math.pow(a, i - 1);
System.out.println("Sum = " + sum);
}
}
Output

(f) S = 12/a + 32 / a2 + 52 / a3 + ...... to n terms

import java.util.Scanner;

public class KboatSeries


{
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 n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 1, j = 1; i <= n; i++, j=j+2)
sum += Math.pow(j, 2) / Math.pow(a, i);
System.out.println("Sum = " + sum);
}
}
Output

(g) S = 1/a + 1/a2 + 1/a3 + ...... + 1/an

import java.util.Scanner;

public class KboatSeries


{
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 n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= n; i++)
sum += 1 / Math.pow(a, i);
System.out.println("Sum = " + sum);
}
}
Output

(h) S = x/2 + x/5 + x/8 + x/11 + ...... + x/20

import java.util.Scanner;

public class KboatSeries


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter x: ");
int x = in.nextInt();
double sum = 0.0;
for (int i = 2; i <= 20; i = i+3)
sum += (double)x / i;
System.out.println("Sum = " + sum);
}
}
Output

Question 13

In order to reach the top of a pole, a monkey in his first attempt reaches to a height of 5 feet
and in the subsequent jumps, he slips down by 2% of the height attained in the previous
jump. The process repeats and finally the monkey reaches the top of the pole. Write a
program to input height of the pole. Calculate and display the number of attempts the monkey
makes to reach the top of the pole.

import java.util.Scanner;

public class KboatMonkeyPole


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter height of the pole: ");
double poleHt = in.nextDouble();
double jumpHt = 5.0;
int numAttempts = 1;
while (jumpHt < poleHt) {
jumpHt += 5.0;
jumpHt -= 2 * jumpHt / 100.0;
numAttempts++;
}
System.out.println("Number of Attempts = " + numAttempts);
}
}
Output

Question 14

Write a program to input Principal (p), Rate (r) and Time (t). Calculate and display the
amount, which is compounded annually for each year by using the formula:
Simple Interest (si) = (prt) / 100
p = p + si
[Hint: The amount after each year is the Principal for the next year]

import java.util.Scanner;

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 Rate: ");
double r = in.nextDouble();
System.out.print("Enter Time: ");
int t = in.nextInt();
double amt = p;
for (int i = 1; i <= t; i++) {
double interest = (amt * r * 1) / 100.0;
amt += interest;
System.out.println("Amount after " + i
+ " year = " + amt);
}
}
}

Output

Question 15

Write a menu driven program to input two positive numbers m and n (where m>n) and
perform the following tasks:
(a) Find the sum of two numbers without using '+' operator.
(b) Find the product of two numbers without using '*' operator.
(c) Find the quotient and remainder of two numbers without using '/' and '%' operator.

[Hint: The last value obtained after each subtraction is the remainder and the number of
iterations results in quotient.]
Sample Input: m=5, n=2
5 - 2 =3
3 - 2 = 1, thus Quotient = 2 and Remainder = 1

import java.util.Scanner;

public class KboatNumberOperations


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Sum without '+' operator");
System.out.println("2. Product without '*' operator");
System.out.println("3. Quotient and Remainder without '/' &
'%' operators");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
System.out.print("Enter m: ");
int m = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();

if (m > n) {
switch (choice) {
case 1:
while (n > 0) {
m++;
n--;
}
System.out.println("Sum = " + m);
break;

case 2:
int p = 0;
while (n > 0) {
p += m;
n--;
}
System.out.println("Product = " + p);
break;

case 3:
int q = 0;
while (m >= n) {
m = m - n;
q++;
}
System.out.println("Quotient = " + q);
System.out.println("Remainder = " + m);
break;

default:
System.out.println("Incorrect Choice");
break;
}
}
else {
System.out.println("Invalid Inputs");
}
}
}
Output
Question 16

Write a menu driven class to accept a number from the user and check whether it is a
Palindrome or a Perfect number.
(a) Palindrome number: (A number is a Palindrome which when read in reverse order is same
as in the right order)
Example: 11, 101, 151 etc.
(b) Perfect number: (A number is called Perfect if it is equal to the sum of its factors other
than the number itself.)
Example: 6 = 1 + 2 + 3

import java.util.Scanner;

public class KboatPalinOrPerfect


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Palindrome number");
System.out.println("2. Perfect number");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
System.out.print("Enter number: ");
int num = in.nextInt();

switch (choice) {
case 1:
int copyNum = num;
int revNum = 0;

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

if (revNum == num)
System.out.println(num + " is palindrome");
else
System.out.println(num + " is not palindrome");
break;

case 2:
int sum = 0;

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


if (num % i == 0) {
sum += i;
}
}

if (num == sum)
System.out.println(num + " is a perfect number");
else
System.out.println(num + " is not a perfect
number");
break;

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

Question 17

Write a menu driven program to accept a number from the user and check whether it is a
Prime number or an Automorphic number.
(a) Prime number: (A number is said to be prime, if it is only divisible by 1 and itself)
Example: 3,5,7,11
(b) Automorphic number: (Automorphic number is the number which is contained in the last
digit(s) of its square.)
Example: 25 is an Automorphic number as its square is 625 and 25 is present as the last two
digits.
import java.util.Scanner;

public class KboatPrimeAutomorphic


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Prime number");
System.out.println("2. Automorphic number");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
System.out.print("Enter number: ");
int num = in.nextInt();

switch (choice) {
case 1:
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
if (c == 2)
System.out.println(num + " is Prime");
else
System.out.println(num + " is not Prime");
break;

case 2:
int numCopy = num;
int sq = num * num;
int d = 0;

/*
* Count the number of
* digits in num
*/
while(num > 0) {
d++;
num /= 10;
}

/*
* Extract the last d digits
* from square of num
*/
int ld = (int)(sq % Math.pow(10, d));

if (ld == numCopy)
System.out.println(numCopy + " is automorphic");
else
System.out.println(numCopy + " is not automorphic");
break;

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

Output
Question 18

Write a menu driven program to perform the following tasks by using Switch case statement:
(a) To print the series:
0, 3, 8, 15, 24, ............ to n terms. (value of 'n' is to be an input by the user)
(b) To find the sum of the series:
S = (1/2) + (3/4) + (5/6) + (7/8) + ........... + (19/20)

import java.util.Scanner;

public class KboatSeriesMenu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 to print series");
System.out.println("0, 3, 8, 15, 24,....to n terms");
System.out.println();
System.out.println("Type 2 to find sum of series");
System.out.println("(1/2) + (3/4) + (5/6) + (7/8) +....+
(19/20)");
System.out.println();
System.out.print("Enter your choice: ");
int choice = in.nextInt();

switch (choice) {
case 1:
System.out.print("Enter n: ");
int n = in.nextInt();
for (int i = 1; i <= n; i++)
System.out.print(((i * i) - 1) + " ");
System.out.println();
break;

case 2:
double sum = 0;
for (int i = 1; i <= 19; i = i + 2)
sum += i / (double)(i + 1);
System.out.println("Sum = " + sum);
break;

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

Output
Question 19

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.
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);
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 20

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 2 - digit
number" otherwise, display the message "Not a special two-digit number".

import java.util.Scanner;

public class KboatSpecialNumber


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

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 21

Using switch statement, write a menu driven program to:


(a) find and display all the factors of a number input by the user ( including 1 and the
excluding the number itself).
Example: Sample Input : n = 15
Sample Output : 1, 3, 5
(b) find and display the factorial of a number input by the user (the factorial of a non-negative
integer n, denoted by n!, is the product of all integers less than or equal to n.)
Example: Sample Input : n = 5
Sample Output : 5! = 1*2*3*4*5 = 120
For an incorrect choice, an appropriate error message should be displayed.
import java.util.Scanner;

public class KboatMenu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Factors of number");
System.out.println("2. Factorial of number");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
int num;

switch (choice) {
case 1:
System.out.print("Enter number: ");
num = in.nextInt();
for (int i = 1; i < num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
break;

case 2:
System.out.print("Enter number: ");
num = in.nextInt();
int f = 1;
for (int i = 1; i <= num; i++)
f *= i;
System.out.println("Factorial = " + f);
break;

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

Question 22

Write a program to input a number. Check and display whether it is a Niven number or not.
(A number is said to be Niven which is divisible by the sum of its digits).
Example: Sample Input 126
Sum of its digits = 1 + 2 + 6 = 9 and 126 is divisible by 9.
import java.util.Scanner;

public class KboatNivenNumber


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

int digitSum = 0;

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

/*
* digitSum != 0 check prevents
* division by zero error for the
* case when users gives the number
* 0 as input
*/
if (digitSum != 0 && orgNum % digitSum == 0)
System.out.println(orgNum + " is a Niven number");
else
System.out.println(orgNum + " is not a Niven number");
}
}
Output

Question 23

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 static void main(String args[]) {

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 24

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; where x = 2
(b) To display the series:
1, 11, 111, 1111, 11111
For an incorrect option, an appropriate error message should be displayed.

import java.util.Scanner;

public class KboatSeriesMenu


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

switch (choice) {
case 1:
int sum = 0;
for (int i = 1; i <= 20; i++) {
int term = (int)Math.pow(2, i);
if (i % 2 == 0)
sum -= term;
else
sum += term;
}
System.out.println("Sum=" + sum);
break;

case 2:
int term = 1;
for (int i = 1; i <= 5; i++) {
System.out.print(term + " ");
term = term * 10 + 1;
}
break;

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

Nested for Loops


Class 9 - APC Understanding Computer
Applications with BlueJ

Fill in the blanks

Question 1

A loop within another loop is called nested loops

Question 2

You can use break statement to terminate a loop block.

Question 3

Label is a tag that decides which of part the loop is to be used.

Question 4

Repetition of inner loop takes place before outer loop

Question 5

Continue statement will repeat a loop for next iteration after ignoring some statements of the
loop.

Write whether the following statements are True/False

Question 1

Loop is a repetitive structure.


True

Question 2

Nesting of loops means restricting the use of inner loop.


False
Question 3

When break statement is applied, it terminates the program completely.


False

Question 4

When outer loop completes its iterations, the inner loop starts. False

Question 5

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

Differentiate between the following

Question 1

Nested if and nested loop


Nested if is used to do conditional checks at multiple levels whereas nested loops are
used to execute one iterative set of statements inside another iterative set.

Question 2

Break and continue

1. break statement is used to unconditionally jump out of the loop whereas continue
statement is used to unconditionally jump to the next iteration of the loop, skipping the
remaining statements of the current iteration.
2. break statement is used in switch-case and loops whereas continue statement is only used
in loops.

Question 3

Labelled break and Unlabelled break


Labelled break can be used to exit out of a deeply nested set of loops whereas
Unlabelled break only exits from the loop within which it is enclosed.

Answer the following questions

Question 1

What do you mean by a nested loop?


When a loop is contained inside another loop it is termed as nested loops
Question 2

In what situation you need a nested loop?


When the repetition of two tasks depend on each other in such a way that for every
repetition of first task, the second tasks needs to be repeated a number of times, then we
use nested loops.

Question 3

How will you terminate outer loop from the block of the inner loop?
By using Labelled break statement.

Question 4

What do you mean by labelled break statement? Give an example.


Labelled break statement transfers program control out of the code block whose label is
specified as its target. The target code block must enclose the break statement but it
does not need to be the immediately enclosing block.
In the below code snippet:

first: for (int j = 1; j <= 5; j++) {


for (int k = 1; k <= j; k++) {
if (k > 4)
break first;
System.out.print(k);
}
System.out.println();
}
System.out.println("Outside code block labelled first");
the labelled break statement break first; will transfer the program control outside the
outer for loop to the statement System.out.println("Outside code block labelled
first");

Question 5

Write down the syntax of the nested loop.


Below is the syntax of nested loop:

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

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

executable statement(s)

}
Give the output of the following snippets based on nested
loops

Question 1

int i,j;
for (i=0; i<4; i++)
{
for (j=i; j>=0; j--)
System.out.print(j);
System.out.println();
}

Output

10

210

3210

Explanation

For each iteration of outer for loop, inner for loop will iterate from i to 0 printing the above
pattern.

Question 2

int y,p;
for (int x=1; x<=3; x++)
{
for (y=1; y<=2; y++)
{
p = x * y;
System.out.print(p);
}
System.out.println( );
}

Output

12

24

36
Explanation

x y p Remarks

1 1 1 1st iteration of outer for loop

2 2

2 1 2 2nd iteration of outer for loop

2 4

3 1 3 3rd iteration of outer for loop

2 6

Question 3

int a,b;
for (a=1; a<=2; a++)
{
for (b= (64+a); b<=70; b++)
System.out.print((char) b);
System.out.println( );
}

Output

ABCDEF

BCDEF

Explanation

In the first iteration of outer for loop, the inner for loop will print characters with ASCII
codes from 65 to 70 i.e. letters from A to F.
In the second iteration of outer for loop, the inner for loop will print characters with ASCII
codes from 66 to 70 i.e. letters from B to F.

Question 4

int x,y;
for(x=1; x<=5; x++)
{
for(y=1; y<x; y++)
{
if(x == 4)
break;
System.out.print(y);
}
System.out.println( );
}

Output

12

1234

Explanation

1st iteration of outer for


x=1
Inner for loop doesn't execute as y = 1 so the condition y<x is false
Just a newline is printed to the console due to System.out.println( );
2nd iteration of outer for
x=2
Inner for loop executes once printing 1 to the console

3rd iteration of outer for


x=3
Inner for loop executes twice printing 12 to the console

4th iteration of outer for


x=4
if(x == 4) becomes true inside inner for loop. break is executed, just a newline is printed to
the console.
5th iteration of outer for
x=5
Inner for loop executes 4 times printing 1234 to the console

Question 5

int i,j;
first:
for (i=10; i>=5; i--)
{
for (j= 5; j<=i; j++)
{
if (i*j <40)
continue first;
System.out.print(j);
}
System.out.println( );
}

Output

5678910

56789

5678

Explanation

For the first 3 iterations of outer loop i * j >= 40. After that as the condition of if (i*j
<40) becomes true, in each iteration of inner for, continue statement transfers the program
control to the next iteration of outer for loop.

Solutions to Unsolved Java Programs

Question 1

Write a program to display the Mathematical Table from 5 to 10 for 10 iterations in the given
format:
Sample Output: Table of 5
5*1 = 5
5*2 =10
--------
--------
5*10 = 50
public class KboatTables
{
public static void main(String args[]) {
for (int i = 5; i <= 10; i++) {
System.out.println("Table of " + i);
for (int j = 1; j <= 10; j++) {
System.out.println(i + "*" + j + " = " + (i*j));
}
}
}
}
Question 2

Write a program to accept any 20 numbers and display only those numbers which are prime.
Hint: A number is said to be prime if it is only divisible by 1 and the number itself.

import java.util.Scanner;

public class KboatPrimeCheck


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 20 numbers");
for (int i = 1; i <= 20; i++) {
int n = in.nextInt();
boolean isPrime = true;
for (int j = 2; j <= n / 2; j++) {
if (n % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println(n + " is a Prime Number");
}
}
}
Question 3

Write a program to compute and display the sum of the following series:
S = (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 static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 2; i <= n; i++) {
double num = 0.0, den = 1.0;
for (int j = 1; j <= i; j++) {
num += j;
den *= j;
}
sum = sum + (num / den);
}
System.out.println("Sum=" + sum);
}
}

Output

Question 4
Write two separate programs to generate the following patterns using iteration (loop)
statements:

(a)

*
* #
* # *
* # * #
* # * # *

public class KboatPattern


{
public static void main(String args[]) {
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

(b)
54321
5432
543
54
5

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 1; i <=5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

Output

Question 5

Write a program to calculate and display the factorials of all the numbers between 'm' and 'n'
(where m<n, m>0, n>0).
[Hint: factorial of 5 means: 5!=5*4*3*2*1]

import java.util.Scanner;

public class KboatFactRange


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

Scanner in = new Scanner(System.in);


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

if (m < n && m > 0 && n > 0) {


for (int i = m; i <= n; i++) {
long fact = 1;
for (int j = 1; j <= i; j++)
fact *= j;
System.out.println("Factorial of " + i + " = " +
fact);
}
}
else {
System.out.println("Invalid Input");
}

}
}

Output
Question 6

Write a menu driven program to display all prime and non-prime numbers from 1 to 100.
Enter 1: to display all prime numbers
Enter 2: to display all non-prime numbers
Hint: A number is said to be prime if it is only divisible by 1 and the number itself.

import java.util.Scanner;

public class KboatMenuPrime


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 1: to display all prime numbers");
System.out.println("Enter 2: to display all non-prime
numbers");
System.out.print("Enter your choice: ");
int choice = in.nextInt();

switch (choice) {
case 1:
for (int i = 2; i <= 100; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println(i);
}
break;

case 2:
System.out.println(1);
for (int i = 2; i <= 100; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (!isPrime)
System.out.println(i);
}
break;

default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 7
In an entrance examination, students have answered 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.

import java.util.Scanner;

public class KboatStudentMarks


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students: ");
int studentCount = in.nextInt();
double totalMarks = 0.0;

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


System.out.println("Enter details of student " + i);
System.out.print("Name: ");
in.nextLine();
String name = in.nextLine();
System.out.print("Marks in English: ");
int engMarks = in.nextInt();
System.out.print("Marks in Science: ");
int sciMarks = in.nextInt();
System.out.print("Marks in Maths: ");
int mathsMarks = in.nextInt();
double avgMarks = (engMarks + sciMarks + mathsMarks) /
3.0;
totalMarks += avgMarks;
System.out.println("Average marks of " + name + " = " +
avgMarks);
}

double classAvg = totalMarks / studentCount;


System.out.println("Class Average = " + classAvg);
}
}
Output

Question 8

Write a program to input a number and perform the following tasks:


(a) to check whether it is a prime number or not
(b) to reverse the number
If the number as well as the reverse is also 'Prime' then display 'Twisted Prime' otherwise
'Not a twisted Prime'.
Sample Input: 167
Sample Output: 167 and 761 both are prime.
It is a 'Twisted Prime'.

import java.util.Scanner;

public class KboatTwistedPrime


{
public static void main(String args[]) {
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 9

Write programs to find the sum of the given series:

(a) 1 + (1/2!) + (1/3!) + (1/4!) + .......... + (1/n!)

import java.util.Scanner;

public class KboatSeriesSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= n; i++) {
long f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
sum += (1.0 / f);
}
System.out.println("Sum=" + sum);
}
}
Output

(b) 1 + (1+2) + (1+2+3) + .......... + (1+2+3+ ...... + n)

import java.util.Scanner;

public class KboatSeriesSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
long sum = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
sum += j;
}
}
System.out.println("Sum=" + sum);
}
}
Output

(c) 1 + (1*2) + (1*2*3) + .......... + (1*2*3* ...... * n)

import java.util.Scanner;

public class KboatSeriesSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
long sum = 0;
for (int i = 1; i <= n; i++) {
int p = 1;
for (int j = 1; j <= i; j++) {
p *= j;
}
sum += p;
}
System.out.println("Sum=" + sum);
}
}
Output

(d) 1 + 1 / (1+2) + 1 / (1+2+3) + .......... + 1 / (1+2+3+.....+n)

import java.util.Scanner;

public class KboatSeriesSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= n; i++) {
long term = 0;
for (int j = 1; j <= i; j++) {
term += j;
}
sum += (1.0 / term);
}
System.out.println("Sum=" + sum);
}
}
Output

(e) (1/2) + (1/3) + (1/5) + (1/7) + (1/11) + .......... + (1/29)

public class KboatSeriesSum


{
public static void main(String args[]) {
double sum = 0.0;
for (int i = 2; i < 30; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
sum += 1.0 / i;
}
System.out.println("Sum=" + sum);
}
}
Output

Question 10

Write the programs in Java to display the following patterns:

(a)

1
21
321
4321
54321

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 1; i <= 5; i++) {
for (int j = i; j >= 1; j--) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(b)

12345
1234
123
12
1

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(c)

54321
5432
543
54
5

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(d)

13579
1357
135
13
1

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = 1; j <= i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(e)

5
54
543
5432
54321

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 5; i >= 1; i--) {
for (int j = 5; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(f)

12345
2345
345
45
5

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 1; i <= 5; i++) {
for (int j = i; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(g)

99999
77777
55555
33333
11111

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = 1; j <= 5; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
Output

(h)

9
79
579
3579
13579

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = i; j <= 9; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(i)

9
97
975
9753
97531

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = 9; j >= i; j -= 2) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output

(j)

1
23
456
7 8 9 10
11 12 13 14 15

public class KboatPattern


{
public static void main(String args[]) {
int term = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(term++ + " ");
}
System.out.println();
}
}
}
Output
Chapter 11

More on Basic Input/Output


Class 9 - APC Understanding Computer
Applications with BlueJ

Fill in the blanks

Question 1

JDK1.5 allows a special class to input from the console. This class is termed
as Scanner class.

Question 2

java.util package is necessary to be imported in order to use scanner class.

Question 3

Token is a set of characters separated by delimiters.

Question 4

The default delimiter used in scanner object is whitespace.

Question 5

System.in receives the input from the keyboard for the scanner object.

Question 6

Method next() can be used to accept a token from scanner object.

Question 7

nextInt() method reads a token as an integer.

Question 8

The method which checks whether the next token of the scanner object is a floating type
value or not is hasNextFloat().
Question 9

hasNextBoolean() is the method used to check whether the next token is a boolean type
value or not.

Question 10

Any number of objects can be input into a scanner object.

Write TRUE or FALSE

Question 1

Scanner class is a useful package of JDK 1.5.


False

Question 2

Strings can even be input without using scanner object.


True

Question 3

The word 'new' is a keyword to create any object.


True

Question 4

You need not be aware about the number of tokens to be input to a scanner object.
True

Question 5

You can terminate a string even by using carriage return.


True

Question 6

nextFloat can also accept an integer token.


True

Question 7

hasNextInt( ) results in true if the next token can be interpreted as an integer.


True
Question 8

nextlnt() can be used to accept an exponential value.


False

Answer the following

Question 1

What do you mean by scanner class?


Scanner class is used to get user input in Java. It is defined in java.util package.

Question 2

Write syntax along with an example to create a scanner object.

Syntax

Scanner = new Scanner(System.in);

Example

Scanner in = new Scanner(System.in);

Question 3

Mention the syntax to use '?' as a token delimiter.


in.useDelimiter("\\?");
Here, 'in' is the Scanner class object

Question 4

Write down the use of nextInt() method.


It reads the next token entered by the user as an int value.

Question 5

What is the application of hasNextBoolean( ) method?


Returns true if the next token in the Scanner's input can be interpreted as a boolean
value, otherwise it returns false.

Question 6

Name the package which can be imported to allow the use of scanner class.
java.util
Question 7

In what way can the following data be read from the scanner object?

(a) Integer type


int a = in.nextInt();

(b) Float type


float b = in.nextFloat();

(c) Double type


double c = in.nextDouble();

(d) String type


String str = in.nextLine();

(e) Boolean type


boolean d = in.nextBoolean();

Differentiate between the following

Question 1

Scanner object and BufferedReader object

Scanner object BufferedReader object

Scanner class parses the tokens into specific types like BufferedReader just reads the stream and does
short, int, float, boolean, etc. not do any special parsing.

It is slower than BufferedReader. It is faster than Scanner.

It was introduced in JDK1.5 It was introduced in JDK1.1

Question 2

nextFloat( ) and nextDouble( )

nextFloat( ) nextDouble( )

It reads the next token entered by the user as a It reads the next token entered by the user as a
float value. double value.
Question 3

next( ) and nextLine( )

next( ) nextLine( )

It reads the next complete token from the Scanner It reads the complete line from the Scanner
object. object.

Question 4

hasNext( ) and hasNextLine( )

hasNext( ) hasNextLine( )

Returns true if the Scanner object has another Returns true if there is another line in the input of
token in its input. the Scanner object.

Question 5

hasNextInt( ) and hasNextBoolean( )

hasNextInt( ) hasNextBoolean( )

Returns true if the next token in the Scanner's input


Returns true if the next token in the Scanner's
can be interpreted as an int value using the nextInt()
input can be interpreted as a boolean value.
method.
Solutions to Unsolved Java Programs

Question 1

Using scanner class, write a program to input temperatures recorded in different cities in °F
(Fahrenheit). Convert and print each temperature in °C (Celsius). The program terminates
when user enters a non-numeric character.

import java.util.Scanner;
public class KboatTemperatureConvert
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Temperature in Fahrenheit: ");
while (in.hasNextDouble()) {
double t = in.nextDouble();
double ct = 5 / 9.0 * (t - 32);
System.out.println("Temperature in Celsius: " + ct);
System.out.print("Enter Temperature in Fahrenheit: ");
}
}
}

Output

Question 2

Write a program to accept a set of 50 integers. Find and print the greatest and the smallest
numbers by using scanner class method.

import java.util.Scanner;

public class KboatSmallLargeNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 50 integers:");
int small = Integer.MAX_VALUE, big = Integer.MIN_VALUE;
for (int i = 1; i <= 50; i++) {
int n = in.nextInt();
if (n > big)
big = n;

if (n < small)
small = n;
}
System.out.println("Smallest Number = " + small);
System.out.println("Largest Number = " + big);
}
}

Output
Question 3

Write a program (using scanner class) to generate a pattern of a token in the form of a triangle
or in the form of an inverted triangle depending upon the user's choice.

Sample Input/Output:
Enter your choice 1
*
**
***
****
*****
Enter your choice 2
*****
****
***
**
*

import java.util.Scanner;

public class KboatPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Triangle");
System.out.println("2. Inverted Triangle");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
switch (choice) {
case 1:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
break;
case 2:
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
break;

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

You might also like