[go: up one dir, main page]

0% found this document useful (0 votes)
47 views128 pages

Computer App With BlueJ-cl9

Fhj

Uploaded by

suguraghu79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views128 pages

Computer App With BlueJ-cl9

Fhj

Uploaded by

suguraghu79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

Understanding ICSE

Computer Applications With Blue J

Class IX
Contents
Chapter 1
Introduction to Object Oriented
Programming Concepts

Topic I: Principles of Object Oriented Programming


III. Name the following:
1. Two categories of Low Level languages
Ans. (a) Assembly Language (b) Machine Language
2. Two Procedure Oriented Languages
Ans. (a) BASIC (b) COBOL
3. Two structure oriented programming languages
Ans. (a) PASCAL (b) ALGOL
4. Two examples of data abstraction in your daily life
Ans. (a) Clicking photos in a camera (b) ATM
5. Two examples of real world objects
Ans. (a) Television (b) Car
6. Two basic principles of Object Oriented Programming
Ans. (a) Encapsulation (b) Inheritance
IV. Write short notes with an example (if applicable)
1. Object Oriented Programming
Ans. 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.
2. Data Abstraction
Ans. Data abstraction is the act of representing the essential features without
knowing the background details.
For example, Driving a car
3. Encapsulation
Ans. Wrapping of data and functions that operate on that data into a single
unit is called Encapsulation.
4. Machine Language
Ans. It is the form of computer language in which instructions are coded in
terms of binary digits (bits), i.e., in the form of zeroes and ones (0s and
1s). This form of binary instructions is also called the machine code or
the object code. The computer understands the machine code easily (i.e.,
it does not need to be transformed or converted into any other form).
The only advantage of this language is that the program executes faster
because the machine code is directly understood by the processor.
5. Polymorphism
Ans. In object oriented programming, polymorphism provides the means to
perform a single action in multiple different ways.

1
6. Procedure Oriented Programming
Ans. Procedure Oriented Programming basically consists of a list of instructions
for the computer to follow and these are organised 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.
7. Inheritance
Ans. The term 'Inheritance' means to link and share some common properties
of one class with the other class. This can be done by extending a class
into another class and thus using both of them.
8. Assembly Language
Ans. In assembly language, the instructions are written more in English like
words knowns as mnemonics. These instructions are not understood
by the processor directly. They are converted into equivalent machine
code through a translator program called Assembler. Assembly language
is machine dependent that makes it unsuitable for writing portable
programs that can execute across machines.
V. Distinguish between:
1. Object Oriented Programming and Procedure Oriented Programming
Ans. Object Oriented Programming Procedure Oriented
Programming
The stress is put on data rather than The stress is put on function rather
functions. than data.
The data is restricted and used in a It allows data to flow freely
specific program area. throughout the program.
It follows bottom-top programming It follows top-down programming
approach. approach.

2. High Level language and Low Level language


Ans. High Level language Low Level language
It is machine independent. It is machine dependent.
It needs a compiler or an interpreter It might need an assembler for
for translation to machine code. translation to machine code.
Programs written in high level Programs written in low level
language are easier to modify and language are hard to modify and
debug. debug.

3. Compiler and Interpreter


Ans. Compiler Interpreter
It converts the whole source It converts the source program into
program into the object program the object program line by line.
at once.
After the compilation, it displays It displays the errors, one line at a
the errors for the whole program time and only after fixing that error
at once. the control goes to the next line.

VI. Answer the following questions:


1. Enlist the features of Object Oriented Programming.
Ans. Some of the features of Object Oriented Programming are:
• It gives stress on data items rather than functions.
• It makes the complete program/problem simpler by dividing it into
a number of objects.
• The objects can be used as a bridge to have data flow from one function
to another.
• The concept of data hiding enhances security in programs.
• It is highly beneficial to solve complex programs.
2. Which OOP principle implements function overloading? Explain
Ans. Polymorphism implements function overloading. It is the process of
using a function/a 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 the
tasks.
3. Write three benefits of Object Oriented Programming.
Ans. Three benefits of Object Oriented Programming are:
• The reusability of the program code is enhanced.
• Data abstraction makes the software easier to handle.
• Software for complex tasks can be easily developed.
4. Mention two limitations of:
(a) Procedure Oriented Programming
Ans. (i) The data values are global to all the functions. So, you may require
to make necessary changes in all the functions, in case of any change
in the data values.
(ii) It is not suitable to solve complex problems in real situations.
(b) Object Oriented Programming
Ans. (i) It requires intensive testing processes.
(ii) It takes more time to solve a problem as compared to Procedure
Oriented Programming.
5. How is Encapsulation useful in Object Oriented Programming? Explain
Ans. 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. In this way, encapsulation helps in protecting the data from
unauthorised access.
6. What are the advantages of High Level languages?
Ans. The advantages of High Level languages are:
• High level languages are machine independent.
• High level languages are human readable as instructions are written
using English like words and phrases.

Introduction to Object Oriented Programming Concepts 3


• It is easier to understand and develop the program logic in high level
languages.
• The error detection and correction is easier.

Topic 2: Introduction to Java


