Class 9 Computer
Class 9 Computer
Class 9 Computer
Question 1
An act of using essential features without including background details is called Data
Abstraction.
Question 2
Question 3
Question 4
An object has unique identity through which it may differ with some characteristics and
behaviour.
Question 5
Question 6
Question 7
The process by which a class acquires the property of another class is known as inheritance.
Question 8
Question 1
In assembly level language, the instructions are given in terms of 0's and 1's.
False
Question 2
Question 3
Question 4
Question 5
A process according to which a class acquires the characteristics from another class is
Encapsulation.
False
Question 6
Question 7
Question 8
Function is a set of objects that share the common state and behaviour.
False
Question 10
Question 1
Question 2
(a) BASIC
(b) COBOL
Question 3
(a) PASCAL
(b) ALGOL
Question 4
Question 5
(a) Television
(b) Car
Question 6
(a) Encapsulation
(b) Inheritance
Question 1
Question 2
Data Abstraction
Data Abstraction is the act of representing the essential features without knowing the
background details. Example of Data Abstraction is given here.
Question 3
Encapsulation
Wrapping of data and functions that operate on that data into a single unit is called
Encapsulation. Example of Encapsulation is given here.
Question 4
For the processor to perform any computation, we need to give the instructions and
data as a sequence of 0's & 1's. This binary sequence that a processor understands is
known as its Machine Level language. Machine Level language is made up of
instructions and data that are all binary numbers. Machine Level language of a
processor differs from vendor to vendor. So programs written in Machine Level
language of one type of processors will not work on a different type of processor.
Question 5
Polymorphism
Question 7
Inheritance
Inheritance enables new classes to receive or inherit the properties and methods of
existing classes. Example of Inheritance is given here.
Question 8
In Assembly Level language, instructions are written in more english like words knowns
as mnemonics. These instructions are not understood by the processor directly. They
are converted into equivalent Machine Level instructions through a translator program
called Assembler. Assembly Level language is machine dependent that makes it
unsuitable for writing portable programs that can execute across machines.
Distinguish between
Question 1
The stress is put on data rather than functions. The stress is put on function rather than data.
The data is restricted, to be used in a specific It allows data to flow freely throughout the
program area. program.
High Level language is machine independent. Low Level language is machine dependent.
High Level language is human friendly so it is Low Level language is machine friendly so it is
easy to understand for programmers. difficult to understand for programmers.
High Level language needs a compiler or Low Level language might need a assembler for
interpreter for translation to machine code. translation to machine code.
Programs written in High Level language are Programs written in Low Level language are hard
easier to modify and debug. to modify and debug.
Question 3
Compiler Interpreter
It converts the whole source program into the It converts the source program into the object program, one
object program at once. line at a time.
It displays the errors for the whole program It displays the error one line at a time and only after fixing
together, after the compilation. that error the control goes to the next line.
Question 1
Question 2
Question 3
Question 4
Encapsulation restricts the free flow of data from one object to another. The data and
functions are wrapped together in an object in such a way that the data of a particular
object can only be used in associated functions. Thus, Encapsulation helps in protecting
the data from unauthorised access.
Question 6
Chapter 1 - Unit 2
Introduction to Java
Class 9 - APC Understanding Computer
Applications with BlueJ
Question 1
Question 2
Question 3
Machine codes are expressed using alphanumeric characters.
False
Question 4
Question 5
Question 1
Question 2
In Java, the package used to find power raised to any base is java.lang.
Clarification: Math class inside java.lang package contains Math.pow that is used to find
power raised to any base. The official documentation is provided here.
It should not be confused with java.math package which contains BigDecimal, BigInteger
and MathContext classes.
Question 3
The words which are preserved with the system are called keywords/reserved words, that can
not be used as variable names in Java programming.
Question 4
Question 5
Question 1
James Gosling developed Java programming language. It was initially called Oak.
Question 2
In 1991, at Sun Microsystems, Green team led by James Gosling started working on a
new technology for consumer electronic devices. Over the next 18 months, in 1992 the
team created a new programming language which they called “Oak”. By 1994 the team
refocussed their efforts towards internet programming with Oak as it didn't find much
traction in consumer electronics space. Oak was renamed to Java and on 23rd of May
1995, Sun microsystems made its first public release.
Question 3
Question 4
(a) A compiler
(b) An interpreter
An interpreter is a program that reads a source program line by line, converts each line
into its equivalent machine code and executes it. As it reads the program line by line so
the errors are reported one by one.
Question 5
Java Virtual Machine (JVM) is a software that takes Bytecode as input, converts it into
Machine code of the specific platform it is running on and executes it. JVM is platform
specific, each platform has its own JVM.
Question 6
1. java.lang
2. java.io
3. java.util
Question 7
In Java, a reserved word is a word that has a predefined meaning in the language. Due
to this, reserved words can’t be used as names for variables, methods, classes or any
other identifier. Reserved words are also known as keywords. Five commonly used Java
reserved words are:
1. public
2. class
3. int
4. double
5. char
Question 8
Distinguish between:
Compiler Interpreter
It translates the whole source program into target It translates the source program into target
program at once. program one line at a time.
All the errors found during compilation are Errors are displayed line by line as each line is
displayed together at once. translated and executed.
JDK or Java Development Kit is the set of tools BlueJ is an IDE or Integrated Development
required to compile and run Java programs Environment for developing Java programs.
JDK includes tools like Compiler, Interpreter, Java BlueJ provides tools like Code Editor, Debugger,
libraries, etc. Syntax Highlighting, etc.
Question 9
Question 10
Question 11
What is BlueJ?
BlueJ is an integrated development environment for Java. It was created for teaching
Object Oriented programming to computer science students.
Question 12
Question 13
java.lang
Question 14
What are the points to be taken care while naming a class in a Java program?
A class name should be a valid Java identifier i.e. it should follow the below three rules:
1. Name of the class should be a sequence of alphabets, digits, underscore and dollar sign
characters only.
2. It should not start with a digit.
3. It should not be a keyword or a boolean or null literal.
Question 15
Java is case sensitive means that it distinguishes between upper case and lower case
characters. Consider the below code snippet:
int studentMarks;
StudentMarks = 85;
This will give a compilation error as Java will treat studentMarks and StudentMarks as
two different variables because the case of the characters is not same in both.
Question 16
static — When we declare a method inside a class as static, we can call it without
creating the object of that class. We need to make the main method static because Java
Virtual Machine (JVM) will call it to start the program even before any objects of the
class are created.
void — The void keyword tells the compiler that the main method will not return any
value.
Question 17
Question 18
Question 19
Design a program in Java to display the following information on the output screen:
Name:
Class:
Roll No.:
Subject:
School:
Answer
class StudentInfo {
public static void main(String args[]) {
System.out.println("Name: Akshay Anand");
System.out.println("Class: 10");
System.out.println("Roll No.: 5");
System.out.println("Subject: Computer Applications");
System.out.println("School: KnowledgeBoat");
}
}
Question 20
You want to display your bio-data on the output screen. Write a program in Java to perform
the task in the given format:
Name:
Father's Name:
Date of birth:
Blood Group:
Aadhar Card No.:
State:
Answer
class BioData {
public static void main(String args[]) {
System.out.println("Name: Shweta Nayak");
System.out.println("Father's Name: Arvind Nayak");
System.out.println("Date of birth: 12/12/2005");
System.out.println("Blood Group: O+");
System.out.println("Aadhar Card No.: 4321 8756 9978");
System.out.println("State: Karnataka");
}
}
Chapter 2
Question 1
Question 2
Question 3
Question 4
Question 5
Question 6
Question 7
Question 8
Question 1
Answer
Question 2
Mention five states (characteristics) and two methods for the following Classes:
Answer
Characteristics Methods
Name computeSalary()
Pan Number
Salary
Income Tax
(b) Class Bank
Answer
Characteristics Methods
IFSC Code
MICR Code
Accounts
Answer
Characteristics Methods
Classes
Students
Teachers
Answer
Characteristics Methods
Price
Author
Publisher
Answer
Characteristics Methods
Ticket Price
Opening Time
Closing Time
Answer
Characteristics Methods
Name buyMedicine()
Quantity sellMedicine()
Manufacturing Date
Expiry Date
Characteristics Methods
Price
Answer
Characteristics Methods
Model startComputer()
Processor
RAM
Hard Disk
Answer
Characteristics Methods
Model takePicture()
Colour
Price
Resolution
Question 3
Question 4
Answer
A software object replaces the characteristics and behaviours of a real world object
with data members and member methods, respectively.
Question 5
Answer
A Class is used to create various Objects that have different characteristics and
common behaviours. Each object follows all the features defined within a class. That is
why class is also referred to as a blue print or prototype of an object. This way we can
say that they are inter-related.
Question 6
Answer
A class has the complete description of the data elements the object will contain, the
methods the object can do, the way these data elements and methods can be accessed. A
class can create objects of itself with different characteristics and common behaviour
just like a factory can produce similar items based on a particular design. Hence, class
is also referred to as 'Object Factory'.
Question 7
This statement creates a new object of class Employee. The newly created object is
assigned to a variable named staff which is of Employee type. The object can be
accessed using staff variable.
Question 8
Answer
A class can create objects of itself with different characteristics and common behaviour.
So, we can say that an Object represents a specific state of the class. For these reasons,
an Object is called an Instance of a Class.
Question 9
Answer
A class can contain data members of various primitive and reference data types. Hence,
class is known as composite data type.
Question 10
Answer
Question 11
Consider a real world object as 'Cricket Ball'. Now, mention two behaviours and methods
each by taking the 'Cricket Ball' as a software Object.
Answer
Question 12
With reference to the above class declaration, indicate whether the following statements are
True/False:
3. Acceptdata( ) and PrintData( ) are the common behaviour of the objects of class
'MySchool'.
True
Question 13
You want to create a class 'Football'. Choose the elements to be used as characteristics and
behavior from the list given below:
Ball, Goalkeeper, Making a goal, Defender, Forward player, passing ball, Referee, hitting
corner, making fault
Answer
Characteristics Behaviours
Referee
Question 14
Write a program by using a class 'Picnic' without any data members but having only functions
as per the specifications given below:
class name : Picnic
void display1( ): To print venue, place and reporting time.
void display2( ): To print number of students, name of the teacher accompanying and bus
number.
Write a main class to create an object of the class 'Picnic' and call the functions display1()
and display2( ).
Answer
class Picnic
{
public void display1() {
System.out.println("Venue: Botanical Garden");
System.out.println("Place: MG Road");
System.out.println("Reporting Time: 9:00 AM");
}
Question 1
1. Variable
2. Literal ✓
3. Identifier
4. Character
Question 2
A word used in a high level language which has a special meaning attached to it is called
1. Class
2. Identifier
3. Keyword ✓
4. Literal
Question 3
1. Char variable ✓
2. Char type literal
3. String variable
4. String literal
Question 4
1. ''✓
2. ""
3. ::
4. {}
Question 5
1. String variable ✓
2. Static variable
3. Boolean variable
4. None
Question 6
1. 65 - 90 ✓
2. 60 - 85
3. 65 - 91
4. 97 - 122
Question 7
1. 11.4F/3.2D
2. 13.8F/4.6F;
3. 12/3 ✓
4. none
Question 8
1. char
2. long
3. object ✓
4. short
Question 9
1. char
2. double ✓
3. byte
4. String
Question 10
Boolean Data is used to test a particular condition i.e. true or false. Which of the following is
a correct representation?
1. boolean m=true ✓
2. boolean m='true'
3. boolean m="true"
4. none
Question 1
Question 2
Question 3
Question 4
Question 5
Question 6
The comma, exclamation, question mark etc., are termed as Tokens in Java language.
Question 8
An element of Java program that is used to identify a class, function or value is called
as identifier.
Question 9
Question 10
A Java expression that contains all the elements of same data type is pure expression.
Question 1
Data types are used to identify the type of data a memory location can hold and the
associated operations of handling it.
Question 2
Question 3
The keyword final before a variable declaration makes it a constant. Its value can't be
changed in the program.
Example:
final int DAYS_IN_A_WEEK = 7;
Question 4
1. Primitive Datatypes.
2. Non-Primitive Datatypes.
Question 5
A token is the smallest element of a program that is meaningful to the compiler. The
different types of tokens in Java are:
1. Identifiers
2. Literals
3. Operators
4. Separators
5. Keywords
Question 6
1. Name of the variable should be a sequence of alphabets, digits, underscore and dollar sign
characters only.
2. It should not start with a digit.
3. It should not be a keyword or a boolean or null literal.
Question 7
The process of converting one predefined type into another is called type casting.
Question 8
(a) Assign the value of pie (3.142) to a variable with the requisite data type.
double pi = 3.142;
(b) Assign the value of (1.732) to a variable with the requisite data type.
double x = 1.732;
Question 9
Distinguish between:
Integer Constants represent whole number values Floating Constants represent fractional numbers
like 2, -16, 18246, 24041973, etc. like 3.14159, -14.08, 42.0, 675.238, etc.
Integer Constants are assigned to variables of Floating Constants are assigned to variables of data
data type — byte, short, int, long, char type — float, double
Token Identifier
A token is the smallest element of a program that is Identifiers are used to name things like classes,
meaningful to the compiler. objects, variables, arrays, functions an so on.
Character Constants are written by enclosing a String Constants are written by enclosing a set of
character within a pair of single quotes. characters within a pair of double quotes.
Character Constants are assigned to variables of String Constants are assigned to variables of type
type char. String.
(d) Character and Boolean literal
Escape Sequences can be used to write character Only true and false values are allowed for
literals boolean literals
Question 10
(a) Integer
int
Question 11
A boolean data type is used to store one of the two boolean values — true or false. The
size of boolean data type is 8 bits or 1 byte.
Example:
boolean bTest = false;
Question 12
Primitive data types are the basic or fundamental data types used to declare a variable.
Examples of primitive data types in Java are byte, short, int, long, float, double, char,
boolean.
Question 13
Data types tells Java how much memory it should reserve for storing the value. Data
types also help in preventing errors as the compiler can check and flag illegal operations
at compile time itself.
Question 14
In implicit type conversion, the result of a mixed mode expression is obtained in the
higher most data type of the variables without any intervention by the user. Example:
int a = 10;
float b = 25.5f, c;
c = a + b;
(b) Explicit type conversion
In explicit type conversion, the data gets converted to a type as specified by the
programmer. For example:
int a = 10;
double b = 25.5;
float c = (float)(a + b);
Question 15
In a mixed-mode expression, the process of promoting a data type into its higher most
data type available in the expression without any intervention by the user is known as
Coercion.
Example:
byte b = 42;
int i = 50000;
double result = b + i;
Question 16
What do you mean by type conversion? How is implicit conversion different from explicit
conversion?
The process of converting one predefined type into another is called type conversion. In
an implicit conversion, the result of a mixed mode expression is obtained in the higher
most data type of the variables without any intervention by the user. For example:
int a = 10;
float b = 25.5f, c;
c = a + b;
In case of explicit type conversion, the data gets converted to a type as specified by the
programmer. For example:
int a = 10;
double b = 25.5;
float c = (float)(a + b);
Question 17
In static declaration, the initial value of the variable is provided as a literal at the time
of declaration. For example:
int a = 4;
int b = Math.sqrt(a);
Question 18
A non-primitive data type is one that is derived from Primitive data types. A number of
primitive data types are used together to represent a non-primitive data type. Examples
of non-primitive data types in Java are Class and Array.
Question 19
(i)
int p; double q;
r = p+q;
System.out.println(r);
Answer
(ii)
float m;
p = m/3*(Math.pow(4,3));
System.out.println(p);
Answer
Question 20
What are the resultant data types if the following implicit conversions are performed? Show
the result with flow lines.
int i; float f; double d; char c; byte b;
(a) i + c/b;
Answer
i + c/b;
⇒ int + char / byte
⇒ int + char
⇒ int
Answer
f/d + c*f;
⇒ float / double + char * float
⇒ double + float
⇒ double
(c) i + f - b*c;
Answer
i + f - b*c;
⇒ int + float - byte * char
⇒ int + float - char
⇒ float - char
⇒ float
(d) (f/i)*c + b;
Answer
(f/i)*c + b;
⇒ (float / int) * char + byte
⇒ float * char + byte
⇒ float + byte
⇒ float
(e) i + f- c + b/d;
Answer
i + f- c + b/d;
⇒ int + float - char + byte / double
⇒ int + float - char + double
⇒ float - char + double
⇒ float + double
⇒ double
Answer
i/c + f/b
⇒ int / char + float / byte
⇒ int + float
⇒ float
Chapter 4
Operators in Java
Class 9 - APC Understanding Computer
Applications with BlueJ
Question 1
1. ++n
2. n=n+4 ✓
3. n+1
4. none
Question 2
What will be the output of a & b in the following, if int a, b; a=10; b=a++;
1. 10,10
2. 10,11
3. 11,10 ✓
4. 11,11
Question 3
1. 1
2. -1
3. 0 ✓
4. none
Question 4
1. 5.0
2. 5
3. 0 ✓
4. none
Question 5
int m=8;
m*=8;
System.out.println("The output =" + m);
1. 8
2. 64 ✓
3. 16
4. 88
Question 6
double c;
int x, y, z;
x = 5; y = 10; z = 11;
c = x*y+z/2;
The value stored in c is:
1. 55.0 ✓
2. 55.5
3. 55
4. none
Explanation
c=x*y+z/2
⇒ c = 5 * 10 + 11 / 2
⇒ c = 5 * 10 + 5
⇒ c = 50 + 5
⇒ c = 55.0
Question 7
int m, p;
m = 5;
p = 0;
p = m-- + --m;
The output will be:
1. 11
2. 10
3. 8 ✓
4. 12
Explanation
p = m-- + --m;
⇒p=5+3
⇒p=8
Question 8
1. 13
2. 14
3. 15
4. -15 ✓
Explanation
p = ++a + --a
⇒p=8+7
⇒ p = 15
q -= p
⇒q=q-p
⇒ q = 0 - 15
⇒ q = -15
Write the Java expressions for the following:
Question 1
p = a2 + bc
Answer
p=a*a+b*c
Question 2
m = a2 - b2 / (ab)
Answer
m = (a * a - b * b) / (a * b)
Question 3
s = ut + (1/2)at2
Answer
s = u * t + (1.0 / 2) * a * t * t
Question 4
f = uv / (u + v)
Answer
f = u * v / (u + v)
Question 5
(a + b)2 + b
Answer
(a + b) * (a + b) + b
Question 6
y = 2(lb + bh + lh)
Answer
y = 2 * (l * b + b * h + l * h)
Question 7
a2 + b2
Answer
a*a+b*b
Question 8
z = x3 + y3 - xy / 3
Answer
z=x*x*x+y*y*y-x*y/3
Question 1
What is an operator?
Question 2
Question 5
Binary operators work on two operands. Ternary operator work on three operands.
It evaluates to true only if both of its It evaluates to true if one or both of its
operands are true. operands are true.
Example: Example:
int a = 8, b = 13, c = 0; int a = 8, b = 13, c = 0;
if (a > 10 && b > 10) if (a > 10 || b > 10)
c = 10; c = 10;
else else
c = 5; c = 5;
Here, value of c will be 5 as one of the Here, value of c will be 10 as at least one of the
operands is false. operands is true.
Example: Example:
int a = 99; int a = 99;
int b = ++a; int b = a++;
After the execution of these two After the execution of these two statements, a will
statements, both a and b will have the have the value of 100 and b will have the value of
value of 100. 99.
(e) System.out.print( ) and System.out.println( )
System.out.print( ) System.out.println( )
It prints data to the console but the cursor It prints data to the console and places
remains at the end of the data in the same line. the cursor in the next line.
Next printing takes place from the same line. Next printing takes place from next line.
Question 6
Question 7
If m=5 and n=2 then what will be the output of m and n after execution that will store in (a)
& (b)?
(a) m -= n;
Answer
m -= n
⇒m=m-n
⇒m=5-2
⇒m=3
(b) n = m + m/n;
Answer
n = m + m/n
⇒n=5+5/2
⇒n=5+2
⇒n=7
Question 8
= ==
It is the assignment operator used for It is the equality operator used to check if a variable
assigning a value to a variable. is equal to another variable or literal.
Question 9
int a=0,b=10,c=40;
a = --b + c++ +b;
System.out.println(" a = " + a);
Output
a = 58
Explanation
a = --b + c++ + b
⇒ a = 9 + 40 + 9
⇒ a = 58
Question 10
(a) 5* ++x;
Answer
5 * ++x
⇒5*6
⇒ 30
(b) 5* x++;
Answer
5 * x++
⇒5*5
⇒ 25
Question 11
Answer
a - (b++) * (--c)
⇒2-3*8
⇒2-3*8
⇒ 2 - 24
⇒ -22
(b) a * (++b) % c;
Answer
a * (++b) % c
⇒ a * (++b) % c
⇒ 2 * (4) % 9
⇒8%9
⇒8
Question 12
Answer
a += a++ - ++b + a
⇒ a = a + (a++ - ++b + a)
⇒ a = 5 + (5 - 10 + 6)
⇒a=5+1
⇒a=6
Question 13
Output
a = 11 and b = 12
Explanation
The condition if(a>=10) is true so a++ increments a to 11. b remains the same.
Question 14
if(income<=100000)
tax = 0;
else
tax = (0.1*income);
Answer
Question 15
if(p>5000)
d = p*5/100;
else
d = 2*p/100;
Answer
Question 1
Write a program to find and display the value of the given expressions:
Output
Output
Question 2
A person is paid ₹350 for each day he works and fined ₹30 for each day he remains absent.
Write a program to calculate and display his monthly income, if he is present for 25 days and
remains absent for 5 days.
Output
Question 3
In a competitive examination, there were 150 questions. One candidate got 80% correct and
the other candidate 72% correct. Write a program to calculate and display the correct answers
each candidate got.
Output
Question 4
Output
Output
Question 5
The normal temperature of human body is 98.6°F. Write a program to convert the
temperature into degree Celsius and display the output.
Hint: c / 5 = f - 32 / 9
Output
Question 6
The angles of a quadrilateral are in the ratio 3:4:5:6. Write a program to find and display all
of its angles. [Hint: The sum of angles of a quadrilateral = 360°]
Output
Chapter 5
Input In Java
Class 9 - APC Understanding Computer
Applications with BlueJ
Question 1
Question 2
Question 3
Question 4
Question 5
Question 1
Question 2
Question 3
Question 4
to accept a fraction value 'n' in double data type through Stream Class
Question 5
Question 6
Question 1
nextInt( ) nextFloat( )
Scans the next token of input as an int Scans the next token of input as a float
Question 2
Syntax Errors occur when we violate the rules of Logical Errors occur due to our mistakes in
writing the statements of the programming language. programming logic.
Question 1
Question 2
Question 4
Question 5
Question 6
if (a < b) {
/*
* All statements within this set of braces
* form the compound statement
*/
}
Question 7
Write down the syntax to input a character through scanner class with an example.
Syntax:
Question 8
import java.util.Scanner;
class RunTimeError
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = in.nextInt();
int result = 100 / n;
System.out.println("Result = " + result);
}
}
This program will work fine for all non-zero values of n entered by the user. When the
user enters zero, a run-time error will occur as the program is trying to perform an
illegal mathematical operation of division by 0. When we are compiling the program, we
cannot say if division by 0 error will occur or not. It entirely depends on the state of the
program at run-time.
Question 9
What are the different types of errors that take place during the execution of a program?
Logical errors and Run-Time errors occur during the execution of the program.
Question 10
Distinguish between:
(a) Testing and Debugging
Testing Debugging
In the process of Testing, we check if the program is In the process of Debugging, we correct
working as expected and find out the errors if it is not the errors that were found during
giving the expected output. testing.
Syntax Errors occur when we violate the rules of Logical Errors occur due to our mistakes in
writing the statements of the programming language. programming logic.
Question 1
T = 2π√(l/g)
Write a program to calculate the time period of a Simple Pendulum by taking length and
acceleration due to gravity (g) as inputs.
import java.util.Scanner;
Output
Question 2
Write a program by using class 'Employee' to accept Basic Pay of an employee. Calculate the
allowances/deductions as given below.
import java.util.Scanner;
Output
Question 3
A shopkeeper offers 10% discount on the printed price of a Digital Camera. However, a
customer has to pay 6% GST on the remaining amount. Write a program in Java to calculate
the amount to be paid by the customer taking printed price as an input.
import java.util.Scanner;
Output
Question 4
A shopkeeper offers 30% discount on purchasing articles whereas the other shopkeeper offers
two successive discounts 20% and 10% for purchasing the same articles. Write a program in
Java to compute and display the discounts.
Take the price of an article as the input.
import java.util.Scanner;
Output
Question 5
Mr. Agarwal invests certain sum at 5% per annum compound interest for three years. Write a
program in Java to calculate:
import java.util.Scanner;
Question 6
Output
Question 7
Write a program to input the time in seconds. Display the time after converting them into
hours, minutes and seconds.
Sample Input: Time in seconds 5420
Sample Output: 1 Hour 30 Minutes 20 Seconds
import java.util.Scanner;
Output
Question 8
Write a program to input two unequal numbers. Display the numbers after swapping their
values in the variables without using a third variable.
Sample Input: a = 23, b = 56
Sample Output: a = 56, b = 23
import java.util.Scanner;
Output
Question 9
A certain amount is invested at the rate 10% per annum for 3 years. Find the difference
between Compound Interest (CI) and Simple Interest (SI). Write a program to take amount as
an input.
Hint: SI = (P * R * T) / 100
A = P * (1 + (R/100))T
CI = A - P
import java.util.Scanner;
public class KboatInterestDifference
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Amount: ");
double p = in.nextDouble();
double si = p * 10 * 3 / 100;
double ciAmt = p * Math.pow(1 + (10/100.0), 3);
double ci = ciAmt - p;
System.out.print("Difference between CI & SI: " + (ci -
si));
}
}
Output
Question 10
A shopkeeper sells two calculators for the same price. He earns 20% profit on one and suffers
a loss of 20% on the other. Write a program to find his total cost price of the calculators by
taking selling price as input.
Hint: CP = (SP / (1 + (profit / 100))) (when profit)
CP = (SP / (1 - (loss / 100))) (when loss)
import java.util.Scanner;
Output
Chapter 6
Question 1
1. Math.pow(a,2)
2. a*a
3. Math.sqrt(a,2) ✓
4. All of the above
Question 2
1. int
2. float
3. double ✓
4. All
Question 3
Which of the following syntax is true to find the square root of a number?
1. sqrt(a)
2. Math.sqrt(a) ✓
3. Squareroot(a)
4. None
Question 4
1. Java.Math ✓
2. Java.Power
3. Java.Sqrt
4. None
Question 5
1. -9.99
2. 9.99 ✓
3. 0.99
4. None
Question 6
1. 3
2. 3.0 ✓
3. 3.00
4. all
Question 1
System.out.println(Math.sqrt(10.24));
Output
3.2
Explanation
Math.sqrt method gives the square root of a positive number. Square root of 10.24 is 3.2 so it
is the output.
Question 2
System.out.println(Math.rint(-99.4));
Output
-99.0
Explanation
Math.rint method rounds off its argument to the nearest mathematical integer and returns its
value as a double type. The nearest integer to -99.4 is -99.0 so that is the output. Math.rint
method behaves in a particular way at the mid-point i.e. when the decimal part of the
argument is 0.5. In such cases, the result is the integer value that is even. Let's understand this
with an example. Math.rint(1.5) and Math.rint(2.5) will both return 2.0. In the case of 1.5,
both 1.0 and 2.0 are equally close to 1.5. Math.rint choses the integer that is even so 2.0 is
returned. In the case of 2.5, both 2.0 and 3.0 are equally close to 2.5. Math.rint again choses
the integer that is even so 2.0 is returned.
Question 3
System.out.println(Math.cbrt(42.875));
Output
3.5
Explanation
Math.cbrt method returns the cube root of its argument as a double value. Cube root of
42.875 is 3.5 so it is the output.
Question 4
System.out.println(Math.min(-25.5, -12.5));
Output
-25.5
Explanation
Math.min method returns the smaller of its 2 arguments. As -25.5 is smaller than -12.5 so it is
the output.
Question 5
System.out.println(Math.ceil(-0.95));
Output
-0.0
Explanation
Math.ceil method returns the smallest double value that is greater than or equal to the
argument and is equal to a mathematical integer. If the argument value is less than zero but
greater than -1.0, then the result is negative zero which is the case in this question.
Question 6
System.out.println(Math.round(-18.51));
Output
-19
Explanation
Math.round method rounds off its argument to the nearest mathematical integer and returns
its value as an int or long type. At the mid-point i.e. when the decimal part of the argument is
0.5, Math.round method rounds up to the higher integer. In this case, the nearest integer to -
18.51 is -19 so it is the output.
Question 7
System.out.println(Math.max(-77.66, -87.45));
Output
-77.66
Explanation
Math.max method returns the greater of its 2 arguments. As -77.66 is greater than -87.45 so it
is the output.
Question 8
System.out.println(Math.floor(-0.88));
Output
-1.0
Explanation
Math.floor method returns the largest double value that is less than or equal to the argument
and is equal to a mathematical integer. As -1.0 is the largest mathematical integer less than -
0.88 so it is the output.
Question 9
System.out.println(Math.rint(98.5));
Output
98.0
Explanation
Math.rint method rounds off its argument to the nearest mathematical integer and returns its
value as a double type. This method behaves in a particular way at the mid-point i.e. when the
decimal part of the argument is 0.5. In such cases, the result is the integer value that is even.
Let's understand this with an example. Math.rint(97.5) and Math.rint(98.5) will both return
98.0. In the case of 97.5, both 97.0 and 98.0 are equally close to 97.5. Math.rint choses the
integer that is even so 98.0 is returned. In the case of 98.5, both 98.0 and 99.0 are equally
close to 98.5. Math.rint again choses the integer that is even so 98.0 is returned.
Question 10
System.out.println(Math.ceil(65.5));
Output
66.0
Explanation
Math.ceil method returns the smallest double value that is greater than or equal to the
argument and is equal to a mathematical integer. Here 66.0 is the smallest mathematical
integer greater than 65.5 so it is the output.
Write down the syntax for the following functions
Question 1
Answer
Math.min(p, q)
Question 2
Answer
Math.abs(m)
Question 3
Answer
Math.exp(k)
Question 4
Answer
Math.sqrt(d)
Question 5
Answer
Math.round(b)
Predict the return data type of the following functions
Question 1
Math.sqrt( );
Answer
double
Question 2
Math.rint( );
Answer
double
Question 3
Math.ceil( );
Answer
double
Question 4
Math.round( );
Answer
int or long
Question 5
Math.floor( );
Answer
double
Question 6
Math.log( )
Answer
double
Explain the following functions
Question 1
Math.random( )
Answer
Returns a positive double value, greater than or equal to 0.0 and less than 1.0.
Question 2
Math.max( )
Answer
Returns the greater of its 2 arguments. Its return type is same as the type of its
arguments.
Question 3
Math.cbrt( )
Answer
Question 4
Math.abs( )
Answer
Returns the absolute value of its argument. Its return type is same as the type of its
arguments.
Question 5
Math.log( )
Answer
Returns the natural logarithm of its argument. Both return type and argument is of
double data type.
Distinguish between them with suitable examples
Question 1
Answer
Math.ceil( ) Math.floor( )
Returns the smallest double value that is greater Returns the largest double value that is less than or
than or equal to the argument and is equal to a equal to the argument and is equal to a
mathematical integer mathematical integer.
Question 2
Answer
Math.rint( ) Math.round( )
Rounds off its argument to the nearest Rounds off its argument to the nearest mathematical integer and
mathematical integer and returns its returns its value as an int or long type. If argument is float, return
value as a double type. type is int, if argument is double, return type is long.
Question 1
Write a program in Java to input three numbers and display the greatest and the smallest of
the two numbers.
Hint: Use Math.min( ) and Math.max( )
Sample Input: 87, 65, 34
Sample Output: Greatest Number 87
Smallest number 34
import java.util.Scanner;
Output
Question 2
Write a program in Java to calculate and display the hypotenuse of a Right-Angled Triangle
by taking perpendicular and base as inputs.
Hint: h = √p2 + b2
import java.util.Scanner;
public class KboatHypotenuse
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Perpendicular: ");
double p = in.nextDouble();
System.out.print("Enter Base: ");
double b = in.nextDouble();
Output
Question 3
Write a program to input a number and evaluate the results based on the number entered by
the user:
(a) Natural logarithm of the number
(b) Absolute value of the number
(c) Square root of the number
(d) Cube of the number
(e) Random numbers between 0 (zero) and 1 (one).
import java.util.Scanner;
Output
Question 4
In an examination, you have appeared for three subjects i.e. Physics, Chemistry and Biology.
Write a program in Java to calculate the average mark obtained and finally display the marks
in rounded-off form.
Take Physics, Chemistry. and Biology marks as inputs.
import java.util.Scanner;
Output
Question 5
import java.util.Scanner;
Output
Chapter 7
Question 1
In a switch case, when the switch value does not respond to any case then the execution
transfers to:
1. a break statement
2. a default case ✓
3. a loop
4. none
Question 2
1. p=Integer.parseInt(in.readLine());
2. c=++a;
3. if(a>b) a++; b- - ; ✓
4. a=4;
Question 3
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. All ✓
Question 4
Question 5
if(a>b)
c=a;
else
c=b;
It can be written as:
1. c= (b>a)?a:b;
2. c= (a!=b)?a:b;
3. c= (a>b)?b:a;
4. None ✓
Question 6
If a, b and c are the sides of a triangle then which of the following statement is true for:
if(a!=b && a!=c && b!=c)?
1. Equilateral triangle
2. Scalene triangle ✓
3. Isosceles triangle
4. All of the above
Question 7
1. Arithmetic operator
2. Relational operator ✓
3. Ternary operator
4. None
Question 8
1. if ✓
2. goto
3. for
4. none
Question 9
1. for statement
2. switch statement ✓
3. if-else
4. none
Question 10
A Java program executes but doesn't give the desired output. It is due to:
Question 1
Answer
Question 2
Answer
if-else statement
(b) Multiple branching of control
Answer
switch statement
Question 3
(a) nested if
Answer
We can write an if-else statement within another if-else statement. We call this nested if.
It has the following syntax:
if (condition 1) {
if (condition 2) {
Statement a;
Statement b;
..
}
else {
Statement c;
Statement d;
..
}
}
else {
if (condition 3) {
Statement e;
Statement f;
..
}
else {
Statement g;
Statement h;
..
}
}
(b) if - else
Answer
if - else statement is used to execute one set of statements when the condition is true and
another set of statements when the condition is false. It has the following syntax:
if (condition 1) {
Statement a;
Statement b;
..
}
else {
Statement c;
Statement d;
..
}
(c) if - else - if
Answer
if - else - if ladder construct is used to test multiple conditions and then take a decision.
It provides multiple branching of control. It has the following syntax:
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
..
..
else
statement;
Question 4
Answer
1. switch can only test for equality whereas if can test for any Boolean expression.
2. switch tests the same expression against constant values while if-else-if ladder can use
different expression involving unrelated variables.
3. switch expression must only evaluate to byte, short, int, char, String or an enum. if doesn’t
have such limitations.
4. A switch statement will run much faster than the equivalent program written using the if-
else-if ladder
Question 5
Answer
switch statement in a program, is used for multi-way branch. It compares its expression
to multiple case values for equality and executes the case whose value is equal to the
expression of switch. If none of the cases match, default case is executed. If default case
is absent then none of the statements from switch are executed.
Question 6
Explain with the help of an example, the purpose of default in a switch statement.
Answer
When none of the case values are equal to the expression of switch statement then
default case is executed. In the example below, value of number is 4 so case 0, case 1 and
case 2 are not equal to number. Hence sopln of default case will get executed printing
"Value of number is greater than two" to the console.
int number = 4;
switch(number) {
case 0:
System.out.println("Value of number is zero");
break;
case 1:
System.out.println("Value of number is one");
break;
case 2:
System.out.println("Value of number is two");
break;
default:
System.out.println("Value of number is greater than two");
break;
}
Question 7
Answer
Use of break statement in a switch case statement is optional. Omitting break statement
will lead to fall through where program execution continues into the next case and
onwards till end of switch statement is reached.
Question 8
Answer
break statement at the end of case is optional. Omitting break leads to program
execution continuing into the next case and onwards till a break statement is
encountered or end of switch is reached. This is termed as Fall Through in switch case
statement.
Question 9
Answer
Two or more statements can be grouped together by enclosing them between opening
and closing curly braces. Such a group of statements is called a compound statement.
if (a < b) {
/*
* All statements within this set of braces
* form the compound statement
*/
}
Question 10
Answer
if - else - if ladder construct is used to test multiple conditions and then take a decision.
It provides multiple branching of control. Below is an example of if - else - if:
Question 11
Answer
Question 12
Give two differences between the switch statement and the if-else statement.
Answer
switch if-else
switch can only test if the expression is equal if-else can test for any boolean expression like less than,
to any of its case constants greater than, equal to, not equal to, etc.
Question 1
int a=1,b=1,m=10,n=5;
if((a==1)&&(b==0))
{
System.out.println((m+n));
System.out.println((m—n));
}
if((a==1)&&(b==1))
{
System.out.println((m*n));
System. out.println((m%n));
}
Output
50
Explanation
First if condition is false, second if condition is true. Statements inside the code block of
second if condition are executed.
m*n => 10 * 5 => 50
m%n => 10 % 5 => 0
Question 2
int x=1,y=1;
if(n>0)
{
x=x+1;
y=y+1;
}
What will be the value of x and y, if n assumes a value (i) 1 (ii) 0?
Output
(i) n = 1
x = 2
y = 2
(ii) n = 0
x = 1
y = 1
Explanation
When n = 1, if condition is true, its code block is executed adding 1 to both x and y. When n
= 0, if condition is false so x and y retain their original values.
Question 3
int b=3,k,r;
float a=15.15,c=0;
if(k==1)
{
r=(int)a/b;
System.out.println(r);
}
else
{
c=a/b;
System.out.println(c);
}
Output
Explanation
Assuming k to be a local variable declared inside a method, we are using k in the if condition
before initializing it i.e. before assigning any value to k. Due to this, the above code will
generate a compile time error.
Question 4
switch (opn)
{
case 'a':
System.out.println("Platform Independent");
break;
case 'b':
System.out.println("Object Oriented");
case 'c':
System.out.println("Robust and Secure");
break;
default:
System.out.println("Wrong Input");
}
When (i) opn = 'b' (ii) opn = 'x' (iii) opn = 'a'
Output
Object Oriented
Explanation
case 'b' is matched, "Object Oriented" gets printed to the console. As there is no case
statement in case 'b', program control falls through to case 'c' printing "Robust and Secure" to
the console. case 'c' has a break statement which transfers the program control outside switch
statement.
Wrong Input
Explanation
Platform Independent
Explanation
case 'a' is matched, "Platform Independent" gets printed to the console. break statement in
case 'a' transfers the program control outside switch statement.
Correct the errors in the given programs
Question 1
class public
{
public static void main(String args{})
{
int a=45,b=70,c=65.45;
sum=a+b;
diff=c-b;
System.out.println(sum,diff);
}
}
Explanation
1. public is a keyword so it can't be used as an identifier for naming the class. Change the class
name from public to any valid identifier, for example class Sample
2. Argument of main method is an array of Strings. Use square brackets instead of curly
brackets — String args[]
3. c is an int variable. We cannot assign a double literal 65.45 to it.
4. Variables sum & diff are not defined
5. The line System.out.println(sum,diff); should be written like
this System.out.println(sum + " " + diff);
Corrected Program
Question 2
class Square
{
public static void main(String args[])
{
int n=289,r;
r=sqrt(n);
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}
Explanation
Corrected Program
class Square
{
public static void main(String args[])
{
int n=289;
double r=Math.sqrt(n); //1st & 2nd correction
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}
Question 3
class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10,b=5,c=1,d=2;
c=a2+b2;
d=(a+b)2;
p=c/d;
System.out.println(c + " "+ " "+d+ " "+p);
}
}
Explanation
1. The line a=10,b=5,c=1,d=2; generates a compile time error. We will combine the
declaration and initialization of these variables.
2. The line c=a2+b2; is written in Java like this c = (int)(Math.pow(a, 2) + Math.pow(b, 2));
3. The line d=(a+b)2; is written in Java like this d=(int)Math.pow((a+b), 2);
4. Variable p is not defined
Corrected Program
class Simplify
{
public static void main(String args[])
{
int a=10,b=5,c=1,d=2; //1st correction
c = (int)(Math.pow(a, 2) + Math.pow(b, 2)); //2nd correction
d = (int)Math.pow((a+b), 2); //3rd correction
int p=c/d; //4th correction
System.out.println(c + " "+ " "+d+ " "+p);
}
}
Question 4
class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12;
if(n=25)
{
k=pow(p,2)
System.out.println("The value of"+p+ " = "+k);
}
else
{
r=Math.square root(n);
System.out.println("The value of"+n+ " = "+r);
}
}
}
Explanation
class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12;
if(n==25) //1st correction
{
k=(float)Math.pow(p,2); //2nd correction
System.out.println("The value of"+p+ " = "+k);
}
else
{
r=(float)Math.sqrt(n); //3rd correction
System.out.println("The value of"+n+ " = "+r);
}
}
}
Solutions to Unsolved Java Programs
Question 1
Write a program to input three angles of a triangle and check whether a triangle is possible or
not. If possible then check whether it is an acute-angled triangle, right-angled or an obtuse-
angled triangle otherwise, display 'Triangle not possible'.
Sample Input: Enter three angles: 40, 50, 90
Sample Output: Right=angled Triangle
import java.util.Scanner;
Output
Question 2
Write a program to input the cost price and the selling price of an article. If the selling price is
more than the cost price then calculate and display actual profit and profit per cent otherwise,
calculate and display actual loss and loss per cent. If the cost price and the selling price are
equal, the program displays the message 'Neither profit nor loss'.
import java.util.Scanner;
Write a program to input three numbers and check whether they are equal or not. If they are
unequal numbers then display the greatest among them otherwise, display the message 'All
the numbers are equal'.
Sample Input: 34, 87, 61
Sample Output: Greatest number: 87
Sample Input: 81, 81, 81
Sample Output: All the numbers are equal.
import java.util.Scanner;
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;
Output
Question 4
Write a program to accept a number and check whether the number is divisible by 3 as well
as 5. Otherwise, decide:
(a) Is the number divisible by 3 and not by 5?
(b) Is the number divisible by 5 and not by 3?
(c) Is the number neither divisible by 3 nor by 5?
The program displays the message accordingly.
import java.util.Scanner;
Output
Question 5
import java.util.Scanner;
Output
Question 6
Write a program to input two unequal positive numbers and check whether they are perfect
square numbers or not. If the user enters a negative number then the program displays the
message 'Square root of a negative number can't be determined'.
Sample Input: 81, 100
Sample Output: They are perfect square numbers.
Sample Input: 225, 99
Sample Output: 225 is a perfect square number.
99 is not a perfect square number.
import java.util.Scanner;
if (a < 0 || b < 0) {
System.out.println("Square root of a negative number
can't be determined");
}
else {
double sqrtA = Math.sqrt(a);
double sqrtB = Math.sqrt(b);
double isAPerfectSq = sqrtA - Math.floor(sqrtA);
double isBPerfectSq = sqrtB - Math.floor(sqrtB);
if (isAPerfectSq == 0 && isBPerfectSq == 0) {
System.out.println("They are perfect square
numbers.");
}
else if (isAPerfectSq == 0) {
System.out.println(a + " is a perfect square
number.");
System.out.println(b + " is not a perfect square
number.");
}
else if (isBPerfectSq == 0) {
System.out.println(a + " is not a perfect square
number.");
System.out.println(b + " is a perfect square
number.");
}
else {
System.out.println("Both are not perfect square
numbers.");
}
}
}
}
Output
Question 7
Without using if-else statement and ternary operators, accept three unequal numbers and
display the second smallest number.
[Hint: Use Math.max( ) and Math.min( )]
Sample Input: 34, 82, 61
Sample Output: 61
import java.util.Scanner;
int sum = a + b + c;
int big = Math.max(a, b);
big = Math.max(big, c);
int small = Math.min(a, b);
small = Math.min(small, c);
int result = sum - big - small;
System.out.println("Second Smallest Number = " + result);
}
}
Output
Question 8
Write a program to input three unequal numbers. Display the greatest and the smallest
number.
Sample Input: 28, 98, 56
Sample Output: Greatest Number: 98
Smallest Number: 28
import java.util.Scanner;
}
}
Output
Question 9
A Pre-Paid taxi charges from the passenger as per the tariff given below:
Distance Rate
Up to 5 km ₹ 100
Write a program to input the distance covered and calculate the amount paid by the
passenger. The program displays the printed bill with the details given below:
Taxi No. :
Distance covered :
Amount :
import java.util.Scanner;
int fare = 0;
if (dist <= 5)
fare = 100;
else if (dist <= 15)
fare = 100 + (dist - 5) * 10;
else if (dist <= 25)
fare = 100 + 100 + (dist - 15) * 8;
else
fare = 100 + 100 + 80 + (dist - 25) * 5;
}
}
Output
Question 10
A cloth showroom has announced festival discounts and the gifts on the purchase of items,
based on the total cost as given below:
Up to ₹ 2,000 5% Calculator
Write a program to input the total cost. Compute and display the amount to be paid by the
customer along with the gift.
import java.util.Scanner;
}
}
Output
Question 11
Given below is a hypothetical table showing rate of income tax for an India citizen, who is
below or up to 60 years.
Up to ₹ 2,50,000 Nil
More than ₹ 2,50,000 and less than or equal to ₹ 5,00,000 (TI - 1,60,000) * 10%
More than ₹ 5,00,000 and less than or equal to ₹ 10,00,000 (TI - 5,00,000) * 20% + 34,000
Write a program to input the name, age and taxable income of a person. If the age is more
than 60 years then display the message "Wrong Category". If the age is less than or equal to
60 years then compute and display the income tax payable along with the name of tax payer,
as per the table given above.
import java.util.Scanner;
Output
Question 12
An employee wants to deposit certain sum of money under 'Term Deposit' scheme in
Syndicate Bank. The bank has provided the tariff of the scheme, which is given below:
Write a program to calculate the maturity amount taking the sum and number of days as
inputs.
import java.util.Scanner;
Mr. Kumar is an LIC agent. He offers discount to his policy holders on the annual premium.
However, he also gets commission on the sum assured as per the given tariff.
Up to ₹ 1,00,000 5% 2%
Write a program to input name of the policy holder, the sum assured and first annual
premium. Calculate the discount of the policy holder and the commission of the agent. The
program displays all the details as:
Name of the policy holder :
Sum assured :
Premium :
Discount on the first premium :
Commission of the agent :
import java.util.Scanner;
}
}
Output
Question 14
A company announces revised Dearness Allowance (DA) and Special Allowances (SA) for
their employees as per the tariff given below:
Up to ₹ 10,000 10% 5%
Write a program to accept name and Basic Salary (BS) of an employee. Calculate and display
gross salary.
Gross Salary = Basic + Dearness Allowance + Special Allowance
Print the information in the given format:
Name Basic DA Spl. Allowance Gross Salary
xxx xxx xxx xxx xxx
import java.util.Scanner;
public class KboatSalary
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
String name = in.nextLine();
System.out.print("Enter basic salary: ");
double bs = in.nextDouble();
double da = 0.0, sa = 0.0;
double gs = bs + da + sa;
System.out.println("Name\tBasic\tDA\tSpl. Allowance\tGross
Salary");
System.out.println(name + "\t" + bs + "\t" + da + "\t" + sa
+ "\t" + gs);
}
}
Output
Question 15
Using a switch case statement, write a menu driven program to convert a given temperature
from Fahrenheit to Celsius and vice-versa. For an incorrect choice, an appropriate message
should be displayed.
Hint: c = 5/9*(f-32) and f=1.8*c+32
import java.util.Scanner;
switch (choice) {
case 1:
System.out.print("Enter temperature in Fahrenheit:
");
ft = in.nextDouble();
ct = 5 / 9.0 * (ft - 32);
System.out.println("Temperature in Celsius: " + ct);
break;
case 2:
System.out.print("Enter temperature in Celsius: ");
ct = in.nextDouble();
ft = 1.8 * ct + 32;
System.out.println("Temperature in Fahrenheit: " +
ft);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 16
The volume of solids, viz. cuboid, cylinder and cone can be calculated by the formula:
Using a switch case statement, write a program to find the volume of different solids by
taking suitable variables and data types.
import java.util.Scanner;
switch(choice) {
case 1:
System.out.print("Enter length of cuboid: ");
double l = in.nextDouble();
System.out.print("Enter breadth of cuboid: ");
double b = in.nextDouble();
System.out.print("Enter height of cuboid: ");
double h = in.nextDouble();
double vol = l * b * h;
System.out.println("Volume of cuboid = " + vol);
break;
case 2:
System.out.print("Enter radius of cylinder: ");
double rCylinder = in.nextDouble();
System.out.print("Enter height of cylinder: ");
double hCylinder = in.nextDouble();
double vCylinder = (22 / 7.0) * Math.pow(rCylinder,
2) * hCylinder;
System.out.println("Volume of cylinder = " +
vCylinder);
break;
case 3:
System.out.print("Enter radius of cone: ");
double rCone = in.nextDouble();
System.out.print("Enter height of cone: ");
double hCone = in.nextDouble();
double vCone = (1 / 3.0) * (22 / 7.0) *
Math.pow(rCone, 2) * hCone;
System.out.println("Volume of cone = " + vCone);
break;
default:
System.out.println("Wrong choice! Please select from
1 or 2 or 3.");
}
}
}
Output
Question 17
A Mega Shop has different floors which display varieties of dresses as mentioned
below:
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:
Write a program to perform the above task as per the user's choice.
import java.util.Scanner;
switch (floor) {
case 1:
System.out.println("Kids Wear");
break;
case 2:
System.out.println("Ladies Wear");
break;
case 3:
System.out.println("Designer Sarees");
break;
case 4:
System.out.println("Men's Wear");
break;
default:
isFloorValid = false;
System.out.println("Incorrect Floor");
break;
}
if (isFloorValid) {
System.out.print("Enter bill amount: ");
double amt = in.nextDouble();
Output
Question 18
The equivalent resistance of series and parallel connections of two resistances are given by
the formula:
(a) R1 = r1 + r2 (Series)
(b) R2 = (r1 * r2) / (r1 + r2) (Parallel)
Using a switch case statement, write a program to enter the value of r1 and r2. Calculate and
display the equivalent resistances accordingly.
import java.util.Scanner;
switch (choice) {
case 1:
eqr = r1 + r2;
break;
case 2:
eqr = (r1 * r2) / (r1 + r2);
break;
default:
isChoiceValid = false;
System.out.println("Incorrect choice");
break;
}
if (isChoiceValid)
System.out.println("Equivalent resistance = " + eqr);
}
}
Output
Question 19
The Simple Interest (SI) and Compound Interest (CI) of a sum (P) for a given time (T) and
rate (R) can be calculated as:
Write a program to input sum, rate, time and type of Interest ('S' for Simple Interest and 'C'
for Compound Interest). Calculate and display the sum and the interest earned.
import java.util.Scanner;
switch (type) {
case 'S':
interest = p * r * t / 100;
break;
case 'C':
interest = p * (Math.pow((1 + (r / 100)), t) - 1);
break;
default:
isTypeValid = false;
System.out.println("Incorrect Interest type");
break;
}
if (isTypeValid) {
double amt = p + interest;
System.out.println("Sum = " + p);
System.out.println("Interest = " + interest);
System.out.println("Sum + Interest = " + amt);
}
}
}
Output
Question 20
'Kumar Electronics' has announced the following seasonal discounts on purchase of certain
items.
Write a program to input name, amount of purchase and the type of purchase (`L' for Laptop
and 'D' for Desktop) by a customer. Compute and print the net amount to be paid by a
customer along with his name.
(Net amount = Amount of purchase - discount)
import java.util.Scanner;
Output
Chapter 8
Question 1
When the statements are repeated sequentially a number of times in a program, the construct
is known as:
1. iteration ✓
2. sequence
3. selection
4. none
Question 2
1. for
2. while
3. do-while ✓
4. if-else
Question 3
Which of the following loop does not execute even once if condition is false in the
beginning?
1. do-while
2. while ✓
3. for ✓
4. nested loop
Question 4
1. for(i=6;i<=26;i=i+2)
2. for(i=3;i<=30;i=i+3) ✓
3. for(i=0;i<10;i=i++)
4. all of the above
Question 5
1. loop
2. continue
3. switch ✓
4. break
Question 6
Which of the following loop checks the condition first and then execution begins?
1. do-while
2. do
3. while loop ✓
4. for ✓
Question 7
1. once
2. ten times
3. eleven times ✓
4. any number of times
Question 8
How many times the loop, for (i=1; ;i++), will execute, if there is no statement to terminate
the loop?
1. 1
2. 0
3. infinite ✓
4. none
Question 9
1. do-while
2. while
3. switch ✓
4. all of the above
Question 10
for(i=10;i<10,i++)
{
Statement
}
For how many times will the given loop statement be executed:
1. never ✓
2. 1 time
3. 10 times
4. infinite
Question 1
What do you understand by iterative process? How can it be resolved by using loop?
Iterative process means repeating a set of actions a certain number of times to perform
some task. Loops in programming languages like Java enable us to repeat a single
statement or a set of statements as long as the desired condition remains true.
Question 2
1. for
2. while
3. do-while
Question 4
Question 5
Question 6
do {
//loop-body
} while (condition);
(c) while loop
while (condition) {
//loop-body
}
Question 7
Question 8
Question 9
What are the different ways to inter-convert the loops? Name them.
Question 10
Distinguish between:
1. for loop is a suitable choice when we know the number of iterations beforehand. while
loop is helpful in situations where numbers of iterations is not known.
2. Omitting the condition in for loop will lead to an infinite loop whereas if condition is not
provided in while loop, it will cause a compilation error.
Question 12
State one difference and one similarity between while and do-while loop
Similarity — Both while and do-while are suitable in situations where numbers of
iterations is not known.
Difference — while is an entry-controlled loop whereas do-while is an exit-controlled
loop
Question 13
State one similarity and one difference between while and for loop.
Similarity — Both for and while are entry-controlled loops
Difference — for loop is a suitable choice when we know the number of iterations
beforehand. while loop is helpful in situations where numbers of iterations is not known.
Question 14
Question 1
class dkl
{
public static void main(String args[])
{
int i;
for(i = -1;i<10;i++)
{
System.out.println(++i);
}
}
}
Output
10
Explanation
This table shows the changes in the value of i as the for loop iterates:
i Remarks
-1 Initial value
class dk2
{
public static void main(String args[])
{
int i=2,k=1;
while (++i<6)
k *= i;
System.out.println(k);
}
}
Output
60
Explanation
This table shows the change in values of i and k as while loop iterates:
i k Remarks
2 1 Initial values
3 3 1st Iteration
4 12 2nd Iteration
5 60 3rd Iteration
Notice that System.out.println(k); is not inside while loop. As there are no curly braces so
only the statement k *= i; is inside the loop. The statement System.out.println(k); is
outside the while loop, it is executed once and prints value of k which is 60 to the console.
Question 3
class dk3
{
public static void main(String args[])
{
int m=2,n=15;
for(int i=1;i<=5;i++)
{
m++;--n;
System.out.println("m="+m);
System.out.println("n="+n);
}
}
}
Output
m=3
n=14
m=4
n=13
m=5
n=12
m=6
n=11
m=7
n=10
Explanation
This table shows the change in values of m, n and i as the for loop iterates:
m n i Remarks
2 15 — Initial values
3 14 1 1st Iteration
4 13 2 2nd Iteration
5 12 3 3rd Iteration
6 11 4 4th Iteration
m n i Remarks
7 10 5 5th Iteration
Question 4
Determine how many times the body of the loop will be executed.
class dk4
{
public static void main(String args[])
{
int x=5,y=50;
while(x<=y)
{
y=y/x;
System.out.println(y);
}
}
}
Output
10
Explanation
x y Remarks
5 50 Initial values
After 2 iterations y becomes less than x so condition of while loop becomes false and it stops
executing.
Rewrite the following Programs
Question 1
Using do while:
class Test
{
public static void main(String args[])
{
int x,c;
for(x=10,c=20;c>=10;c=c-2)
{
x++;
System.out.println(x);
}
}
}
Solution
class Test
{
public static void main(String args[])
{
int x=10, c=20;
do {
x++;
System.out.println(x);
c=c-2;
} while (c>=10);
}
}
Question 2
Using do while:
class Pattern
{
public static void main(String args[])
{
int i,j;
for(i=5;i>=1;i--)
{
System.out.print(i);
}
System.out.println();
}
}
Solution
class Pattern
{
public static void main(String args[])
{
int i=5,j;
do {
System.out.print(i);
i--;
} while (i>=1);
System.out.println();
}
}
Question 3
Using do while:
class Number
{
public static void main(String args[])
{
int i,n=191,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
c=c+1;
}
if(c==2)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
Solution
class Number
{
public static void main(String args[])
{
int i=1,n=191,c=0;
do {
if(n%i==0)
c=c+1;
i++;
} while (i<=n);
if(c==2)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
Question 4
import java.io.*;
class Sample
{
public static void main(String args[]) throws IOException
{
int n,r;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("Enter a number");
n=Integer.parseInt(in.readLine());
do
{
r=n%10;
n=n/10;
System.out.println(r);
}
while(n!=0);
}
}
Solution
import java.io.*;
class Sample
{
public static void main(String args[]) throws IOException
{
int n,r;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("Enter a number");
n=Integer.parseInt(in.readLine());
while(n!=0)
{
r=n%10;
n=n/10;
System.out.println(r);
}
}
}
Solutions to Unsolved Java Programs
Question 1
Write the programs in Java to display the first ten terms of the following series:
(a) 1, 4, 9, 16,
Output
(b) 1, 2, 4, 7, 11,
Output
(c) 3, 6, 9, 12,
(f) 0, 7, 26,
(i) 0, 3, 8, 15,
Question 2
import java.util.Scanner;
Write a program to calculate the sum of all odd numbers and even numbers between a range
of numbers from m to n (both inclusive) where m < n. Input m and n (where m<n).
import java.util.Scanner;
if (m > n) {
System.out.println("m should be less than n");
}
else {
for (int i = m; i <=n; i++) {
if (i % 2 == 0)
sumEven += i;
else
sumOdd += i;
}
Question 4
Write a program to enter any 50 numbers and check whether they are divisible by 5 or not. If
divisible then perform the following tasks:
(a) Display all the numbers ending with the digit 5.
(b) Count those numbers ending with 0 (zero).
import java.util.Scanner;
Write a program to display all the numbers between m and n input from the keyboard (where
m<n, m>0, n>0), check and print the numbers that are perfect square. e.g. 25, 36, 49, are said
to be perfect square numbers.
import java.util.Scanner;
Question 6
Write a program to display all the 'Buzz Numbers' between p and q (where p<q). A 'Buzz
Number' is the number which ends with 7 or is divisible by 7.
import java.util.Scanner;
}
}
Output
Question 7
Write a program to input marks in English, Maths and Science of 40 students who have
passed ICSE Examination 2014. Now, perform the following tasks:
(a) Number of students, who have secured 95% or more in all the subjects.
(b) Number of students, who have secured 90% or more in English, Maths and Science.
import java.util.Scanner;
Output
Output
(e) 2 - 4 + 6 - 8 + ...... - 20
Write a program to input a number and count the number of digits. The program further
checks whether the number contains odd number of digits or even number of digits.
Sample Input: 749
Sample Output: Number of digits=3
The number contains odd number of digits.
import java.util.Scanner;
while (n != 0) {
dc++;
n /= 10;
}
if (dc % 2 == 0)
System.out.println("The number contains even number of
digits");
else
System.out.println("The number contains odd number of
digits");
}
}
Output
Question 10
Write a program to input a number and display the new number after reversing the digits of
the original number. The program also displays the absolute difference between the original
number and the reversed number.
Sample Input: 194
Sample Output: 491
Absolute Difference= 297
import java.util.Scanner;
while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
int diff = revNum - orgNum;
System.out.println("Reversed Number = " + revNum);
System.out.println("Absolute Difference = " +
Math.abs(diff));
}
}
Output
Question 11
The Greatest Common Divisor (GCD) of two integers is calculated by the continued division
method. Divide the larger number by the smaller, the remainder then divides the previous
divisor. The process repeats unless the remainder reaches to zero. The last divisor results in
GCD.
Sample Input: 45, 20
Sample Output: GCD=5
import java.util.Scanner;
Output
Question 12
(a) S = a2 + a2 / 2 + a2 / 3 + ...... + a2 / 10
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
(d) S = a + a2 + a3 + ...... + an
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
Question 13
In order to reach the top of a pole, a monkey in his first attempt reaches to a height of 5 feet
and in the subsequent jumps, he slips down by 2% of the height attained in the previous
jump. The process repeats and finally the monkey reaches the top of the pole. Write a
program to input height of the pole. Calculate and display the number of attempts the monkey
makes to reach the top of the pole.
import java.util.Scanner;
Question 14
Write a program to input Principal (p), Rate (r) and Time (t). Calculate and display the
amount, which is compounded annually for each year by using the formula:
Simple Interest (si) = (prt) / 100
p = p + si
[Hint: The amount after each year is the Principal for the next year]
import java.util.Scanner;
Output
Question 15
Write a menu driven program to input two positive numbers m and n (where m>n) and
perform the following tasks:
(a) Find the sum of two numbers without using '+' operator.
(b) Find the product of two numbers without using '*' operator.
(c) Find the quotient and remainder of two numbers without using '/' and '%' operator.
[Hint: The last value obtained after each subtraction is the remainder and the number of
iterations results in quotient.]
Sample Input: m=5, n=2
5 - 2 =3
3 - 2 = 1, thus Quotient = 2 and Remainder = 1
import java.util.Scanner;
if (m > n) {
switch (choice) {
case 1:
while (n > 0) {
m++;
n--;
}
System.out.println("Sum = " + m);
break;
case 2:
int p = 0;
while (n > 0) {
p += m;
n--;
}
System.out.println("Product = " + p);
break;
case 3:
int q = 0;
while (m >= n) {
m = m - n;
q++;
}
System.out.println("Quotient = " + q);
System.out.println("Remainder = " + m);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
else {
System.out.println("Invalid Inputs");
}
}
}
Output
Question 16
Write a menu driven class to accept a number from the user and check whether it is a
Palindrome or a Perfect number.
(a) Palindrome number: (A number is a Palindrome which when read in reverse order is same
as in the right order)
Example: 11, 101, 151 etc.
(b) Perfect number: (A number is called Perfect if it is equal to the sum of its factors other
than the number itself.)
Example: 6 = 1 + 2 + 3
import java.util.Scanner;
switch (choice) {
case 1:
int copyNum = num;
int revNum = 0;
while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
if (revNum == num)
System.out.println(num + " is palindrome");
else
System.out.println(num + " is not palindrome");
break;
case 2:
int sum = 0;
if (num == sum)
System.out.println(num + " is a perfect number");
else
System.out.println(num + " is not a perfect
number");
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 17
Write a menu driven program to accept a number from the user and check whether it is a
Prime number or an Automorphic number.
(a) Prime number: (A number is said to be prime, if it is only divisible by 1 and itself)
Example: 3,5,7,11
(b) Automorphic number: (Automorphic number is the number which is contained in the last
digit(s) of its square.)
Example: 25 is an Automorphic number as its square is 625 and 25 is present as the last two
digits.
import java.util.Scanner;
switch (choice) {
case 1:
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
if (c == 2)
System.out.println(num + " is Prime");
else
System.out.println(num + " is not Prime");
break;
case 2:
int numCopy = num;
int sq = num * num;
int d = 0;
/*
* Count the number of
* digits in num
*/
while(num > 0) {
d++;
num /= 10;
}
/*
* Extract the last d digits
* from square of num
*/
int ld = (int)(sq % Math.pow(10, d));
if (ld == numCopy)
System.out.println(numCopy + " is automorphic");
else
System.out.println(numCopy + " is not automorphic");
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 18
Write a menu driven program to perform the following tasks by using Switch case statement:
(a) To print the series:
0, 3, 8, 15, 24, ............ to n terms. (value of 'n' is to be an input by the user)
(b) To find the sum of the series:
S = (1/2) + (3/4) + (5/6) + (7/8) + ........... + (19/20)
import java.util.Scanner;
switch (choice) {
case 1:
System.out.print("Enter n: ");
int n = in.nextInt();
for (int i = 1; i <= n; i++)
System.out.print(((i * i) - 1) + " ");
System.out.println();
break;
case 2:
double sum = 0;
for (int i = 1; i <= 19; i = i + 2)
sum += i / (double)(i + 1);
System.out.println("Sum = " + sum);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 19
import java.util.Scanner;
switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;
case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Output
Question 20
A special two-digit number is such that when the sum of its digits is added to the product of
its digits, the result is equal to the original two-digit number.
Example: Consider the number 59.
Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits to the product of its
digits. If the value is equal to the number input, then display the message "Special 2 - digit
number" otherwise, display the message "Not a special two-digit number".
import java.util.Scanner;
while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
digitProduct *= digit;
count++;
}
if (count != 2)
System.out.println("Invalid input, please enter a 2-
digit number");
else if ((digitSum + digitProduct) == orgNum)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");
}
}
Output
Question 21
switch (choice) {
case 1:
System.out.print("Enter number: ");
num = in.nextInt();
for (int i = 1; i < num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
break;
case 2:
System.out.print("Enter number: ");
num = in.nextInt();
int f = 1;
for (int i = 1; i <= num; i++)
f *= i;
System.out.println("Factorial = " + f);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 22
Write a program to input a number. Check and display whether it is a Niven number or not.
(A number is said to be Niven which is divisible by the sum of its digits).
Example: Sample Input 126
Sum of its digits = 1 + 2 + 6 = 9 and 126 is divisible by 9.
import java.util.Scanner;
int digitSum = 0;
while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
}
/*
* digitSum != 0 check prevents
* division by zero error for the
* case when users gives the number
* 0 as input
*/
if (digitSum != 0 && orgNum % digitSum == 0)
System.out.println(orgNum + " is a Niven number");
else
System.out.println(orgNum + " is not a Niven number");
}
}
Output
Question 23
Write a program to accept a number and check whether it is a 'Spy Number' or not. (A
number is spy if the sum of its digits equals the product of its digits.)
Example: Sample Input: 1124
Sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1*1*2*4 = 8
import java.util.Scanner;
sum += digit;
prod *= digit;
num /= 10;
}
if (sum == prod)
System.out.println(orgNum + " is Spy Number");
else
System.out.println(orgNum + " is not Spy Number");
}
}
Output
Question 24
Using switch statement, write a menu driven program for the following:
(a) To find and display the sum of the series given below:
S = x1 - x2 + x3 - x4 + x5 - ............ - x20; where x = 2
(b) To display the series:
1, 11, 111, 1111, 11111
For an incorrect option, an appropriate error message should be displayed.
import java.util.Scanner;
switch (choice) {
case 1:
int sum = 0;
for (int i = 1; i <= 20; i++) {
int term = (int)Math.pow(2, i);
if (i % 2 == 0)
sum -= term;
else
sum += term;
}
System.out.println("Sum=" + sum);
break;
case 2:
int term = 1;
for (int i = 1; i <= 5; i++) {
System.out.print(term + " ");
term = term * 10 + 1;
}
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Chapter 9
Question 1
Question 2
Question 3
Question 4
Question 5
Continue statement will repeat a loop for next iteration after ignoring some statements of the
loop.
Question 1
Question 2
Question 4
When outer loop completes its iterations, the inner loop starts. False
Question 5
Labelled continue statement allows the next iteration of the loop from any place of looping
structure.
False
Question 1
Question 2
1. break statement is used to unconditionally jump out of the loop whereas continue
statement is used to unconditionally jump to the next iteration of the loop, skipping the
remaining statements of the current iteration.
2. break statement is used in switch-case and loops whereas continue statement is only used
in loops.
Question 3
Question 1
Question 3
How will you terminate outer loop from the block of the inner loop?
By using Labelled break statement.
Question 4
Question 5
executable statement(s)
}
Give the output of the following snippets based on nested
loops
Question 1
int i,j;
for (i=0; i<4; i++)
{
for (j=i; j>=0; j--)
System.out.print(j);
System.out.println();
}
Output
10
210
3210
Explanation
For each iteration of outer for loop, inner for loop will iterate from i to 0 printing the above
pattern.
Question 2
int y,p;
for (int x=1; x<=3; x++)
{
for (y=1; y<=2; y++)
{
p = x * y;
System.out.print(p);
}
System.out.println( );
}
Output
12
24
36
Explanation
x y p Remarks
2 2
2 4
2 6
Question 3
int a,b;
for (a=1; a<=2; a++)
{
for (b= (64+a); b<=70; b++)
System.out.print((char) b);
System.out.println( );
}
Output
ABCDEF
BCDEF
Explanation
In the first iteration of outer for loop, the inner for loop will print characters with ASCII
codes from 65 to 70 i.e. letters from A to F.
In the second iteration of outer for loop, the inner for loop will print characters with ASCII
codes from 66 to 70 i.e. letters from B to F.
Question 4
int x,y;
for(x=1; x<=5; x++)
{
for(y=1; y<x; y++)
{
if(x == 4)
break;
System.out.print(y);
}
System.out.println( );
}
Output
12
1234
Explanation
Question 5
int i,j;
first:
for (i=10; i>=5; i--)
{
for (j= 5; j<=i; j++)
{
if (i*j <40)
continue first;
System.out.print(j);
}
System.out.println( );
}
Output
5678910
56789
5678
Explanation
For the first 3 iterations of outer loop i * j >= 40. After that as the condition of if (i*j
<40) becomes true, in each iteration of inner for, continue statement transfers the program
control to the next iteration of outer for loop.
Question 1
Write a program to display the Mathematical Table from 5 to 10 for 10 iterations in the given
format:
Sample Output: Table of 5
5*1 = 5
5*2 =10
--------
--------
5*10 = 50
public class KboatTables
{
public static void main(String args[]) {
for (int i = 5; i <= 10; i++) {
System.out.println("Table of " + i);
for (int j = 1; j <= 10; j++) {
System.out.println(i + "*" + j + " = " + (i*j));
}
}
}
}
Question 2
Write a program to accept any 20 numbers and display only those numbers which are prime.
Hint: A number is said to be prime if it is only divisible by 1 and the number itself.
import java.util.Scanner;
Write a program to compute and display the sum of the following series:
S = (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + -------- + (1 + 2 + 3 + ----- + n ) / (1 * 2 * 3 *
----- * n)
import java.util.Scanner;
Output
Question 4
Write two separate programs to generate the following patterns using iteration (loop)
statements:
(a)
*
* #
* # *
* # * #
* # * # *
Output
(b)
54321
5432
543
54
5
Output
Question 5
Write a program to calculate and display the factorials of all the numbers between 'm' and 'n'
(where m<n, m>0, n>0).
[Hint: factorial of 5 means: 5!=5*4*3*2*1]
import java.util.Scanner;
}
}
Output
Question 6
Write a menu driven program to display all prime and non-prime numbers from 1 to 100.
Enter 1: to display all prime numbers
Enter 2: to display all non-prime numbers
Hint: A number is said to be prime if it is only divisible by 1 and the number itself.
import java.util.Scanner;
switch (choice) {
case 1:
for (int i = 2; i <= 100; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println(i);
}
break;
case 2:
System.out.println(1);
for (int i = 2; i <= 100; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (!isPrime)
System.out.println(i);
}
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 7
In an entrance examination, students have answered English, Maths and Science papers.
Write a program to calculate and display average marks obtained by all the students. Take
number of students appeared and marks obtained in all three subjects by every student along
with the name as inputs.
import java.util.Scanner;
Question 8
import java.util.Scanner;
if (num == 1) {
System.out.println(num + " is not a twisted prime
number");
}
else {
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
int t = num;
int revNum = 0;
while (t != 0) {
int digit = t % 10;
t /= 10;
revNum = revNum * 10 + digit;
}
if (isPrime)
System.out.println(num + " is a twisted prime
number");
else
System.out.println(num + " is not a twisted
prime number");
}
}
}
Output
Question 9
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
Question 10
(a)
1
21
321
4321
54321
(b)
12345
1234
123
12
1
(c)
54321
5432
543
54
5
(d)
13579
1357
135
13
1
(e)
5
54
543
5432
54321
(f)
12345
2345
345
45
5
(g)
99999
77777
55555
33333
11111
(h)
9
79
579
3579
13579
(i)
9
97
975
9753
97531
(j)
1
23
456
7 8 9 10
11 12 13 14 15
Question 1
JDK1.5 allows a special class to input from the console. This class is termed
as Scanner class.
Question 2
Question 3
Question 4
Question 5
System.in receives the input from the keyboard for the scanner object.
Question 6
Question 7
Question 8
The method which checks whether the next token of the scanner object is a floating type
value or not is hasNextFloat().
Question 9
hasNextBoolean() is the method used to check whether the next token is a boolean type
value or not.
Question 10
Question 1
Question 2
Question 3
Question 4
You need not be aware about the number of tokens to be input to a scanner object.
True
Question 5
Question 6
Question 7
Question 1
Question 2
Syntax
Example
Question 3
Question 4
Question 5
Question 6
Name the package which can be imported to allow the use of scanner class.
java.util
Question 7
In what way can the following data be read from the scanner object?
Question 1
Scanner class parses the tokens into specific types like BufferedReader just reads the stream and does
short, int, float, boolean, etc. not do any special parsing.
Question 2
nextFloat( ) nextDouble( )
It reads the next token entered by the user as a It reads the next token entered by the user as a
float value. double value.
Question 3
next( ) nextLine( )
It reads the next complete token from the Scanner It reads the complete line from the Scanner
object. object.
Question 4
hasNext( ) hasNextLine( )
Returns true if the Scanner object has another Returns true if there is another line in the input of
token in its input. the Scanner object.
Question 5
hasNextInt( ) hasNextBoolean( )
Question 1
Using scanner class, write a program to input temperatures recorded in different cities in °F
(Fahrenheit). Convert and print each temperature in °C (Celsius). The program terminates
when user enters a non-numeric character.
import java.util.Scanner;
public class KboatTemperatureConvert
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Temperature in Fahrenheit: ");
while (in.hasNextDouble()) {
double t = in.nextDouble();
double ct = 5 / 9.0 * (t - 32);
System.out.println("Temperature in Celsius: " + ct);
System.out.print("Enter Temperature in Fahrenheit: ");
}
}
}
Output
Question 2
Write a program to accept a set of 50 integers. Find and print the greatest and the smallest
numbers by using scanner class method.
import java.util.Scanner;
if (n < small)
small = n;
}
System.out.println("Smallest Number = " + small);
System.out.println("Largest Number = " + big);
}
}
Output
Question 3
Write a program (using scanner class) to generate a pattern of a token in the form of a triangle
or in the form of an inverted triangle depending upon the user's choice.
Sample Input/Output:
Enter your choice 1
*
**
***
****
*****
Enter your choice 2
*****
****
***
**
*
import java.util.Scanner;
default:
System.out.println("Invalid Choice");
break;
}
}
}