III. Answer the following questions:
1. Who developed Java? What was it initially called?
Ans. James Gosling developed Java programming language. It was
initially called Oak.
2. Give a brief historical development of Java.
Ans. In 1991, at Sun Microsystems, Green team led by James Gosling started
working on a new technology for consumer electronic devices. In 1992,
the team created a new programming language called 'Oak' (the name
of a tree outside Gosling's office). But, the Oak didn't find much suitable
and renamed to Java in 1995.
3. Mention at least four features of Java.
Ans. The four features of Java are:
• It is an object oriented programming language.
• It is case sensitive.
• It is platform independent.
• It uses a compiler as well as an interpreter.
4. Define the following:
(a) A compiler
Ans. A compiler is a program that translates a source program written in
high level programming language to a low level programming language
without changing the meaning of the program. It processes the complete
source program at once and if, there are compilation errors, they are all
reported at once.
(b) An interpreter
Ans. An interpreter is a program that reads a source program line by line and
converts each line into its equivalent machine code and executes it. As
it reads the program line by line and so the errors are also reported one
by one.
(c) Byte code
Ans. Java compiler converts Java source code into an intermediate binary
code called byte code. The byte code is a common binary form of the
program and works irrespective of the machine on which it is to be
executed. Further, Java interpreter accepts the byte code and converts
it into machine code suitable to the specific platform.
5. What is Java Virtual Machine (JVM)?
Ans. Java Virtual Machine (JVM) is a software that takes byte code as input and
converts it into machine code of the specific platform for its execution.
6. Name three packages of Java Class Library.
Ans. The three packages of Java Class Library are:
(i) java.lang
(ii) java.io
(iii) java.util
7. What are Java reserved words? Name any five.
Ans. Java reserved words are the keywords that have special meaning in the
language.
Due to this, these words can not be used as names for variables, methods,
classes or any other identifier.
The five commonly used Java reserved words are:
(i) public (ii) void
(iii) int (iv) double
(v) char
8. Distinguish between:
(a) Source code and Object code
Source code Object code
It is a set of statements written It is a set of statements written in
in a high level programming machine language.
language.
It is understood by human/ It is understood by the processor.
programmer.

(b) Compiler and Interpreter


Compiler Interpreter
It translates the whole source It translates the source program
program into object program at into object program one line at a
once. time.
All the errors found during Errors are displayed line by line
the compilation are displayed as each line is translated and
together. executed.

(c) JDK 1.3 and BlueJ


JDK 1.3 BlueJ
JDK or Java Development Kit BlueJ is an Integrated
is the set of tools required to Development Environment for
compile and run Java programs. developing Java programs.
It provides a DOS based It is a Window based environment
environment to compile and run to compile and run the Java
Java programs. programs.

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


Ans. A compiler translates a source program written in a high level
programming language into an object program (low level programming
language). It means that the compiler designed for Java programming

Introduction to Object Oriented Programming Concepts 5


language is specific to compilation and execution of Java language only. It
must be noted that each language needs a specific language translator to
perform the task. So, we can say that a compiler is specific to a language.
10. What is the basic format of a Java Program? ExplainDewcliatrhatai onn oefx a mple.
Ans. The basic format of a Java program: main function
// .........................comment of the program
public class <name of the class>
{
1 public static void main (String args[ ])
{
2 ……………………………………
Java statements
…………………………………..
<Java output statement>
}
}
1: Opening and closing of a class
2: Opening and closing of main function
11. What is BlueJ?
Ans. BlueJ is an integrated development environment for Java programming
language that runs with the help of JDK. It is especially designed for the
beginners to learn Java programming.
12. Mention five features of BlueJ.
Ans. Five features of BlueJ are:
(i) It is a graphical user interface to write and execute Java programs.
(ii) It allows creating objects of the class dynamically and invoking their
methods.
(iii) It highlights the different tokens of the program like keywords,
variables, data types, etc. in different colours.
(iv) It facilitates easier debugging.
13. Name a package that is invoked by default.
Ans. java.lang
14. What are the points to be taken care while naming a class in a Java
program?
Ans. (i) The class name must not be a Java reserved word.
(ii) As far as possible, the class name should be meaningful and relevant
to the program.
(iii) Name of the class may be a sequence of letters or the combinations
of letters and digits.
(iv) Use underscore, if class name is to be given using two different
words.
For example, Emp_Salary, Prime_Number, etc.
(v) The class name should not start with a digit.
15. Java is a case sensitive language. Explain.
Ans. Java is case sensitive means that it distinguishes between uppercase and
lowercase characters.
For example,
int num;
Num = 85;
It will give a compilation error because Java will treat num and Num as
two different variables.
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?
Ans. public : The keyword 'public' is an access specifier. It controls the visibility
of class members.
static : We make the main method static Java Virtual Machine (JVM)
will call to start the program even without creating any objects
of the class.
void : The keyword 'void' tells the compiler that the main method will
not return any value.
17. What does the term 'Compilation' mean?
Ans. The process of converting a source program written in a high level
programming language into an object program (machine language)
without changing the meaning of the program is called compilation.
18. A Java program uses compiler as well as interpreter. Explain.
Ans. Java compiler compiles Java source code to Bytecode. However,
this Bytecode can not run on the processor directly as the processor
understands only machine mode. 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 the program executed.
19. Design a program in Java to display the following information on the
output screen:
Name: ………………………………………
Class: ………………………………………
Roll No.: ………………………………………
Subject:
School:
Ans. public class Student
{
public static void main(String args[ ])
{
System.out.println("Name: Saket Jain ");
System.out.println("Class: IX");
System.out.println("Roll No.: 35");
System.out.println("Subject: Computer Applications");
System.out.println("School: Delhi Public School");
}
}
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:

Introduction to Object Oriented Programming Concepts 7


Name : ……………………………………………
Father's Name : ……………………………………………
Date of birth : ……………………………………………
Blood Group : ……………………………………………
Aadhar Card No. : ……………………………………………
State : ……………………………………………
Ans. public class BioData
{
public static void main(String args[ ])
{
System.out.println("Name: Mayank Kumar");
System.out.println("Father's Name: Abhijeet Mishra");
System.out.println("Date of birth: 12/10/2006");
System.out.println("Blood Group: O+");
System.out.println("Aadhar Card No.: **** **** ****");
System.out.println("State: Uttar Pradesh");
}
}
Chapter 2

Elementary Concept of Objects and Classes

II. Answer the following Questions:


1. Define an Object with an example.
Ans. An object is a fundamental unit of Object Oriented Programming and
represents the real life entities. They are the basic elements of the Object
Oriented system and are also known as the Entities. Each real world
object contains some characteristics and behaviour.
For example, Taking a car as an object.
It has characteristics like colour, model, registration number, etc. It has
behaviours like start the engine, stop the engine, accelerate the car, apply
the brakes, etc.
2. Mention five states (characteristics) and two methods for the following
classes:
(a) class Employee
Ans. Characteristics Methods
Name Cal_Salary( )
Employee Number Cal_Tax( )
Pan Number
Salary
Income Tax
(b) class Bank
Ans. Characteristics Methods
Bank Name Open_Account( )
Branch Deposit( )
Bank Address
IFSC Code
MICR Code
(c) class School
Ans. Characteristics Methods
Name Admission( )
Address Exams( )
Affiliation
Students
Teachers

9
(d) class Book
Ans. Characteristics Methods
Name Input( )
ISBN Number Read( )
Price
Author
Publisher
(e) class Park
Ans. Characteristics Methods
Name OpenPark( )
Address ClosePark( )
ENtry
Opening Time
Closing Time
(f) class Medicine
Ans. Characteristics Methods
Name Purchase( )
Quantity Sell( )
Price
Manufacturing Date
Expiry Date
(g) class Computer
Ans. Characteristics Methods
Company Input( )
Model Display( )
Processor
RAM
Hard Disk
(h) class Camera
Ans. Characteristics Methods
Company Input( )
Model Display( )
Serial Number
Price
Resolution
3. What is an Object? Give five examples of real world objects.
Ans. An object is an entity having some specific characteristics and specific
behaviour.
For example, car, mobile phone, computer, student, camera, etc.
4. How will you define a software object?
Ans. A software object replaces the characteristics and behaviours of a real
world object with data members and member methods respectively.
5. Class and objects are inter-related. Explain.
Ans. A class is used to create various objects having different characteristics
and common behaviours. Further, each object follows all the features
defined within a class. This is why class is also referred to as a blue print or
prototype of an object. In this way, we can say that they are inter-related.
6. A class is also referred to as 'Object Factory'. Comment.
Ans. A class can create objects with different characteristics and common
behaviour just like a factory where it produces similar items (objects)
based on a particular design (class). Hence, class is also referred to as
'Object Factory'.
7. What does the following statement mean?
Employee staff = new Employee ( );
Ans. This statement means that the staff is an object created of class Employee.
Further, this object of the class 'Employee' will possess different
characteristics but will have common behaviour.
8. Why is an object called an 'Instance' of a class? Explain.
Ans. The data members declared within a class are also known as instance
variables.
When an object of a class is created, it includes instance variables
described within the class. This is the reason why an object is called as
an instance of a class.
9. Why is a class known as composite data type?
Ans. When the user creates a class, it becomes a data type for his/her program.
Thus, class is referred to as a user defined data type. This data type
includes different primitive data types such as int, float, char, etc. Hence,
it is also said to be composite data type.
10. Write a statement to create an object 'Keyboard' of the class 'Computer'.
Ans. Computer Keyboard = new Computer( );
11. Consider a real world object as 'Cricket Ball'. Now, mention two behaviour
and methods each by taking the 'Cricket Ball' as a software Object.
Ans. Behaviour : colour, weight
Methods : Throw( ), Display( )
12. Refer the class structure as shown below:
class MySchool
{
Name
Address
Principal's name

Elementary Concept of Objects and Classes 11


AcceptData( );
PrintData( );
}
With reference to the above class declaration, indicate whether the
following statements are True/False:
Ans. (i) Acceptdata( ) is the characteristic of the class.
False
(ii) Address is behaviour of the class.
False
(iii) Acceptdata( ) and PrintData( ) are the common behaviour of the
objects of class 'MySchool'.
True
(iv) Behaviour is the medium of inter-object communication.
True
(v) Creating multiple objects of class 'MySchool' is not possible.
False
13. You want to create a class 'Football'. Choose the elements to be used as
characteristics and behaviour from the list given below:
Ball, Goalkeeper, Making a goal, Defender, Forward player, Passing ball,
Referee, Hitting corner, Making fault
Ans. Characteristics Behaviour
Ball Making a goal
Goalkeeper Passing ball
Defender Hitting corner
Forward player Making fault
Referee

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( ) to enable the task.
Ans. class Picnic
{
public void display1( )
{
System.out.println("Venue: Dimna Lake");
System.out.println("Place: Jamshedpur");
System.out.println("Reporting Time: 9:00 am");
}
public void display2( )
{
System.out.println("Number of students: 50");
System.out.println("Name of the teacher: Mr. Abhinandan Kishore");
System.out.println("Bus Number: JH 05 DH 2445");
}
public static void main(String args[ ])
{
Picnic ob = new Picnic( );
ob.display1( );
ob.display2( );
}
}

Elementary Concept of Objects and Classes 13


Chapter 3

Values and Data Types

III. Write short answers:


1. What do you mean by data type?
Ans. In Java, the data type refers to as the classification that specifies to
identify the type of data a memory location can hold and the associated
operations applied to it without causing an error.
2. Define variable with an example.
Ans. A variable represents a memory location through a symbolic name which
holds a value of a particular data type. This name of the variable is used
in the program to refer to the stored value.
For example,
int marks = 95;
3. What do you mean by constant? Explain with an example.
Ans. In a Java program, there are some quantities which remain fixed (i.e. do
not change) throughout the execution of the program. Such quantities
are termed as Literals or Constants.
For example,
int num = 45;
variable constant

4. State two kinds of data types.


Ans. Two kinds of data types are:
(i) Primitive Data type
(ii) Non-Primitive Data type
5. What do you understand by Token? Name different types of tokens.
Ans. A token is the smallest element of a program that is meaningful to the
compiler.
The different types of tokens in Java are:
• Identifiers
• Literals
• Operators
• Separators
• Keywords
6. What are the rules to assign a variable in a Java programming?
Ans. The rules to assign a variable in a Java programming are:
(i) Name of the variable should be a sequence of letters, digits,
underscore, etc.
(ii) It should not start with a digit.
(iii) It should not be a keyword or a boolean literal.
(iv) The underscore can be used in between the characters to separate
the words of a variable name.

14
7. Explain the term 'type casting'?
Ans. The process of converting one pre-defined data type into another after
the user's intervention, is called type casting.
8. Perform the following:
Ans. (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 3 (1.732) to a variable with the requisite data type.
double x = 1.732;
9. Distinguish between:
Ans. (a) Integer and floating constant
Integer Constant Floating Constant
Integer constants represent whole Floating constants represent
number values like 2, –16, 18246, fractional numbers like 3.14159,
24041973, etc. –14.08, 42.0, 675.238, etc.
Integer constants are assigned Floating constants are assigned
to variables of data type such as to variables of data type such as
byte, short, int, long, char. float, double.
(b) Token and Identifier
Token Identifier
A token is the smallest element of Identifiers are used to name
a program that is meaningful to things like classes, objects,
the compiler. variables, arrays, etc.
Tokens in Java are categorised Identifier is a type of token in
into various types such as Java.
Keywords, Identifiers, Literals,
Operators, etc.
(c) Character and String constant
Character Constant String Constant
These constants are written by They are written by enclosing a
enclosing a character within a set of characters within a pair of
pair of single quotes. double quotes.
Character constants are assigned String constants are assigned to
to variables of type char. variables of type String.
(d) Character and Boolean literal
Character Literal Boolean Literal
Character literals are written by A boolean literal can take only
enclosing a character within a one of the two boolean values
pair of single quotes. represented by the words true or
false.
Character literals can be assigned Boolean literals can only be
to variables of any numeric data assigned to variables declared as
type such as byte, short, int, boolean.
double, char, etc.

Values and Data Types 15


10. Write down the data type of the following:
Ans. (a) Integer : int
(b) Long Integer : long
(c) A fractional number : double
(d) A special character : char
11. What do you understand by Boolean data type? Explain with an example.
Ans. A boolean data type is used to store one of the two boolean values i.e.,
true or false. The size of boolean data type is 8 bits or 1 byte.For example,
boolean temp = false;
12. What do you understand by primitive data type? Give two examples.
Ans. Primitive data types are the basic or fundamental data types used to
declare a variable.
For example, int, float
13. Why is it necessary to define data types in Java programming?
Ans. Data types tells Java how much memory it should reserve for storing
the value.
It also helps in preventing errors during compilation of programs.
14. Define the following with an example each:
Ans. (a) Implicit type conversion
When the result of a mixed mode expression is obtained in the higher
most data type of the variables without any intervention by the user,
it is called implicit type conversion.
For example,
int a = 10; float b = 25.5f, float 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; int c = (int)(a + b);
15. Define 'Coercion' with reference to type conversion.
Ans. 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.
For example,
byte a = 42; int b = 50000; int result = a + b;
16. What do you mean by type conversion? How is implicit conversion
different from explicit conversion?
Ans. The process of converting of one pre-defined data 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. Whereas, in an explicit
type conversion, the data gets converted to a type as specified by the
programmer.
17. In what way is static declaration different from dynamic declaration?
Ans. In static declaration, the initial value of the variable is provided as a
literal at the time of declaration.
For example,
int num = 85; double p = 24.46535; 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. This declaration happens
at runtime.
For example:
int a = 4;
double ans = Math.sqrt(a);
18. What do you mean by non-primitive data type? Give examples.
Ans. A non-primitive data type is one that is derived from primitive data
types. When a number of primitive data types are used together, it
represents a non-primitive data type. For example, class and array.
19. Predict the return data type of the following:
(i) int p; double q;
r = p+q;
System.out.println(r);
Ans. double
(ii) float m;
p = m/3*(Math.pow(4,3));
System.out.println(p);
Ans. double
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;
Ans. i + c/b;
⇒ int + char / byte
⇒ int + char
⇒ int
(b) f/d + c*f;
Ans. f/d + c*f;
⇒ float / double + char * float
⇒ double + float
⇒ double
(c) i + f – b*c;
Ans. i + f – b*c;
⇒ int + float – byte * char
⇒ int + float – char
⇒ float – char
⇒ float
(d) (f/i)*c + b;
Ans. (f/i)*c + b;
⇒ (float / int) * char + byte
⇒ float * char + byte
⇒ float + byte
⇒ float

Values and Data Types 17


(e) i + f – c + b/d;
Ans. 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;
Ans. i/c + f/b
⇒ int / char + float / byte
⇒ int + float
⇒ float
Chapter 4

Operators in Java

III. Answer the following Questions:


1. What is an operator?
Ans. An operator is a symbol or sign used to specify an operation to be
performed in Java programming.
2. Name the different types of operators.
Ans. The different types of operators are Arithmetical, Logical and Relational.
3. Explain the following:
(a) Arithmetical operator
Ans. Arithmetic operators are used to perform mathematical operations on its
operands and the operands of arithmetic operators must be of numeric
type.
The arithmetic operators can operate upon one operand and two operands.
(b) Relational operator
Ans. Relational operators are used to determine the relationship between
the operands. They 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 or not.
For example,
int a = 8;
int b = 10;
boolean c = a < b;
It will result in true.
(c) Logical operator
Ans. Logical operators operate on boolean expressions to combine the results
of these boolean expressions into a single boolean value.
For example,
int a = 7;
int b = 10;
boolean c = (a < b) && (a % 2) == 0;
Here, the boolean variable c will result in false.
(d) Unary operator
Ans. Operators that act on one operand are called as Unary operators.
For example, unary +, unary –, unary increment (++), unary decrement
(– –), etc.
(e) New operator
Ans. The new operator is used to instantiate an object dynamically to allocate
memory for it.
(f) dot operator
Ans. The dot operator facilitates invoking members of the class to carry out
the tasks.
For example,
import java.util.*;

19
4. What is a Ternary operator? Explain with the help of an example.
Ans. Ternary operators deal with three operands and evaluates the condition.
Syntax: variable = (test expression)? Expression 1: Expression 2;
If the condition is true then the result of ternary operator is the value of
expression 1. Otherwise, the result is the value of expression 2.
For example,
int a = 5; int b = 3;
int Max = (a>b)? a : b;
Here, the value 5 is stored in Max, as a>b is true.
5. Differentiate between the following:
Ans. (a) Arithmetical operator and Logical operator
Arithmetical Operator Logical Operator
Arithmetic operators are used They operate on boolean
to perform mathematical expressions to combine the results
operations. into a single boolean value.
It results in int, float, double data It results in true or false.
types.
(b) Binary operator and Ternary operator
Binary operator Ternary operator
Binary operators work on two Ternary operators work on three
operands. operands.
It is an arithmetical operator. It is a conditional operator.

(c) Logical AND (&&) and Logical OR(||)


Logical AND Logical OR
It evaluates to true, only if both of It evaluates to true, if one or both
its operands are true. of its operands are true.
It is represented by the symbol It is represented by the symbol
(&&). (||).

(d) Prefix operator and Postfix operator


Prefix Operator Postfix Operator
It works on the principle of It works on the principle of USE-
CHANGE-THEN-USE. THEN-CHANGE.
It is written before the operand. It is written after the operand.

(e) System.out.print( ) and System.out.println( )


System.out.print( ) System.out.println( )
It prints data but the cursor It prints data and places the
remains at the end of the data in cursor in the next line.
the same line.
Next printing takes place from the Next printing takes place from the
same line. next line.
6. Differentiate between an operator and an expression.
Ans. An operator is a symbol or a 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).
7. If m=5 and n=2 then what will be the output of m and n after execution
of the following statements
(a) m –= n;
Ans. m –= n
⇒m=m–n
⇒m=5–2
⇒m=3
(b) n = m + m/n;
Ans. n = m + m/n
⇒n=5+5/2
⇒n=5+2
⇒n=7
8. State the difference between = and ==.
Ans. = ==
It is the assignment operator used It is the equality operator used
for assigning a value to a variable. to check, if a variable is equal to
another variable or literal.
For example, int a = 10; For example, if (a == 10)
It assigns 10 to variable a. It checks whether the variable a is
equal to 10 or not.
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
10. What will be the output of the following?
if x =5
(a) 5* ++x;
Ans. 5 * ++x ⇒5*6
⇒ 30
(b) 5* x++;
Ans. 5 * x++
⇒5*5
⇒ 25
11. Evaluate the following expressions, if the values of the variables are:
a = 2, b = 3, and c = 9
(a) a – (b++) * (– –c);
Ans. a – (b++) * (– –c)
⇒2–3*8
⇒2–3*8
⇒ 2 – 24
⇒ –22

Operators in Java 21
(b) a * (++b) % c;
Ans. a * (++b) % c
⇒ a * (++b) % c
⇒ 2 * (4) % 9
⇒8%9
⇒8
12. If a = 5, b = 9, calculate the value of:
a += a++ – ++b + a;
Ans. a += a++ – ++b + a
⇒ a = a + (a++ – ++b + a)
⇒ a = 5 + (5 – 10 + 6)
⇒a=5+1
⇒a=6
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
14. Rewrite the following using ternary operator.
(a) if(income<=100000)
tax = 0;
else
tax = (0.1*income);
Ans. tax = income <= 100000 ? 0 : (0.1*income);
(b) if(p>5000)
d = p*5/100;
else
d = p*2/100;
Ans. d = p > 5000 ? p * 5 / 100 : p * 2 / 100;
IV. Unsolved Java Programs
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
Prog. public class Expression
{
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);
}
}
(b) a2 + b2 + c2 / abc; taking the values a=5, b=4,c=3
Prog. public class Expression
{
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);
}
}
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.
Prog. public class Salary
{
public static void main(String args[ ])
{
int salary = 25 * 350;
int fine = 5 * 30;
int netSalary = salary – fine;
System.out.println("Monthly Income = " + netSalary);
}
}
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.
Prog. public class Exam
{
public static void main(String args[ ])
{
int tques = 150;
int c1 = (int)(80 / 100.0 * tques);
int c2 = (int)(72 / 100.0 * tques);
System.out.println("Correct Answers of Candidate 1 = " + c1);
System.out.println("Correct Answers of Candidate 2 = " + c2);
}
}
4. Write a program to find and display the percentage difference, when:
(a) a number is updated from 80 to 90
public class Increase
{
public static void main(String args[ ])
{
int num = 80;
int newnum = 90;
int inc = newnum – num;
double p = inc / (double)num * 100;

Operators in Java 23
System.out.println("Percentage Increasee = " + p + "%");
}
}
(b) a number is updated from 7.5 to 7.2
Prog. public class Decrease
{
public static void main(String args[ ])
{
double num = 7.5;
double newnum = 7.2;
double inc = num – newnum;
double p = inc / num * 100;
System.out.println("Percentage Decrease = " + p + "%");
}
}
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]
Prog. public class Temp
{
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);
}
}
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°]
Prog. public class Display
{
public static void main(String args[ ])
{
int r1 = 3, r2 = 4, r3 = 5, r4 = 6, total;
double a, b, c, d;
total = r1 + r2 + r3 + r4;
a = (double)r1/total * 360;
b = (double)r2 /total * 360;
c = (double)r3 /total * 360;
d = (double)r4 /total * 360;
System.out.println("Angle A = " + a);
System.out.println("Angle B = " + b);
System.out.println("Angle C = " + c);
System.out.println("Angle D = " + d);
}
}
Chapter 5

Input in Java

II. Write down the syntax with reference to Java Programming:


1. to accept an integral value 'p' through InputStreamReader Class
Syntax: InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int p = Integer.parseInt(in.readLine( ));
2. to accept a fractional value (float) 'm' through Scanner Class
Syntax: Scanner in = new Scanner(System.in);
float m = in.nextFloat( );
3. to accept a character 'd' through InputStreamReader Class
Syntax: InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
char d = (char) (in.read( ));
4. to accept a fraction value 'n' in double data type through
InputStreamReader Class
Syntax: InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
double n = Double.parseDouble(in.readLine( ));
5. to accept a word 'wd' through InputStreamReader Class
Syntax: InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
String wd = in.readLine( );
6. to create a scanner object
Syntax: Scanner in = new Scanner(System.in);
III. Differentiate between the following
1. nextInt( ) and nextFloat( ) methods
Ans. nextInt( ) method nextFloat( ) method
It accepts the next token as an int It accepts the next token as a float
type. type.
2. Syntax and logical errors
Ans. Syntax Errors Logical Errors
It occurs when we violate the rules It occurs due to our mistakes in
of writing the statements of the programming logic.
programming language.
Program fails to compile and Program compiles and executes but
execute. doesn't give the desired output.

25
3. Testing and Debugging
Ans. Testing Debugging
In this process, we check the validity In this process, we correct the errors
of a program. that were found during testing.
Testing is complete when all Debugging is finished when there
the desired verifications against are no errors and the program is
specifications have been performed. ready for execution.

IV. Answer the following:


1. What is meant by comment? Name the various ways to give comments
in a Java programming.
Ans. It is the non-executable statement that enables the users to understand the
program logic. It is basically a statement of remark called the comment.
The various ways to give comments in a Java programming are:
(i) Single line comment
(ii) Multiline comment
(iii) Documentation comment
2. What do you mean by scanner class?
Ans. The Scanner Class is the latest development in Java which allows the user
to read values of various data types. It is present in java.util package.
3. What are the different ways to give inputs in a Java program?
Ans. Java provides the following ways to give input in a program:
• Using Function Argument.
• Using InputStreamReader class
• Using Scanner class
• Using Command Line Arguments.
4. What is the use of the keyword 'import'?
Ans. The keyword 'import' is used to avail the facilities available in the related
built-in packages which are to be used in Java programs.
5. What is a package? Give an example.
Ans. Java package is a collection of various classes where each class contains
different functions. A package can be included in the program by using
a keyword 'import'.
For example, java.util, java.lang are the examples of some built-in packages.
6. Give an example to input an integer number by using function argument.
Ans. public class Test
{
public static void main (int a)
{
int ans;
System.out.println("Result = "+ (a*a*a));
}
}
7. 'Diagnostical messages detect only syntax errors'. Give comment.
Ans. A diagnostic message indicates that something may be wrong with the
program.
It happens when the compiler detects a suspect condition, it displays
a message that describes the problem, known as diagnostic message.
These messages help the programmers to identify and rectify the syntax
errors.
8. Write down the syntax to input a character through scanner class with
an example.
Ans. Syntax: char <variable name> = <Scanner Object>.next( ).charAt(0);
For example,
Scanner in = new Scanner(System.in);
char ch = in.next( ).charAt(0);
9. What do you understand by 'Run Time' error? Explain with an example.
Ans. The errors that occur during the execution of the program are known as
run time errors. They can only be resolved at runtime.
For example,
import java.util.*;
class Test
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = in.nextInt( );
int ans = 10/n;
System.out.println("Result = " + ans);
}
}
This program will work for all non-zero values of n entered by the user.
When the user enters zero, a run-time error will occur. It means that the
execution depends entirely on the state of the program at run-time.
10. What are the different types of errors that take place during the execution
of a program?
Ans. Logical errors and Run time errors occur during the execution of the
program.
V. Unsolved Java Programs
1. The time period of a simple pendulum is given by the formula:
T = 2π√(l/g)
Write a program to calculate and display the time period of a simple
pendulum by taking length (l) and acceleration due to gravity (g) as
inputs. [π = 22 ]
7
Prog. import java.util.Scanner;
public class Time_Period
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
double l, g, t;

Input in Java 27
System.out.print("Enter length: ");
l = in.nextDouble( );
System.out.print("Enter the value g: ");
g = in.nextDouble( );
t = 2 * (22.0/7.0) * Math.sqrt(l/g);
System.out.println("Time Peroid = " + t);
}
}
2. Write a program by using class 'Employee' to accept basic pay of an
employee. Calculate the allowances/deductions as given below.
Finally, find and display the gross and net pay.

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
Gross Pay = Basic Pay + Dearness Allowance + House Rent Allowance
Net Pay = Gross Pay – Provident Fund
import java.util.*;
Prog. public class Employee
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int basic;
double da, hra, pf, gp, np;
System.out.print("Enter Basic Pay: ");
basic = in.nextInt( );
da = 0.3 * basic;
hra = 0.15 * basic;
pf = 0.125 * basic;
gp = basic + da + hra;
np = gp – pf;
System.out.println("Gross Pay = " + gp);
System.out.println("Net Pay = " + np);
}
}
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 and display the amount to be paid by the
customer taking printed price as an input.
Prog. import java.util.*;
public class Camera
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int mp;
double dis, price, gst;
System.out.println("Enter printed price of Digital Camera:");
mp = in.nextInt( );
dis = mp * 10/100.0;
price = mp – dis;
gst = price * 6/100.0;
price += gst;
System.out.println("Amount to be paid: " + price);
}
}
4. A shopkeeper offers 30% discount on purchasing an article whereas
the other shopkeeper offers two successive discounts 20% and 10% for
purchasing the same article. Write a program in Java to compute and
display the discounts.
Take the price of an article as the input.
Prog. import java.util.*;
public class Discounts
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int price;
double d1, amt1, d2, amt2, d3;
System.out.print("Enter price of article: ");
price = in.nextInt( );
d1 = price * 30 / 100.0;
amt1 = price – d1;
System.out.println("30% discount = " + d1);
System.out.println("Amount after 30% discount = " + amt1);
d2 = price * 20 / 100.0;
amt2 = price – d2;
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);
}
}
5. Mr. Agarwal invests certain sum at 5% per annum compound interest
for three years. Write a program in Java to calculate and disiplay:
(a) the interest for the first year
(b) the interest for the second year
(c) the interest for the third year
Take sum as an input from the user.
Sample Input: Principal = ` 5000
Sample Output: Interest for the first year: ` 500
Interest for the second year: ` 550
Interest for the third year: ` 605
Input in Java 29
Prog. import java.util.*;
public class Interest
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int p;
double interest;
System.out.print("Enter principal: ");
p = in.nextInt( );
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);
}
}
6. A businessman wishes to accumulate shares of a company. However,
he already has 500 shares of that company valuing ` 50 (nominal value)
which yields 10% dividend per annum and receives ` 2000 as dividend
at the end of the year. Write a program in Java to input number of shares
wants to purchase. Calculate and display:
(i) total number of shares
(ii) total dividend earned in a year.
[Hint: Annual dividend = No. of shares* Nominal value * div%]
Prog. import java.util.*;
public class Shares
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int ns;
double div;
System.out.print("Enter number of shares to purchase : ");
ns = in.nextInt( );
div = (ns+500)*50*10/100.0;
System.out.println("Total number of shares = "+(ns+500));
System.out.println("Dividend = "+div);
}
}
7. Write a program to input the time in seconds. Display the time after
converting it into hours, minutes and seconds.
Sample Input: Time in seconds 5420
Sample Output: 1 Hour 30 Minutes 20 Seconds
Prog. import java.util.*;
public class Time
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int sec, min, hrs;
System.out.print("Enter time in seconds: ");
sec = in.nextInt( );
hrs = sec/3600;
sec %= 3600;
min = sec/60;
sec %= 60;
System.out.println(hrs+" Hours "+min+" Minutes "+sec+" Seconds");
}
}
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
Prog. import java.util.*;
public class Swap
{
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("After swapping:");
System.out.println("First number = " + a);
System.out.println("Second number = " + b);
}
}
9. A certain sum is invested at the rate of 10% per annum for 3 years. Write
a program to find and display the difference between Compound Interest
(CI) and Simple Interest (SI). Take the sum as an input.
[Hint: SI = (P * R * T) / 100
A = P * (1 + (R/100)T
CI = A – P]

Input in Java 31
Prog. import java.util.*;
public class Difference
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int p;
double si, amt, ci;
System.out.print("Enter principal : ");
p = in.nextInt( );
si = p * 10 * 3/100;
amt = p * Math.pow(1+(10/100.0), 3);
ci = amt – p;
System.out.print("Difference between CI and SI: " + (ci – si));
}
}
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 and display his total cost price of the calculators by taking their
selling price as input.
Hint: CP = (SP/(1 + (profit/100))) (when profit)
CP = (SP/(1 – (loss/100))) (when loss)
Prog. import java.util.*;
public class Calculate
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int sp;
double cp1, cp2, totalcp;
System.out.print("Enter the selling price: ");
sp = in.nextInt( );
cp1 = (sp/(1 + (20/100.0)));
cp2 = (sp/(1 – (20/100.0)));
totalcp = cp1 + cp2;
System.out.println("Cost Price of first article = " + cp1);
System.out.println("Cost Price of second article = " + cp2);
System.out.println("Total Cost Price = " + totalcp);
}
}
Chapter 6

Mathematical Library Methods

III. Write down the syntax for the following functions


1. To find the smaller between two numbers p and q
Ans. Math.min(p, q)
2. To find the absolute value of a number m
Ans. Math.abs(m)
3. To find the exponent of a number k
Ans. Math.exp(k)
4. To find the square root of a number d
Ans. Math.sqrt(d)
5. To find the rounded-off value of a number b
Ans. Math.round(b)
IV. Predict the return data type of the following functions
1. Math.sqrt( );
Ans. double
2. Math.rint( );
Ans. double
3. Math.ceil( );
Ans. double
4. Math.round( );
Ans. long
5. Math.floor( );
Ans. double
6. Math.log( )
Ans. double
V. Explain the following functions
1. Math.random( )
Ans. Returns a positive double value, greater than or equal to 0.0 and less
than 1.0.
2. Math.max( )
Ans. Returns the greater of its arguments. Its return type is same as the type
of its arguments.
3. Math.cbrt( )
Ans. Returns the cube root of its argument as a double type value.
4. Math.abs( )
Ans. Returns the absolute value of its argument. Its return type is same as the
type of its arguments.

33
5. Math.log( )
Ans. Returns the natural logarithm value of its argument. Both return type
and argument are of double data type.
VI. Distinguish between them with suitable examples:
1. Math.ceil( ) and Math.floor( )
Ans. Math.ceil( ) Math.floor( )
This function is used to return This function is used to return
the higher integer for the given the lower integer for the given
argument. argument.
double a = Math.ceil(65.5); double b = Math.floor(65.5);
It will result in 66.0. It will result in 65.0.
2. Math.rint( ) and Math.round( )
Ans. Math.rint( ) Math.round( )
Rounds off its argument to the Rounds off its argument to the
nearest mathematical integer and nearest mathematical integer and
returns its value as a double type. returns its value as a long type.
At mid-point, it returns the integer At mid-point, it returns the higher
that is even. integer.
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

VII. Unsolved Java Programs


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
Prog. import java.util.*;
public class Number
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, b, c, g, sm;
System.out.print("Enter First Number: ");
a = in.nextInt( );
System.out.print("Enter Second Number: ");
b = in.nextInt( );
System.out.print("Enter Third Number: ");
c = in.nextInt( );
g = Math.max(a, b);
g = Math.max(g, c);
sm = Math.min(a, b);
sm = Math.min(sm, c);
System.out.println("Greatest Number = " + g);
System.out.println("Smallest Number = " + sm);
}
}
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]
Prog. import java.util.*;
public class Hypotenuse
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
double p, b, h;
System.out.print("Enter Perpendicular: ");
p = in.nextDouble( );
System.out.print("Enter Base: ");
b = in.nextDouble( );
h = Math.sqrt(Math.pow(p, 2) + Math.pow(b, 2));
System.out.println("Hypotenuse = " + h);
}
}
3. Write a program to input a number. Evaluate and display 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).
Prog. import java.util.*;
public class Evaluate
{
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( ));
}
}

Mathematical Library Methods 35


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
marks obtained and finally display the marks in rounded-off form.
Take Physics, Chemistry. and Biology marks as inputs.
Prog. import java.util.*;
public class AvgMarks
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int p, c, b;
double avg;
long ravg;
System.out.print("Enter marks in Physics: ");
p = in.nextInt( );
System.out.print("Enter marks in Chemistry: ");
c = in.nextInt( );
System.out.print("Enter marks in Biology: ");
b = in.nextInt( );
avg = (p + c + b) / 3.0;
ravg = Math.round(avg);
System.out.println("Rounded Off Avg Marks = " + ravg);
}
}
5. You want to calculate the radius of a circle by using the formula:
Area = (22/7) * r2; where r = radius of the 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.
Prog. import java.util.*;
public class Circle
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
double area, r;
System.out.print("Enter Area of Circle: ");
area = in.nextDouble( );
r = Math.sqrt((7 * area) / 22);
System.out.print("Radius of Circle = " + r);
}
}
Chapter 7

Conditional Statements in Java

II. Answer the following questions:


1. Name the different ways to manage the flow of control in a program.
Ans. The different ways to manage the flow of control in a program are:
• Normal flow of control
• Conditional flow of control
• Multiple branching of control
2. Mention one statement each to achieve:
(a) Conditional flow of control
Ans. if-else statement
(b) Multiple branching of control
Ans. switch case statement
3. Explain the following statements with their constructs:
(a) nested if
The nested if statement is a statement, where an 'if' statement is
placed within another 'if' statement.
Syntax:
if (condition 1)
{
if (condition 2)
……………….
Statements
……………….
else
…………………
Statements
………………..
}
else
{
if (condition 3)
……………….
Statements
……………….
else
…………………
Statements
…………………
}

37
(b) if - else
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.
Syntax:
if (condition 1)
{
Statement 1;
Statement 2;
………………
}
else
{
Statement 3;
Statement 4;
………………
}
(c) if - else - if
if - else - if ladder construct is used to test multiple conditions and then
take a decision. It provides multiple branching of control.
Syntax:
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
……………….
……………....
else
statement;
4. Differentiate between if and switch statement.
Ans. if switch
if can test for any Boolean switch can only test for equality.
expression.
if doesn't have such limitations. tests the same expression against
constant values.
5. What is the purpose of the switch statement in a program?
Ans. Switch statement is used for multi-way branching. It compares its
expression with 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.
6. Explain with the help of an example, the purpose of default in a switch
statement.
Ans. When none of the case values are equal to the expression of switch
statement then default case is executed.
For example,
int num = 3;
switch(num)
{
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("Incorrect Input!");
}
7. Is it necessary to use 'break' statement in a switch case statement?
Explain.
Ans. Use of break statement in a switch case statement is optional. The
omission of break statement will lead to fall through where program
execution continues into the next case and onwards till end of switch
statement is reached.
8. Explain 'Fall through' with reference to a switch case statement.
Ans. The use of break statement at the end of each case is an optional. The
omission of break statement will continue the execution 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 a switch case statement.
9. What is a compound statement? Give an example.
Ans. When two or more statements can be grouped together by enclosing
them between opening and closing curly braces, it is called a compound
statement.
For example,
a= 10; b=20;
if (a < b)
{
d = a – b;
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);
System.out.println("The difference is " + d);
}
10. Explain with an example the if-else-if construct.
Ans. The if - else - if ladder construct is used to test multiple conditions and
then take a decision. It provides multiple branching of control.
For example,
if (marks < 35)
System.out.println("No Grade");
else if (marks < 60)
System.out.println("Grade: C");
else if (marks < 80)
System.out.println("Grade: B");

Conditional Statements in Java 39


else if (marks < 95)
System.out.println("Grade: A");
else
System.out.println("Grade: A+");
11. What is the significance of System.exit(0)?
Ans. The function System.exit(0) is used when we want to terminate the
execution of the program at any instance. As soon as System.exit(0)
function is invoked, it terminates the execution, ignoring the rest of the
statements of the program.
12. Give two differences between the switch statement and the if-else
statement.
Ans. switch if-else
It can only test, if the expression is It can test for any boolean expression
equal to any of its case constants. like less than, greater than, equal to,
not equal to, etc.
It is a multiple branching flow of It is a bi-directional flow of control
control statement. statement.

III. Predict the output of the given snippet, when executed:


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
0
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
3. int b=3, k=0, r;
double a=15.15, c=0;
if(k==1)
{
r=(int)a/b;
System.out.println(r);
}
else
{
c=(double)a/b;
System.out.println(c);
}
Output: 5.05
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
(ii) opn = 'x'
Wrong Input
(ii) opn = 'a'
Platform Independent
IV. Correct the errors in the given programs:
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);
}
}

Conditional Statements in Java 41


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; //5th correction
System.out.println(sum + " " + diff); //6th correction
}
}
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");
}
}
Corrected Program:
class Square
{
public static void main(String args[ ])
{
int n=289;
double r=Math.sqrt(n); //1st correction
if(n==(int)r*r) //2nd correction
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}
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);
}
}
Corrected Program:
class Simplify
{
public static void main(String args[ ])
{
int a=10, b=5, c=1, d=2; //1st correction
c = a*a + b*b; //2nd correction
d = (int)Math.pow((a+b), 2); //3rd correction
double p=(double)c/d; //4th correction
System.out.println(c + " "+ " "+d+ " "+p);
}
}
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);
}
}
}
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);
}
}
}
Conditional Statements in Java 43
Unsolved Java Programs:
1. Write a program to input three angles of a triangle and check whether
its construction is possible or not. If possible then check and display
whether it is an acute-angled triangle, right-angled triangle or an obtuse-
angled triangle otherwise, display 'A Triangle is not possible'.
Sample Input: Enter three angles: 40, 50, 90
Sample Output: Right–Angled Triangle
Prog. import java.util.*;
public class Triangle
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a1, a2, a3, sum;
System.out.print("Enter first angle: ");
a1 = in.nextInt( );
System.out.print("Enter second angle: ");
a2 = in.nextInt( );
System.out.print("Enter third angle: ");
a3 = in.nextInt( );
sum = a1 + a2 + a3;
if (sum == 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("A Triangle is not possible");
}
}
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 the
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".
Prog. import java.util.*;
public class Profit_Loss
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int cp, sp, p, loss;
double pp, lp;
System.out.print("Enter cost price of the article: ");
cp = in.nextInt( );
System.out.print("Enter selling price of the article: ");
sp = in.nextInt( );
if (sp>cp)
{
p = sp – cp;
pp = (double)p/cp * 100.0;
System.out.println("Profit = " + p);
System.out.println("Profit % = " + pp);
}
else if (sp<cp)
{
loss = cp – sp;
lp = (double)loss/cp * 100.0;
System.out.println("Loss = " + loss);
System.out.println("Loss % = " + lp);
}
else
System.out.println("Neither profit nor loss");
}
}
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.
Prog. import java.util.*;
public class Numbers
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, b, c;
System.out.print("Enter first number: ");
a = in.nextInt( );
System.out.print("Enter second number: ");
b = in.nextInt( );
System.out.print("Enter third number: ");
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;

Conditional Statements in Java 45


System.out.println("Greatest number: " + g);
}
}
}
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.
Prog. import java.util.*;
public class Divisor
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int num;
System.out.print("Enter number: ");
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");
}
}
5. Write a program to input the year. The program checks and displays
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.
Prog. import java.util.*;
public class LeapYear
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int yr;
System.out.print("Enter the year to check: ");
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");
}
}
6. Write a program to input two unequal positive numbers and check
whether they are perfect square numbers or not. If the user enters any
negative number then the program displays the message "Square root
of a negative number cannot 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.
Prog. import java.util.*;
public class PerfectSquare
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, b;
double sqrta, sqrtb;
System.out.print("Enter first number: ");
a = in.nextInt( );
System.out.print("Enter second number: ");
b = in.nextInt( );
if (a < 0 || b < 0)
{
System.out.println("Square root of a negative number cannot be
determined");
}
else
{
sqrta = Math.sqrt(a);
sqrtb = Math.sqrt(b);
if ((a==(int)sqrta*sqrta) && (b==(int)sqrtb*sqrtb))
System.out.println("They are perfect square numbers.");
else if ((a==(int)sqrta*sqrta) && (b!=(int)sqrtb*sqrtb))
{
System.out.println(a + " is a perfect square number.");
System.out.println(b + " is not a perfect square number.");
}
else if ((a!=(int)sqrta*sqrta) && (b==(int)sqrtb*sqrtb))
{
System.out.println(a + " is not a perfect square number.");
System.out.println(b + " is a perfect square number.");
}

Conditional Statements in Java 47


else
System.out.println("Both are not perfect square numbers.");
}
}
}
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( ) functions]
Sample Input: 34, 82, 61
Sample Output: 61
Prog. import java.util.*;
public class Second_SmallestNum
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, b, c, sum, big, small, res;
System.out.println("Enter 3 unequal numbers");
System.out.print("Enter first number: ");
a = in.nextInt( );
System.out.print("Enter second number: ");
b = in.nextInt( );
System.out.print("Enter third number: ");
c = in.nextInt( );
sum = a + b + c;
big = Math.max(a, b);
big = Math.max(big, c);
small = Math.min(a, b);
small = Math.min(small, c);
res = sum – big – small;
System.out.println("Second Smallest Number = " + res);
}
}
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
Prog. import java.util.*;
public class Max_Min
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, b, c, min, max;
System.out.println("Enter 3 unequal numbers");
System.out.print("Enter first number: ");
a = in.nextInt( );
System.out.print("Enter second number: ");
b = in.nextInt( );
System.out.print("Enter third number: ");
c = in.nextInt( );
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);
}
}
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
to be paid by the passenger. The program displays the printed bill with
the details given below:
Taxi No. : …………………………
Distance covered : …………………………
Amount : …………………………
Prog. import java.util.*;
public class PrePaidTaxi
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int dist, fare;
String tn;
System.out.print("Enter Taxi Number: ");
tn = in.nextLine( );
System.out.print("Enter distance travelled: ");
dist = in.nextInt( );
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;

Conditional Statements in Java 49


System.out.println("Taxi No: " + tn);
System.out.println("Distance covered: " + dist);
System.out.println("Amount: " + fare);
}
}
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.
Prog. import java.util.*;
public class Discount
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int cost;
String gift;
double amt;
System.out.print("Enter total cost: ");
cost = in.nextInt( );
if (cost <= 2000)
{
amt = cost – (cost * 5/100);
gift = "Calculator";
}
else if (cost <= 5000)
{
amt = cost – (cost * 10/100);
gift = "School Bag";
}
else if (cost <= 10000)
{
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);
}
}
11. Given below is a hypothetical table showing the rate of income tax for
an India citizen, who is up to the age of 60 years.

Taxable income (TI) in ` Income Tax in `


Up to ` 2,50,000 Nil
More than ` 2,50,000 and less than or (TI – 1,60,000) * 10%
equal to ` 5,00,000
More than ` 5,00,000 and less than or (TI – 5,00,000) * 20% + 34,000
equal to ` 10,00,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.
Prog. import java.util.*;
public class IncomeTax
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int age;
double ti, tax=0.0;
String name;
System.out.print("Enter Name: ");
name = in.nextLine( );
System.out.print("Enter taxable income: ");
ti = in.nextDouble( );
System.out.print("Enter age: ");
age = in.nextInt( );
if (age > 60)
{
System.out.print("Wrong Category");
System.exit(0);
}
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);

Conditional Statements in Java 51


else
tax = 94000 + ((ti – 1000000) * 30/100);
}
System.out.println("Name: " + name);
System.out.println("Tax Payable: " + tax);
}
}
12. An employee wants to deposit certain sum of money under 'Term Deposit'
scheme in a 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 and display the maturity amount taking
the sum and number of days as inputs.
Prog. import java.util.*;
public class TermDeposit
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int sum, days;
double interest = 0.0, amt;
System.out.print("Enter sum of money: ");
sum = in.nextInt( );
System.out.print("Enter number of days: ");
days = in.nextInt( );
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;
amt = sum + interest;
System.out.print("Maturity Amount = " + amt);
}
}
13. Mr. Kumar is an LIC agent. He offers discount to his policy holders on
the first 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 the 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 : ……………………………
Prog. import java.util.*;
public class LICPolicy
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int sum, pre;
double disc = 0.0, comm = 0.0;
String name;
System.out.print("Enter Name: ");
name = in.nextLine( );
System.out.print("Enter Sum Assured: ");
sum = in.nextInt( );
System.out.print("Enter First Premium: ");
pre = in.nextInt( );
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

Conditional Statements in Java 53


{
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);
}
}
14. A company announces revised Dearness Allowance (DA) and Special
Allowance (SA) for their employees as per the tariff given below:

Basic Dearness Special


Allowance (DA) 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
Display the information in the given format:
Name Basic DA Spl. Allowance Gross Salary
xxx xxx xxx xxx xxx xxx
Prog. import java.util.*;
public class Salary
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
String name;
int bs;
double da = 0.0, sa = 0.0, gs;
System.out.print("Enter name: ");
name = in.nextLine( );
System.out.print("Enter basic salary: ");
bs = in.nextInt( );
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;
}
gs = bs + da + sa;
System.out.println("Name\t\tBasic\tDA\tSpl. Allowance\tGross Salary");
System.out.println(name + "\t" + bs + "\t" + da + "\t" + sa + "\t\t" + gs);
}
}
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]
Prog. import java.util.*;
public class Temperature
{
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");
System.out.print("Enter your choice : ");
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");
}
}
}
Conditional Statements in Java 55
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 and display the
volume of different solids by taking suitable variables and data types
as input.
Prog. import java.util.*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, l, b, h, vol;
double rcyl, hcyl, vcyl, rcone, hcone, vcone;
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: ");
choice = in.nextInt( );
switch(choice) {
case 1:
System.out.print("Enter length of cuboid: ");
l = in.nextInt( );
System.out.print("Enter breadth of cuboid: ");
b = in.nextInt( );
System.out.print("Enter height of cuboid: ");
h = in.nextInt( );
vol = l * b * h;
System.out.println("Volume of cuboid = " + vol);
break;
case 2:
System.out.print("Enter radius of cylinder: ");
rcyl = in.nextDouble( );
System.out.print("Enter height of cylinder: ");
hcyl = in.nextDouble( );
vcyl = (22/7.0) *rcyl*rcyl*hcyl ;
System.out.println("Volume of cylinder = " + vcyl);
break;
case 3:
System.out.print("Enter radius of cone: ");
rcone = in.nextDouble( );
System.out.print("Enter height of cone: ");
hcone = in.nextDouble( );
vcone = (1/3.0) * (22/7.0) * rcone*rcone*hcone;
System.out.println("Volume of cone = " + vcone);
break;
default:
System.out.println("Wrong choice!");
}
}
}
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.
Prog. import java.util.*;
public class MegaShop
{
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");

Conditional Statements in Java 57


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!!");
}
}
}
18. The equivalent resistance of series and parallel connections of two
resistances are given by the formulae:
(a) R 1 = r1 + r 2 (Series)
(b) R 2 = (r1 * r 2) / (r1 + r 2) (Parallel)
Using a switch case statement, write a program to enter the value of
r1 and r2. Calculate and display the equivalent resistances accordingly.
Prog. import java.util.*;
public class Resistance
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
double r1, r2, eqr = 0.0;
System.out.print("Enter r1: ");
r1 = in.nextDouble( );
System.out.print("Enter r2: ");
r2 = in.nextDouble( );
System.out.println("1 for equivalent resistance in Series");
System.out.println("2 for equivalent resistance in Parallel");
System.out.print("Enter your choice: ");
int choice = in.nextInt( );
switch (choice)
{
case 1:
eqr = r1 + r2;
System.out.println("Equivalent resistance = " + eqr);
break;
case 2:
eqr = (r1 * r2) / (r1 + r2);
System.out.println("Equivalent resistance = " + eqr);
break;
default:
System.out.println("Incorrect choice");
}
}
}
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. Use switch case statement.
Prog. import java.util.*;
public class Interest
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int p, t;
double r, interest=0.0, amt =0.0;
System.out.print("Enter the sum: ");
p = in.nextInt( );
System.out.print("Enter rate: ");
r = in.nextDouble( );
System.out.print("Enter time: ");
t = in.nextInt( );
System.out.println("Enter type of Interest:");
System.out.print("'S' for Simple Interest and 'C' for Compound
Interest: ");
char type = in.next( ).charAt(0);
switch (type)
{
case 'S':
interest = p * r * t/100.0;
amt = p + interest;
System.out.println("Sum = " + p);
System.out.println("Interest = " + interest);
System.out.println("Amount = " + amt);
break;
case 'C':
interest = p * (Math.pow((1+(r/100.0)), t) – 1);
amt = p + interest;
System.out.println("Sum = " + p);
System.out.println("Interest = " + interest);
System.out.println("Amount = " + amt);
break;
default:
System.out.println("Incorrect Interest type!!");
}
}
}

Conditional Statements in Java 59


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 0.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 display the net amount to be paid by a customer along with his
name.
(Net amount = Amount of purchase – discount)
Prog. import java.util.*;
public class Sale
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int amt;
double disc = 0.0;
System.out.print("Enter Name: ");
String name = in.nextLine( );
System.out.print("Enter Amount of Purchase: ");
amt = in.nextInt( );
System.out.println("Enter Type of Purchase:");
System.out.print("'L' for Laptop or 'D' for Desktop: ");
char type = in.next( ).charAt(0);
type = Character.toUpperCase(type);
if (type =='L' || type =='D')
{
if (amt <= 25000)
disc = type == 'L' ? 0.0 : 5.0;
else if (amt <= 50000)
disc = type == 'L' ? 5.0 : 7.5;
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.0);
System.out.println("Name: " + name);
System.out.println("Net Amount: " + netAmt);
}
else
System.out.println("Incorrect type of purchase!!");
}
}
Chapter 8

Iterative Constructs in Java

II. Answer the following questions:


1. What do you understand by iterative process? How can it be resolved
by using loop?
Ans. Iterative process means repeating a set of instructions a certain number
of times to perform some task. Using loops, the programming language
like Java, enable us to repeat a single statement or a set of statements as
long as the desired condition remains true.
2. Explain for loop with an example.
Ans. The for loop is an entry-controlled loop. It is also said to be a fixed
iterative loop because the number of iterations is fixed. Here, the loop
starts with a given value of a variable. It executes the block of statements
by updating the control variable unless the given condition is false.
For example,
for (i = 1; i <= 10; i++)
{
a = 2 * i;
System.out.println(a);
}
This for loop prints the table of 2 till 10 and iterates as long as this
condition remains true. Once it becomes false, execution of the loop is
stopped.
3. Name the different types of looping constructs.
Ans. The different types of looping constructs are:
• for
• while
• do-while
4. What are the parameters needed to create a for loop?
Ans. The following parameters are commonly used in a for loop:
(i) An initial value of the loop.
(ii) A test condition of the loop. The processs will iterate as long as the
condition remains true.
(iii) An update value to modify the loop control variable after each
iteration.
(iv) Body of the loop which consists of the statements that need to be
repeatedly executed.
5. Define the following with their constructs:
(a) Entry controlled loop
Ans. An entry-controlled loop checks the condition at the beginning of the
loop. If the condition is true, the control enters the body of the loop and
the process repeats until the given condition is false.
For example, for and while loops.

61
(b) Exit controlled loop
Ans. An exit-controlled loop checks the condition after executing its body. If
the condition is true, the loop will perform the next iteration, otherwise
the program control will exit the loop.
For example, do-while loop
6. Write down the general format of:
(a) for loop
Ans. for (initial value; test condition; update)
{
//loop-body
}
(b) do - while loop
do
{
//loop-body
} while (condition);
(c) while loop
while (condition)
{
//loop-body
}
7. What is the purpose of using:
(a) break statement?
Ans. The 'break' statement is also used in looping construct for unnatural
termination of the loop. It can be used in all the loops.
(b) continue statement?
Ans. The continue statement is used to unconditionally jump to the next
iteration of the loop, skipping the remaining statements of the current
iteration.
8. What do you understand by inter-conversion of loops?
Ans. We can convert the repetitive statement using one type of loop into other
type of loops. Thus, the process of converting of some repetitive logic is
coded using a loop into other type of loop is termed as inter-conversion
of loops.
9. What are the different ways to inter-convert the loops? Name them.
Ans. The different ways to inter-convert the loops are:
• for loop to while loop
• for loop to do-while loop
• do-while loop to while loop
• do-while loop to for loop
• while loop to do-while loop
• while loop to for loop
10. Define the following:
(a) Finite loop
Ans. A loop which iterates for a finite number of iterations is termed as a finite
loop.
(b) Delay loop
Ans. A loop which is used to pause the execution of the program for some
amount of time, is termed as delay loop.
(c) Infinite loop
Ans. A loop which continues iterating indefinitely and never stops, is termed
as infinite loop.
(d) Null loop
Ans. A loop that does not include any statement to be repeated, is known as
null loop.
Basically, a null loop is used to create a delay in the execution.
11. Distinguish between:
(a) for and while loop
Ans. for loop while loop
It is suitable when the number of It is helpful in situations where
iterations are known. number of iterations are not known.
The loop will repeat infinite times, if If the condition is not defined then
the condition is not defined. an error will be shown.
(b) while and do-while loop
Ans. while loop do-while loop
It is an entry-controlled loop. It is an exit-controlled loop.
The loop will not execute at all, if This loop will execute at least once,
the condition is not satisfied. whether the condition is true or
false.
12. State one difference and one similarity between while and do-while loop.
Ans. Similarity: Both while and do-while loops are suitable in situations where
numbers of iterations is not known.
Difference: The while is an entry-controlled loop whereas do-while is an
exit-controlled loop.
13. State one similarity and one difference between while and for loop.
Ans. Similarity: Both for and while are entry-controlled loops.
Difference: The for loop is a suitable choice when the number of iterations
are known. Wheras, while loop is helpful in situations where number of
iterations is not known.
14. Distinguish between Step loop and Continuous loop.
Ans. In Continuous loop, loop control variable is incremented or decremented
by one in each iteration. Whereas in Step loop, the loop control variable
is incremented or decremented by more than one in each iteration.
III. Predict the output of the following program snippets:
1. class dkl
{
public static void main(String args[ ])
{
int i;
for(i = –1;i<10;i++)

Iterative Constructs in Java 63


{
System.out.println(++i);
{
}
}
Output: 0
2
4
6
8
10
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
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
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
2
The loop will execute 2 times.
IV. Rewrite the following programs:
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);
}
}

Iterative Constructs in Java 65


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( );
}
}
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");
}
}
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);

Iterative Constructs in Java 67


System.out.println("Enter a number");
n=Integer.parseInt(in.readLine( ));
while(n!=0)
{
r=n%10;
n=n/10;
System.out.println(r);
}
}
}
V. Solutions to Unsolved Java Programs:
1. Write the programs in Java to display the first ten terms of the following
series:
(a) 1, 4, 9, 16, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 1; i <= 10; i++)
System.out.print(i * i + " ");
}
}
(b) 1, 2, 4, 7, 11, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 0; i < 10; i++)
{
int term = 1 + ((i * (i + 1))/2);
System.out.print(term + " ");
}
}
}
(c) 3, 6, 9, 12, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 1; i <= 10; i ++)
{
System.out.print(3*i + " ");
}
}
}
(d) 4, 8, 16, 32, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 2; i <= 11; i++)
{
System.out.print((int)(Math.pow(2, i)) + " ");
}
}
}
(e) 1.5, 3.0, 4.5, 6.0, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
float term = 1.5f;
for (int i = 1; i <= 10; i++)
{
System.out.print(term + " ");
term += 1.5f;
}
}
}
(f) 0, 7, 26, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 1; i <= 10; i++)
{
int term = ((i*i*i) – 1);
System.out.print(term + " ");
}
}
}
(g) 1, 9, 25, 49, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 1; i <= 19; i = i + 2)
{
System.out.print((i * i) + " ");
}
}
}

Iterative Constructs in Java 69


(h) 4, 16, 36, 64, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 2; i <= 20; i = i + 2)
{
System.out.print((i * i) + " ");
}
}
}
(i) 0, 3, 8, 15, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 1; i <= 10; i++)
{
System.out.print((i * i – 1) + " ");
}
}
}
(j) 24, 99, 224, 399, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 5; i <= 50; i = i + 5)
{
int term = ((i*i) – 1);
System.out.print(term + " ");
}
}
}
(k) 2, 5, 10, 17, …………………………………………
Prog. public class Series
{
public static void main(String args[ ])
{
for (int i = 1; i <= 10; i++)
{
System.out.print((i * i + 1) + " ");
}
}
}
2. Write a program to input any 50 numbers (including positive and
negative).
Perform the following tasks:
(a) Count and display the positive numbers
(b) Count and display the negative numbers
(c) Display the sum of positive numbers
(d) Display the sum of negative numbers
Prog. import java.util.*;
public class Numbers
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int i, n;
int pSum = 0, pCount = 0, nSum = 0, nCount = 0;
System.out.println("Enter 50 numbers");
for (i = 1; i <= 50; i++)
{
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);
}
}
3. Write a program to calculate and display 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).
Prog. import java.util.*;
public class Sum
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int m, n, i, sumodd =0, sumeven =0;
System.out.print("Enter the value of m: ");
m = in.nextInt( );

Iterative Constructs in Java 71


System.out.print("Enter the value of n: ");
n = in.nextInt( );
if (m < n)
{
for (i = m; i <=n; i++)
{
if (i % 2 == 0)
sumeven += i;
else
sumodd += i;
}
System.out.println("Sum of even numbers: " + sumeven);
System.out.println("Sum of odd numbers: " + sumodd);
}
else
{
System.out.println("The value of m is greater than n");
System.out.println("Re-enter the value!!");
}
}
}
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 and display the numbers ending with 0 (zero).
Prog. import java.util.*;
public class Divisible
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int i, n, c = 0;
System.out.println("Enter any 50 numbers");
for (i = 1; i <= 50; i++)
{
n = in.nextInt( );
if (n % 5 == 0)
{
if (n % 10 == 5)
{
System.out.print("Number ending with the digit 5 : "+n);
System.out.println( );
}
if (n % 10 == 0)
c++;
}
}
System.out.println("Count of numbers ending with zero: " + c);
}
}
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 display the numbers
that are perfect square.
For example, 25, 36, 49, are said to be perfect square numbers.
Prog. import java.util.*;
public class PerfectSquare
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int i, m, n;
System.out.print("Enter the value of m: ");
m = in.nextInt( );
System.out.print("Enter the value of n: ");
n = in.nextInt( );
if (m < n && m > 0 && n > 0)
{
System.out.println("Perfect square numbers are :");
for (i = m; i <= n; i++)
{
double sroot = Math.sqrt(i);
if (sroot == Math.floor(sroot))
System.out.println(i);
}
}
else
System.out.println("Invalid input!!");
}
}
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.
Prog. import java.util.*;
public class BuzzNumber
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int p, q, i;
System.out.print("Enter the value of p: ");
p = in.nextInt( );
System.out.print("Enter the value of q: ");
q = in.nextInt( );
if (p < q)
{
System.out.println("Buzz Numbers between " + p + " and " + q);
for (i = p; i <= q; i++)
{

Iterative Constructs in Java 73


if (i % 10 == 7 || i % 7 == 0)
System.out.println(i);
}
}
else
System.out.println("Invalid Inputs!!!");
}
}
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) Find and display the number of students, who have secured 95% or more
in aggregate.
(b) Number of students, who have secured 90% or more in English, Maths
and Science.
Prog. import java.util.*;
public class Marks
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int i, eng, maths, sci, ta = 0, te = 0, tm = 0, ts = 0;
for (i = 1; i <= 40; i++)
{
System.out.println("Enter marks of student " + i);
System.out.print("In English: ");
eng = in.nextInt( );
System.out.print("In Maths: ");
maths = in.nextInt( );
System.out.print("In Science: ");
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 getting 95% or more in all subjects: " + ta);
System.out.println("No. of students getting 90% or more in English: " + te);
System.out.println("No. of students getting 90% or more in Maths: " + tm);
System.out.println("No. of students getting 90% or more in Science: " + ts);
}
}
8. Write a program in Java to find and display the sum of the following
series:
(a) 1 + 4 + 9 + ...... + 400
Prog. public class Series
{
public static void main(String args[ ])
{
int i, sum = 0;
for (i = 1; i <= 20; i++)
sum += (i*i);
System.out.println("Sum = " + sum);
}
}
(b) 1 + (1/2) + (1/3) +....... + (1/20)
Prog. public class Series
{
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);
}
}
(c) 1 + (1/3) + (1/5) +....... + (1/19)
Prog. public class Series
{
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)
Prog. public class Series
{
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);
}
}

Iterative Constructs in Java 75


(e) 2 – 4 + 6 – 8 + ..........20
Prog. public class Series
{
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);
}
}
(f) (1*2) + (2*3) + ....... + (19*20)
Prog. public class Series
{
public static void main(String args[ ])
{
int i, sum = 0;
for (i = 1; i <= 19; i++)
sum += i * (i + 1);
System.out.println("Sum = " + sum);
}
}
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 and displays the output accordingly.
Sample Input: 749
Sample Output:Number of digits = 3
The number contains odd number of digits.
Prog. import java.util.*;
public class Count
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, c = 0;
System.out.print("Enter a number: ");
n = in.nextInt( );
c = 0;
while (n != 0)
{
c++;
n/= 10;
}
System.out.println("Number of digits = " + c);
if (c % 2 == 0)
System.out.println("The number contains even number of digits");
else
System.out.println("The number contains odd number of digits");
}
}
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
Prog. import java.util.*;
public class Abs_Diff
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int num, num1, rnum = 0, d, diff;
System.out.print("Enter a number: ");
num = in.nextInt( );
num1 = num;
while(num1 != 0)
{
d = num1 % 10;
num1 /= 10;
rnum = rnum * 10 + d;
}
diff = rnum – num;
System.out.println("Reversed Number = " + rnum);
System.out.println("Absolute Difference = " + Math.abs(diff));
}
}
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
Prog. import java.util.*;
public class GCD
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);

Iterative Constructs in Java 77


int a, b, t;
System.out.print("Enter first number: ");
a = in.nextInt( );
System.out.print("Enter second number: ");
b = in.nextInt( );
while (b != 0)
{
t = b;
b = a % b;
a = t;
}
System.out.println("GCD = " + a);
}
}
12. Write a program in Java to find and display the sum of the following
series:
(a) S = a2 + a2/2 + a2/3 + ...... + a2/10
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, i;
double sum = 0;
System.out.print("Enter the value of a: ");
a = in.nextInt( );
for (i = 1; i <= 10; i++)
sum += (double)(a*a)/i;
System.out.println("Sum = " + sum);
}
}
(b) S = a + a2/2 + a3/3 + ...... + a10/10
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, i;
double sum = 0;
System.out.print("Enter the value of a: ");
a = in.nextInt( );
for (i = 1; i <= 10; i++)
sum += Math.pow(a, i) / i;
System.out.println("Sum = " + sum);
}
}
(c) S = (a*2) + (a*3) + ..... + (a*20)
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, i;
long sum = 0;
System.out.print("Enter the value of a: ");
a = in.nextInt( );
for (i = 2; i <= 20; i++)
sum += a * i;
System.out.println("Sum = " + sum);
}
}
(d) S = a + a2 + a3 + ...... + an
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, n, i;
long sum = 0;
System.out.print("Enter the value of a: ");
a = in.nextInt( );
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 1; i <= n; i++)
sum += Math.pow(a, i);
System.out.println("Sum = " + sum);
}
}
(e) S = 1 + 22/a + 33/a2 +....... to n terms
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, n, i;
double sum = 1.0;
System.out.print("Enter the value of a: ");
a = in.nextInt( );
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 2; i <= n; i++)

Iterative Constructs in Java 79


sum += Math.pow(i, i)/Math.pow(a, i – 1);
System.out.println("Sum = " + sum);
}
}
(f) S = 12/a + 32/a2 + 52/a3 + ...... to n terms
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, n, i, p;
double sum = 0;
System.out.print("Enter the value of a: ");
a = in.nextInt( );
System.out.print("Enter the value of n: ");
n = in.nextInt( );
p =1;
for (i = 1; i<= n; i++)
{
sum += Math.pow(p, 2)/Math.pow(a, i);
p = p+2;
}
System.out.println("Sum = " + sum);
}
}
(g) S = 1/a + 1/a2 + 1/a3 + ...... + 1/an
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int a, n, i;
double sum = 0;
System.out.print("Enter the value of a: ");
a = in.nextInt( );
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 1; i <= n; i++)
sum += 1/Math.pow(a, i);
System.out.println("Sum = " + sum);
}
}
(h) S = x/2 + x/5 + x/8 + x/11 + ....... + x/20
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int x, i;
double sum = 0;
System.out.print("Enter the value of x: ");
x = in.nextInt( );
for (i = 2; i <= 20; i = i+3)
sum += (double)x/i;
System.out.println("Sum = " + sum);
}
}
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.
For example,
Height of the pole = 9.9 feet
First attempt jumps = 5 feet
Second attempt slips down = 2% of 5 = 0.1 feet
Now, total height reached = 5 – 0.1 = 4.9 feet
Third attempt jumps = 5 feet
Thus, reaches the top of the pole (4.9 + 5 = 9.9 feet)
Number of jumps = 3
Prog. import java.util.*;
public class Jump
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
double ht, jump =5.0;
int nattempt = 1;
System.out.print("Enter height of the pole: ");
ht = in.nextDouble( );
while (jump < ht)
{
jump += 5.0;
jump –= 2 * ht/100.0;
nattempt++;
}
System.out.println("Number of attempts = " + nattempt);
}
}

Iterative Constructs in Java 81


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.]
Prog. import java.util.*;
public class Interest
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int p, t, i;
double amt, r, interest;
System.out.print("Enter Principal: ");
p = in.nextInt( );
System.out.print("Enter Rate: ");
r = in.nextDouble( );
System.out.print("Enter Time: ");
t = in.nextInt( );
amt = p;
for (i = 1; i <= t; i++)
{
interest = (amt * r * 1) / 100.0;
amt += interest;
System.out.println("Amount after " + i + " year = " + amt);
}
}
}
15. Write a menu driven program to input two positive numbers m and n
(where m>n) and perform the following tasks:
(a) Find and display the sum of two numbers without using '+' operator.
(b) Find and display the product of two numbers without using '*' operator.
(c) Find and display the quotient and remainder of two numbers
without using '/' and '%' operator.
[Hint: Successive subtraction is known as division, the last value obtained
as a result of successive subtractions is the remainder and the number
of subtractions will result in the quotient.]
Sample Input: m=5, n=2
⇒ 5 – 2 =3
⇒ 3 – 2 = 1,
Thus, Quotient = 2 and Remainder = 1
Prog. import java.util.Scanner;
public class Operations
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, m, n, p, q;
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: ");
choice = in.nextInt( );
System.out.print("Enter the value of m: ");
m = in.nextInt( );
System.out.print("Enter the value of n: ");
n = in.nextInt( );
if (m > n)
{
switch (choice)
{
case 1:
while (n > 0)
{
m++;
n– –;
}
System.out.println("Sum = " + m);
break;
case 2:
p = 0;
while (n > 0)
{
p += m;
n– –;
}
System.out.println("Product = " + p);
break;
case 3:
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!!!");
}
}

Iterative Constructs in Java 83


16. Write a menu driven program to accept a number from the user. Check
and display 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
Prog. import java.util.*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, num, num1, rnum, i, sum=0, d;
System.out.println("1. Palindrome number");
System.out.println("2. Perfect number");
System.out.print("Enter your choice: ");
choice = in.nextInt( );
System.out.print("Enter number: ");
num = in.nextInt( );
switch (choice)
{
case 1:
num1 = num;
rnum = 0;
while(num1 != 0)
{
d = num1 % 10;
num1 /= 10;
rnum = rnum * 10 + d;
}
if (rnum == num)
System.out.println(num + " is palindrome");
else
System.out.println(num + " is not palindrome");
break;
case 2:
for (i = 1; i < num; 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");
}
}
}
17. Write a menu driven program to accept a number from the user. Check
and display 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.
Prog. import java.util.*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, num, i, c=0, num1, sq, d=0;
System.out.println("1. Prime number");
System.out.println("2. Automorphic number");
System.out.print("Enter a number: ");
num = in.nextInt( );
System.out.print("Enter your choice: ");
choice = in.nextInt( );
switch (choice)
{
case 1:
for (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:
num1 = num;
sq = num * num;
while(num > 0)
{
d++;
num/=10;
}

Iterative Constructs in Java 85


int ld = (int)(sq % Math.pow(10, d));
if (ld == num1)
System.out.println(num1 + " is automorphic");
else
System.out.println(num1 + " is not automorphic");
break;
default:
System.out.println("Incorrect Choice!!");
}
}
}
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)
Prog. import java.util.*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, n, i;
double sum = 0;
System.out.println("Type 1 to print series");
System.out.println("Type 2 to find the sum of the series");
System.out.print("Enter your choice: ");
choice = in.nextInt( );
switch (choice)
{
case 1:
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 1; i <= n; i++)
System.out.print(((i * i) – 1) + " ");
break;
case 2:
for (i = 1; i <= 19; i = i + 2)
sum += i / (double)(i + 1);
System.out.println("Sum = " + sum);
break;
default:
System.out.println("Incorrect Choice!!");
}
}
}
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 numbers.
(b) Find and display 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.
Prog. import java.util.*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int ch, i, num, sum =0;
System.out.println("1. Fibonacci Series");
System.out.println("2. Sum of digits");
System.out.print("Enter your choice: ");
ch = in.nextInt( );
switch (ch)
{
case 1:
int a = 0, b = 1, c=0;
System.out.print(a + " " + b);
for (i = 3; i <= 10; i++)
{
c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
break;
case 2:
System.out.print("Enter a number: ");
num = in.nextInt( );
while (num != 0)
{
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;
default:
System.out.println("Incorrect choice!!");
}
}
}

Iterative Constructs in Java 87


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".
Prog. import java.util.*;
public class SplNumber
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int num, num1, c =0, d, dsum=0, dprod =1;
System.out.print("Enter a 2-digit number: ");
num = in.nextInt( );
num1 = num;
while (num1 != 0)
{
d = num1 % 10;
num1 /= 10;
dsum += d;
dprod *= d;
c++;
}
if (c != 2)
System.out.println("Invalid input!!");
else if ((dsum + dprod) == num)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");
}
}
21. Using switch case statement, write a menu driven program to:
(a) find and display all the factors of a number input by the user ( including
1 and 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.
Prog. import java.util.*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, num, i, f;
System.out.println("1. Factors of number");
System.out.println("2. Factorial of number");
System.out.print("Enter your choice: ");
choice = in.nextInt( );
switch (choice)
{
case 1:
System.out.print("Enter a number: ");
num = in.nextInt( );
System.out.println("The factors are: ");
for (i = 1; i < num; i++)
{
if (num % i == 0)
{
System.out.print(i + " ");
}
}
System.out.println( );
break;
case 2:
System.out.print("Enter a number: ");
num = in.nextInt( );
f = 1;
for (i = 1; i <= num; i++)
f *= i;
System.out.println("Factorial = " + f);
break;
default:
System.out.println("Incorrect Choice!!");
}
}
}
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 when it 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.
Prog. import java.util.*;
public class NivenNum
{
public static void main(String args[ ])

Iterative Constructs in Java 89


{
Scanner in = new Scanner(System.in);
int num, num1, d, dsum =0;
System.out.print("Enter a number: ");
num = in.nextInt( );
num1 = num;
while (num1 != 0)
{
d = num1 % 10;
num1 /= 10;
dsum += d;
}
if (dsum != 0 && num % dsum == 0)
System.out.println(num + " is a Niven number");
else
System.out.println(num + " is not a Niven number");
}
}
23. Write a program to accept a number and check whether it is a 'Spy
Number' or not. (A number is a 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
Prog. import java.util.*;
public class SpyNum
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int num, num1, d, sum = 0, prod =1;
System.out.print("Enter a number: ");
num = in.nextInt( );
num1 = num;
while (num1 > 0)
{
d = num1 % 10;
sum += d;
prod *= d;
num1/= 10;
}
if (sum == prod)
System.out.println(num + " is Spy Number");
else
System.out.println(num + " is not Spy Number");
}
}
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 –................... 20; where x = 2
(b) To display the series:
1, 11, 111, 1111, 11111
For an incorrect option, an appropriate error message should be
displayed.
Prog. import java.util.*;
public class Menu
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, sum =0, i, term;
System.out.println("1. Sum of the series");
System.out.println("2. Display series");
System.out.print("Enter your choice: ");
choice = in.nextInt( );
switch (choice)
{
case 1:
for (i = 1; i <= 20; i++)
{
term = (int)Math.pow(2, i);
if (i % 2 == 0)
sum –= term;
else
sum += term;
}
System.out.println("Sum=" + sum);
break;
case 2:
term = 1;
for (i = 1; i <= 5; i++)
{
System.out.print(term + " ");
term = term * 10 + 1;
}
break;
default:
System.out.println("Incorrect Choice!!");
}
}
}

Iterative Constructs in Java 91


Chapter 9

Nested for Loops

III. Differentiate between the following:


1. Nested if and nested loop
Ans. Nested if Nested loop
Nested if statement is a statement Nested loop is a loop programmed
where an 'if' statement is placed within another loop.
within another 'if' statement.
Nested if is used to do conditional Nested loops are used to execute
checks at multiple levels. one iterative set of statements inside
another iterative set.

2. Break and continue


Ans. Break Continue
Break statement is used to terminate It is used to postpone the further
a block in which it exists. execution of the loop and move to
the next iteration.
Break statement can be used in Continue statement is used only in
switch-case as well as in loop the loop statement.
statements.

3. Labelled break and Unlabelled break


Ans. Labelled break Unlabelled break
In labelled break, a label is used In unlabelled break, label is not used
with the break statement which will with the break statement which will
allow the control to move out of the allow the control to move out of the
label block. inner most block.
Labelled break can be used to exit Unlabelled break only exits from the
out of a deeply nested set of loops. loop within which it is enclosed.

IV. Answer the following questions:


1. What do you mean by a nested loop?
Ans. Nested loop is defined as a loop programmed within another loop. It
is used in such a way that the inner loop repeats a number of times for
each repetition of the outer loop.
2. In what situation you need a nested loop?
Ans. Nested loops are used when the problem statement requires the use of
loop inside another loop. The inner loop executes for the defined period
for every single iteration of the outer loop. Nested loops are generally
used in sorting problems, pattern printing, matrix multiplication etc.

92
3. How will you terminate outer loop from the block of the inner loop?
Ans. We can terminate outer loop from the block of the inner loop by using
Labelled break statement (break outer).
4. What do you mean by labelled break statement? Give an example.
Ans. Sometimes, it may happen that the outer loop is to be terminated, if a
condition is met in the inner loop. In this situation, the labelled break
statement will be used to serve the purpose.
For example,
int i, j;
outer:
for(i=1;i<=5;i++)
{
for(j=1;j<=3;j++)
{
System.out.println(i*j);
if (j ==2)
break outer; //Labelled break
}
}
5. Write down the syntax of the nested loop.
Ans. The syntax of the nested loop:

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


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

executable statement(s)
………………………………………………………………………………………………
}
}

V. Give the output of the following snippets based on nested loops:


1. int i, j;
for (i=0; i<4; i++)
{
for (j=i; j>=0; j– –)
System.out.print(j);
System.out.println( );
}
Output: 0
10
210
3210
2. int y,p;
for (int x=1; x<=3; x++)
{
for (y=1; y<=2; y++)

Nested for Loops 93


{
p = x * y;
System.out.print(p);
}
System.out.println( );
}
Output: 12
24
36
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
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:

1
12

1234
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
VI. Solutions to Unsolved Java Programs:
1. Write a program to display the Mathematical Tables 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
Prog. public class Tables
{
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));
}
}
}
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.]
Prog. import java.util.*;
public class Prime
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, i, j, c;
System.out.println("Enter any 20 numbers");
for (i = 1; i <= 20; i++)
{
n = in.nextInt( );
c=0;
for (j = 1; j <= n; j++)
{
if (n % j == 0)
c++;
}
if (c==2)
System.out.println(n + " is a Prime Number");
}
}
}

Nested for Loops 95


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)
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, i, j;
double sum = 0.0, num, dnm;
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 2; i <= n; i++)
{
num = 0.0; dnm = 1.0;
for (j = 1; j <= i; j++)
{
num += j;
dnm *= j;
}
sum = sum + (num/dnm);
}
System.out.println("Sum=" + sum);
}
}
4. Write two separate programs to generate the following patterns using
iteration (loop) statements:
(a) *
*#
*# *
*# * #
*# * # *
Prog. public class Pattern
{
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( );
}
}
}
(b) 5 4 3 2 1
5432
543
54
5
Prog. public class Pattern
{
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( );
}
}
}
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]
Prog. import java.util.*;
public class Factorial
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int m, n, i, j, fact;
System.out.print("Enter the value m: ");
m = in.nextInt( );
System.out.print("Enter the value n: ");
n = in.nextInt( );
if (m < n && m > 0 && n > 0)
{
for (i = m; i <= n; i++)
{
fact = 1;
for (j = 1; j <= i; j++)
fact *= j;
System.out.println("Factorial of " + i + " = " + fact);
}
}
else
System.out.println("Invalid Input!!");
}
}

Nested for Loops 97


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.]
Prog. import java.util.*;
public class MenuPrime
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int choice, i, j, c;
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: ");
choice = in.nextInt( );
switch (choice)
{
case 1:
System.out.println("Prime numbers between 1 – 100:");
for (i = 1; i <= 100; i++)
{
c=0;
for (j = 1; j <= i; j++)
{
if (i % j == 0)
c++;
}
if (c==2)
System.out.println(i);
}
break;
case 2:
System.out.println("Non-prime numbers between 1 – 100:");
for (i = 2; i <= 100; i++)
{
c=0;
for (j = 1; j <= i; j++)
{
if(i % j == 0)
c++;
}
if (c!=2)
System.out.println(i);
}
break;
default:
System.out.println("Incorrect Choice!!");
}
}
}
7. Write a program to input a number and display all its prime factors.
Sample Input: 84
Sample Output: 2, 2, 3, 7
Prog. import java.util.*;
public class PrimeFactors
{
public static void main(String args[ ])
{
int num,i;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number :");
num = sc.nextInt( );
System.out.println("The prime factors are :");
for(i = 2; i< num; i++)
{
while(num%i == 0)
{
System.out.println(i+" ");
num = num/i;
}
}
if(num >2)
System.out.println(num);
}
}
8. Write a program to input a number and check whether it is a twisted
prime or not.
A number is said to be a twisted prime, if the number as well as its reverse
is also a prime and display an appropriate message accordingly.
Sample Input: 37
Reversed Number: 73
Sample Output: 37 and 73 both are prime. So, it is a 'Twisted Prime'.
Prog. import java.util.*;
public class TwistedPrime
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int num, i, c =0, num1, d, rnum=0, j, c1=0;
System.out.print("Enter number: ");
num = in.nextInt( );
for (i = 1; i <= num; i++)
{
if (num % i == 0)
c++;
Nested for Loops 99
}
if (c==2)
{
num1 = num;
rnum = 0;
while (num1 != 0)
{
d = num1 % 10;
num1 /= 10;
rnum = rnum * 10 + d;
}
}
for (j = 1; j <= rnum; j++)
{
if (rnum % j == 0)
c1++;
}
if (c1==2)
System.out.println(num + " is a twisted prime number");
else
System.out.println(num + " is not a twisted prime number");
}
}
9. Write a program to display the factorial of any ten numbers.
[Hint: Factorial of 5! = 5*4*3*2*1]
Sample Input: 8
Factorial of 8 = 40320
Factorial of 11 = 39916800 and so on.
Prog. import java.util.*;
public class Factorial
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, i, j;
for (i = 1; i <= 10; i++)
{
System.out.print("Enter a number: ");
n = in.nextInt( );
long f = 1;
for (j = 1; j <= n; j++)
{
f *= j;
}
System.out.println("Factorial of " +n+ ": "+f);
}
}
}
10. Write a program to input a number. Calculate and display the factorial
of each digit.
Sample Input: 365
Factorial of 5= 120
Factorial of 6= 720
Factorial of 3= 6
Prog. import java.util.*;
public class DFactorial
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, d, i, j;
System.out.print("Enter a number: ");
n = in.nextInt( );
for (i = 1; i <= n; j++)
{
d = n%10;
long f = 1;
for (j = 1; j <= d; j++)
{
f *= j;
}
System.out.println("Factorial of " +d+ ": "+f);
n = n/10;
}
}
}
11. Write a program to input a three-digit number. Display its digits raised
to the power of their respective position.
Sample Input: 465
Sample Output: 51 = 5
62 = 36
43 = 64
[Hint: 5 is at Unit's place, 6 is at Ten's place and 4 is at Hundredth's
place.]
Prog. import java.until.*;
class Display
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int i, n, d, p=1;
System.out.print("Enter a three-digit number:");
n=in.nextInt( );
System.out.println("Value of the digits are:");
while(n>0)

Nested for Loops 101


{
d=n%10;
System.out.println((int)Math.pow(d, p));
n=n/10;
p++;
}
}
}
12. Write a program to display all composite numbers from 1 to 100.
A number is said to be composite, if it has two or more factors excluding
1 and the number itself.
Sample Input: 6
Sample Output: Factors of 6 are 2 and 3.
Hence, 6 is a composite number.
Few composite numbers are 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, …..
Prog. public class Composite
{
public static void main(String args[ ])
{
int n, c, i, j;
System.out.println("Composite numbers from 1 - 100 :");
for (i = 1; i <= 100; i++)
{
c=0;
for (j = 1; j <= i; j++)
{
if (i % j== 0)
c++;
}
if (c > 2)
System.out.println(i);
}
}
}
13. In a school, there are four different sections. In each section, there are 40
students who have appeared for ICSE Examination. Write a program to
input percentage marks of each student of each section. Calculate and
display the number of students of each section, securing 95% and above
in the council examination.
Prog. import java.util.*;
public class Result
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int i, c, j, a = 65;
for (i = 1; i <= 4; i++)
{
c=0;
System.out.println("Enter % marks of each student one by one: ");
for (j = 1; j <= 40; j++)
{
double pm = in.nextDouble( );
if (pm >= 95)
c++;
}
System.out.println("Number of students getting 95% or more in
Section:"+ (char)(a)+" = "+c);
a++;
}
}
}
14. Write programs to find the sum of the given series:
(a) 1 + (1/2!) + (1/3!) + (1/4!) + ........... + (1/n!)
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, i, j;
double sum = 0;
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 1; i <= n; i++)
{
long f = 1;
for (j = 1; j <= i; j++)
{
f *= j;
}
sum += (1.0/f);
}
System.out.println("Sum=" + sum);
}
}
(b) 1 + (1+2) + (1+2+3) + .......... + (1+2+3+ ...... + n)
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, sum = 0, i, j;
System.out.print("Enter the value of n: ");
n = in.nextInt( );

Nested for Loops 103


for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++)
{
sum += j;
}
}
System.out.println("Sum=" + sum);
}
}
(c) 1 + (1*2) + (1*2*3) + .......... + (1*2*3* .......* n)
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, sum = 0, i, j, p;
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 1; i <= n; i++)
{
p = 1;
for (j = 1; j <= i; j++)
{
p *= j;
}
sum += p;
}
System.out.println("Sum=" + sum);
}
}
(d) 1 + 1/(1+2) + 1/(1+2+3) + .......... + 1/(1+2+3+. ... +n)
Prog. import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
int n, i, j, t;
double sum = 0.0;
System.out.print("Enter the value of n: ");
n = in.nextInt( );
for (i = 1; i <= n; i++)
{
t = 0;
for (j = 1; j <= i; j++)
{
t+= j;
}
sum += (1.0/t);
}
System.out.println("Sum=" + sum);
}
}
(e) (1/2) + (1/3) + (1/5) + (1/7) + (1/11) + .......... + (1/29)
public class Series
{
public static void main(String args[ ])
{
int i, j;
double sum = 0.0;
for (i = 2; i < 30; i++)
{
boolean isPrime = true;
for (j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
sum += 1.0/i;
}
System.out.println("Sum=" + sum);
}
}
15. Write the programs in Java to display the following patterns:
(a) 1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = i; j >= 1; j– –)
{
System.out.print(j + " ");
}
System.out.println( );
Nested for Loops 105
}
}
}
(b) 1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 5; i >= 1; i– –)
{
for (j = 1; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println( );
}
}
}
(c) 5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 5; j >= i; j– –)
{
System.out.print(j + " ");
}
System.out.println( );
}
}
}
(d) 1 3 5 7 9
1 3 5 7
1 3 5
1 3
1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 9; i >= 1; i –= 2)
{
for (j = 1; j <= i; j += 2)
{
System.out.print(j + " ");
}
System.out.println( );
}
}
}
(e) 5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 5; i >= 1; i– –)
{
for (j = 5; j >= i; j– –)
{
System.out.print(j + " ");
}
System.out.println( );
}
}
}
(f) 1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 1; i <= 5; i++)
{

Nested for Loops 107


for (j = i; j <= 5; j++)
{
System.out.print(j + " ");
}
System.out.println( );
}
}
}
(g) 9 9 9 9 9
7 7 7 7 7
5 5 5 5 5
3 3 3 3 3
1 1 1 1 1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 9; i >= 1; i –= 2)
{
for (j = 1; j <= 5; j++)
{
System.out.print(i + " ");
}
System.out.println( );
}
}
}
(h) 9
7 9
5 7 9
3 5 7 9
1 3 5 7 9
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 9; i >= 1; i –= 2)
{
for (j = i; j <= 9; j += 2)
{
System.out.print(j + " ");
}
System.out.println( );
}
}
}
(i) 9
9 7
9 7 5
9 7 5 3
9 7 5 3 1
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j;
for (i = 9; i >= 1; i –= 2)
{
for (j = 9; j >= i; j –= 2)
{
System.out.print(j + " ");
}
System.out.println( );
}
}
}
(j) 1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Prog. public class Pattern
{
public static void main(String args[ ])
{
int i, j, p=1;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
System.out.print(p+ " ");
p++;
}
System.out.println( );
}
}
}

Nested for Loops 109


Chapter 10

Computing and Ethics

II. Write short notes on:


1. Software Piracy
Ans. Software piracy means illegally copying, reproduction, distribution or
use of software. Making duplicate copies not only promotes immorality
but also affects the sale of the original software. It is also defined as the
act of stealing software that is legally protected.
2. Spam
Ans. Spam is referred to as the unwanted e-mails through which an adversary
can pass on viruses and fake messages. Most spam messages contain
lucrative advertisement and message heading to compel users to open
the messages. Spams waste user's valuable time and also waste memory
space of the user's PC.
3. Cyber Crime
Ans. Cyber crime can be defined as an online crime, using computer and
the Internet medium. It mainly involves stealing personal information,
passwords, credit card/debit card details, bank accounts, etc. with
the intent of causing harm to the individual. Cyber crimes may create
problems for the individual being infected, their family and the society
to which the individual belongs to.
4. Hacking
Ans. Hacking can be defined as an attempt to exploit a computer system. It
mainly involves unauthorised access viz. fraud, stealing personal data
over a computer and the network.
5. Software Copyright
Ans. Software copyright is defined as the legal custody of a software system.
The legal custody of the software can be held by paying the licencing
cost of the software to the developers or the distributors of the software.
Software copyright prohibits the users of a software program from
making copies without the permission of the person/company concerned
which issues the license for the program.
6. Cyber Law
Ans. Cyber law defines the legal ways of gainfully utilising the internet
or computer systems. Cyber laws prevent illegal use of the internet
technology for unlawful purposes. India became the 21st nation to adopt
Cyber law in the year 2000.
III. Answer the following questions:
1. What do ethics mean? Mention at least five ethical values related to
computers.
Ans. In the field of information technology, ethical responsibilities are
known as computer ethics which regulate the use of computers. Some

110
common issues of computer ethics include intellectual property rights
(such as copyrighted electronic content), privacy concerns, and how the
computers affect society.
Five ethical values related to computers are as follows:
• Do not install or uninstall any software without prior permission.
• Never move the peripherals from one place to other unnecessarily.
• While working in a computer lab/room, you must maintain the rules
and regulations of the lab.
• Do not try to steal the secret information of any other computer.
• Do not copy or use proprietary software for which you have not paid.
2. How will you protect your data on the Internet?
Ans. The different ways to protect data on the internet are as follows:
• Do not disclose your passwords to your friends. They may open
different websites and misuse your accounts.
• Do not download unwanted software/free software from the web. It
may corrupt your system.
• Do not read unwanted e-mails, as they might be carrying viruses.
• Install high quality antivirus programs or signatory antivirus of a
reputed company in your computer to protect against viruses.
3. What is meant by malicious code?
Ans. Malicious code refers to a new kind of threat, which corrupts the system
and leaks personal data in due course of time. It is virtually impossible
to recognise such malicious code attacks.
Malicious code is any program that acts in unexpected and potentially
damaging ways (e.g., Trojan Horse). Malicious code can attack
institutions at either the server or the client level. It can also attack into
the infrastructure of a system (i.e., it can change, delete, insert or even
transmit data outside the institution).
Malicious code may be downloaded by the user in the following ways:
• While working on e-mails
• At the time of web surfing
• While downloading files/documents/software
Protection from malicious code involves limiting the capabilities of the
servers and web applications to only functions necessary to support the
operations. User of firewalls and other such network protection devices
prevents ingress of malicious code through the network. There must be
user awareness and training programs to overcome such situations.
4. How will you protect your system from malicious intent and malicious
code?
Ans. You can protect your computer system by using it in a proper and
systematic way. The following precautions can protect your system from
attackers:
• You should use high quality antivirus/signature-based antivirus on
your computer system.
• If you have started downloading a software that you suspect to be
malicious then stop the downloading immediately.
• You should avoid the use of pirated software or unauthorised software
which might cause great damage to your system in due course.

Computing and Ethics 111


• You should also avoid using memory cards and pen drives of others
which may be virus infected. If it is necessary to use them, then scan
them first as a safety measure.
• If you find any e-mail coming from unknown sources, then do not
open it and delete it from your computer system.
5. What are the advantages of cyber law? Mention any five.
Ans. The main advantages of cyber law are as follows:
• Companies shall now be able to carry out electronic commerce using
the legal infrastructure provided by the Act.
• Digital signatures have also been given legal validity and sanction in
the Act.
• The Act opens the doors for the entry of corporate companies in the
business of being certifying authorities for issuing Digital Signatures
Certificates.
• The Act allows the Government to issue notifications on the web, thus
heralding e-governance.
• The Act enables companies to file any form, application or any
other document with any office, authority, body or agency owned
or controlled by the appropriate Government in electronic form by
means of such electronic form as may be prescribed by the appropriate
Government.
6. How will you avoid software piracy? Explain.
Ans. The ways to avoid software piracy are as follows:
• Always buy your software from a reputed organisation. When in doubt,
you can contact through e-mail for guidance.
• Make sure that your software comes with a licensing agreement,
original disk and authentic packaging.
• Avoid buying multiple software titles from different publishers on a
single disk.
• If the seller provides a serial number other than the one mentioned on
package, it indicates that the software is not authentic.
7. What are the different ways to stop spam?
Ans. We can stop spam by installing a good antivirus software (also known
as filters) in our computer system. Some useful filters are Spam Attack,
Spam Hater, etc. Moreover, as far as possible, try to avoid reading e-mail
messages from unrecognised senders and delete them.
8. What role can you play to stop cyber crimes? Explain.
Ans. Cyber crimes affect individuals viz. loss of data or personal information,
online criminal activity etc. In order to stop cyber crimes following
activities can be undertaken:
• Always educate the needy about cyber crime issues and relevant laws.
• Report cyber criminal activities to legal agencies to prevent others
from being affected.
• Never download pirated software.
• To ensure privacy, never share password and OTP with others.
• Ensure that your computer system and installed software are timely
updated.
Chapter 11
More on Basic Input/Output
(Scanner and Printer Classes)

III. Answer the following:


1. What do you mean by the Scanner class?
Ans. The Scanner class is a development in Java which allows user to input
the values of various data types. The Scanner class basically works on
the principle of 'Tokens' in the set of values input from the console.
2. Write syntax along with an example to create a scanner object.
Ans. Syntax: Scanner sc = new Scanner(System.in);
Where, sc is the scanner class object created in the above line. It can be
used to use any available method in Scanner class documentation.
3. Mention the syntax to use '?' as a token delimiter.
Ans. Scanner sc = new Scanner(System.in);
sc.useDelimiter ( "?" );
4. Write down the use of nextInt( ) method.
Ans. It receives the next token which can be expressed as an integer from the
scanner object. It is stored in an integer type variable.
5. What is the application of hasNextBoolean( ) method?
Ans. This function returns true if the next token can be expressed as a boolean
type value otherwise, it returns false.
6. Name the package which can be imported to use Scanner class.
Ans. Scanner class is available in the system package java.util.*.
7. In what way can the following data be read from the scanner object?
(a) Integer type
Ans. Scanner sc = new Scanner(System.in);
int m = sc.nextInt( );
(b) Float type
Ans. Scanner sc = new Scanner(System.in);
float m = sc.nextFloat( );
(c) Double type
Ans. Scanner sc = new Scanner(System.in);
double m = sc.nextDouble( );
(d) String type
Ans. Scanner sc = new Scanner(System.in);
String str = sc.next( );
(e) Boolean type
Ans. Scanner sc = new Scanner(System.in);
boolean bv = sc.nextBoolean( );

113
IV. Differentiate between the following:
1. Scanner object and BufferedReader object
Ans. Scanner Object BufferedReader Object
It works on the principle of 'Tokens' The buffered allows storing of input
into specific types like int, float, so that the instant supply of data
boolean, etc. as an input. can be done to the CPU without
any delay.
It works in JDK 1.5 version or more. It works in JDK 1.1 version onwards.

2. nextFloat( ) and nextDouble( )


Ans. nextFloat( ) nextDouble( )
It receives the next token which This method receives the next token
can be expressed as a floating type which can be expressed as a double
value. type value.
float p; double p;
p= in.nextFloat( ); p= in.nextDouble( );

3. next( ) and nextLine( )


Ans. next( ) nextLine( )
The next( ) method accepts a token This method receives a sentence or a
as a string through the scanner line of text which contains spaces in
object. between the words, excluding any
terminator at the end.
String str1; String str2;
str1= in.next( ); str2= in.nextLine( );

4. hasNext( ) and hasNextLine( )


Ans. hasNext( ) hasNextLine( )
This function returns true if the This function returns true if the
scanner object has another token in scanner object has another line in
its input, otherwise it returns false. its input, otherwise it returns false.

5. hasNextInt( ) and hasNextBoolean( )


Ans. hasNextInt( ) hasNextBoolean( )
This function returns true if the next This function returns true if the
token in the scanner object can be next token can be expressed as a
interpreted as an int value. boolean type value otherwise, it
returns false.

V. Unsolved Programs:
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 the user enters a non-

numeric character.
c F – 32
Formula: = =
 5 9
Prog. import java.util.Scanner;
public class Convert
{
public static void main(String args[ ])
{
Scanner in = new Scanner(System.in);
System.out.println("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.println("Enter temp. in Fahrenheit to continue or a
character to quit: ");
}
}
}
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.
Prog. import java.util.Scanner;
public class MaxMin
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int max, min, n, i, num;
System.out.print("Enter first number: ");
n = sc.nextInt( );
max = n;
min = n;
for(i = 2; i<=50 ; i++)
{
System.out.print("Enter remaining numbers one by one : ");
num = sc.nextInt( );
if(num>max)
max = num;
if(num < min)
min = num;
}
System.out.println("Maximum of fifty numbers : " + max);
System.out.println("Minimum of fifty numbers : " + min);
}
}
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.

More on Basic Input/Output (Scanner and Printer Classes) 115


Sample Input:
Enter your choice: 1 Enter your choice 2
Sample Output: Sample Output:
* *****
** ****
*** ***
**** **
***** *
Prog. import java.util.Scanner;
public class Pattern
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n, i, j;
System.out.println("Enter 1 for triangle and enter 2 for inverted
triangle.");
System.out.print("Enter your choice: ");
n = sc.nextInt( );
switch (n)
{
case 1:
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
System.out.print("* ");
}
System.out.println( );
}
break;
case 2:
for (i = 5; i >= 1; i--)
{
for (j = 1; j <= i; j++)
{
System.out.print("* ");
}
System.out.println( );
}
break;
default:
System.out.println("Incorrect choice!!");
}
}
}
4. In a competitive examination, a set of 'N' number of questions results
in 'True' or 'False'. Write a program by using Scanner class to accept the
answers. Print the frequency of 'True' and 'False'.
Prog. import java.util.Scanner;
public class Frequency
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n, i, t=0, f=0;
System.out.print("Enter number of questions: ");
n = sc.nextInt( );
for(i = 1; i <=n ; i++)
{
System.out.print("Enter the answer true or false: ");
boolean val = sc.nextBoolean( );
if (val)
{
t++;
}
else
{
f++;
}
}
System.out.println("Frequency of true : "+t);
System.out.println("Frequency of false : "+f);
}
}
5. Write a program to accept a sentence in mixed case. Find the frequency
of vowels in each word and print the words along with their frequencies
in separate lines.
Sample Input: We are learning scanner class
Sample Output: Word Frequency of vowels
We 1
are 2
learning 3
scanner 2
class 1
Prog. import java.util.Scanner;
public class Frequency
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println("To quit program: Enter a sentence ending with
space and with '.' ");
String n;
int c = 0;
while (true)
{

More on Basic Input/Output (Scanner and Printer Classes) 117


n = sc.next( );
if(n.equals("."))
{
break;
}
for (int i = 0; i < n.length( ); i++)
{
char ch = n.charAt(i);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'
||ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
c++;
}
System.out.println(n);
System.out.println("Frequency of vowel: " + c);
c = 0;
}
}
}
6. Write a program by using Scanner class to input a sentence. Display the
longest word along with the number of characters in it.
Sample Input: We are learning scanner class in Java
Sample Output: The longest word: learning
Number of characters: 8
Ans. import java.util.Scanner;
public class LongestWord
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println("To quit program: Enter a sentence ending with
space and with '.' ");
String n,s = "";
int c = 0;
while (true)
{
n = sc.next( );
if(n.equals("."))
break;
int p = n.length( );
if(p > c)
{
s = n;
c = p;
}
}
System.out.println("Longest word : "+s);
System.out.println("Number of characters : "+c);
}
}
7. Write a program by using Scanner class to input a sentence. Print each
word of the sentence along with the sum of the ASCII codes of its
characters.
Ans. import java.util.Scanner;
public class SumOfCodes
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println("To quit program: Enter a sentence ending with space and with '.' ");
String n;
int sum = 0;
while (true)
{
n = sc.next( );
if(n.equals("."))
{
break;
}
for (int i = 0; i < n.length( ); i++)
{
sum = sum + n.charAt(i);
}
System.out.println("Word : " + n);
System.out.println("Sum of ASCII : "+sum);
sum = 0;
}
}
}
8. Write a program by using Scanner class to accept a set of positive and
negative numbers randomly. Display all the negative numbers first and
then all the positive numbers without changing the order of the numbers.
Sample Input: 1, 5, –2, 6, –3, –5, 8, –4, 9, 12
Sample Output: –2, –3, –5, –4, 1, 5, 6, 8, 9, 12
Prog. import java.util.Scanner;
public class PositiveNegative
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n, i, num;
System.out.print("Enter the value of n :");
n = sc.nextInt( );
String negative = "", positive = "";
for(i = 1;i<=n;i++)
{
System.out.print("Enter the number :");
num = sc.nextInt( );

More on Basic Input/Output (Scanner and Printer Classes) 119


if(num < 0 )
{
if(i==n)
negative = negative + num;
else
negative = negative + num + ',';
}
if(num > 0 )
{
if(i==n)
positive = positive + num;
else
positive = positive + num + ',';
}
}
System.out.println(negative+positive);
}
}
9. Write a program to generate and display random numbers between 1
to N by using scanner class taking N from the console.
Prog. import java.util.Scanner;
public class RandomNumber
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n, i;
System.out.println("Enter the value of n.");
System.out.println("Random number between 1to "+n" are:";
n = sc.nextInt( );
for(i = 1; i <= n; i++)
{
double p = (Math.random( )*n)+1;
System.out.println(p);
}
}
}
10. Consider a String:
THE COLD WATER AND THE HOT WATER GLASSES ARE KEPT ON
THE TABLE
Write a program by using Scanner class to enter the string and display
the new string after removing repeating token 'THE'.
The new string is:
COLD WATER AND HOT WATER GLASSES ARE KEPT ON TABLE
Prog. import java.util.Scanner;
public class Duplicate
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String s1 = "";
System.out.println("To quit program: Enter a string ending with space and with '.' ");
while (true)
{
String n = sc.next( ).toUpperCase( );
if (n.equals("."))
break;
if(!n.equals("THE"))
s1 = s1 + " "+n;
}
System.out.println("Sentence after removing 'THE' : " + s1);
}
}
11. Using Scanner class, write a program to input a string and display all
the tokens of the string which begin with a capital letter and end with
a small letter.
Sample Input: The capital of India is New Delhi
Sample Output: The India New Delhi
Prog. import java.util.Scanner;
public class CaptialLetter
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String s1 = "";
System.out.println("To quit program: Enter a string ending with space and with '.' ");
while (true)
{
String n = sc.next( );
if (n.equals("."))
break;
if(Character.isUpperCase(n.charAt(0)))
s1 = s1 + " "+n;
}
System.out.println("Sentence : " + s1);
}
}
12. Write a program to input a string by using Scanner class. Display the
new string which is formed by the first character of each string.
Sample Input: Automated Teller Machine
Sample Output: ATM
Prog. import java.util.Scanner;
public class Acronym
{
public static void main(String args[ ])
{

More on Basic Input/Output (Scanner and Printer Classes) 121


Scanner sc = new Scanner(System.in);
String s1 = "";
System.out.println("To quit program: Enter a string ending with space and with '.' ");
while (true)
{
String n = sc.next( );
if (n.equals("."))
break;
s1 = s1 + n.charAt(0);
}
System.out.println("Result : " + s1);
}
}
13. Consider the following statement:
"26 January is celebrated as the Republic Day of India"
Write a program (using Scanner class) to change 26 to 15; January to
August; Republic to Independence and finally print as:
"15 August is celebrated as the Independence Day of India"
Prog. import java.util.Scanner;
public class Replace
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String s1 = "";
System.out.println("To quit program: Enter a string ending with space and with '.' ");
while (true)
{
String n = sc.next( );
if(n.equals("."))
break;
else if (n.equals("26"))
s1 = s1 + "15";
else if (n.equals("January"))
s1 = s1 + " " +"August";
else if (n.equals("Republic"))
s1 = s1 + " " +"Independence";
else
s1 = s1 + " " + n;
}
System.out.println("Result : " + s1);
}
}
14. Write a program by using Scanner class to input principal (P), rate (R)
and time (T).
Calculate and display the amount and compound interest.
Use the formula:
A = P(1 + (R / 100))T
CI = A – P
Prog. import java.util.Scanner;
public class Interest
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int principal, rate, time;
double ci, amount;
System.out.print("Enter Principal :");
principal = sc.nextInt( );
System.out.print("Enter rate% :");
rate = sc.nextInt( );
System.out.print("Enter time :");
time = sc.nextInt( );
amount = principal * (Math.pow((1 + ((double) rate /100)), time));
ci = amount – principal;
System.out.println("Amount : "+amount);
System.out.println("Compound Interest : "+ci);
}
}

More on Basic Input/Output (Scanner and Printer Classes) 123

You might also like