0% found this document useful (0 votes)
52 views79 pages

Organized Merged

Uploaded by

anuveena
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)
52 views79 pages

Organized Merged

Uploaded by

anuveena
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/ 79

CONTENTS

1. Introduction to Java

2. Input Statement

3. Conditional Statement

4. Tokens

5. Datatypes

6. Expressions

7. Class Math

8. Iteration - Counters

9. Iterations – Accumulator

10.Nested Loops

11. Modulus
CHAPTER 1
INTRODUCTION TO JAVA
Java is Third Generation Object Oriented Programming Language developed
by Sun MicroSystems in the year 1991. It was originally named as Oak. It is
designed to be small, simple and portable across different platforms. Java is
both a programming language and a platform. It is programming language,
because you can create various types of applications. It is also a platform for
application development. Platform refers to combination of hardware and
system software.

Characteristics of Java
1.Write Once Run Anywhere(WORA) :compiled Java program can be run
anywhere without making any changes.
2. Light Weight Code :Because of advanced Java API(application program
interface) even complex applications can be developed with light code.(API
consists of pre-compiled library files)
3. Security : This feature make Java programs safe for the platform independent
on which they execute
4. Built-in graphics : This features makes development of visual application
very simple
5. Object-Oriented Language: Being an object oriented language, java can be
used to simulate real world objects.
6.Supports Multimedia : Ideally suited for integration of video, audio and
animation in stand-alone and internet based applications
7.Open product :Being an open product, it can be down-loaded and freely
available for all.
Java Compilation Process
To understand Java compilation process you need to understand the
development of computer languages Generation Computer
Languages
Machine Level Assembly Level Language / High Level
Language/ First Second Generation Computer Language
Generation Language
Computer
Language/ Binary
Language
Computer can Assembly language uses binary These languages
understand only one number with Mnemonics. These are similar to
language called Mnemonics are 3 letter words like English language
Binary Language ADD, SUB, MUL, DIV which and a common
which is made of 0’s were used instead of codes. As person could
and 1’s. O or 1 is computer can understand only easily understand
called a bit (Binary binary language, there is a and program it. It

1
digit). This binary translator which converts has many English
language was difficult Mnemonics to Machine level words like if,
to understand and to language. This translator is called while, then, for
code it. The user had Assembler. etc.
to know the working Some of the draw backs of
of the computer. The Machine level language still
user had to memorize existed here like:
the codes which  the user need not memorize
varied from machine the code but they had to
to machine. So this know the internal working
was not popular. of the computer.
 The user had to know
binary language.

As computer can understand only machine language. There are 2 types of


translator to convert high level language to machine language. They are:

Compiler Interpreter
1. Translates High Level Language to 1. Translates High Level Language to
Machine Level language all at once. Machine line by line.
2. It is Fast. 2. It is slow.
3.. HLL like C, COBOL, FORTRAN 3. HLL BASIC uses Interpreter.
and Pascal uses Compiler

Ordinary Compilation Process


Program is a set of instructions given to a computer. The program or code
written by a programmer is usually called the Source Code. The source code
needs to be converted into machine language code or object code(which the
computer can easily understand). This process of converting source code to
machine code is called Compilation.
In ordinary compilation process, the source code is directly converted to
machine code depending on the machine it has been compiled. So, this
machine code will not work on other platforms or computers other than the
computer on which it has been compiled. All the languages like BASIC,
COBOL, FORTRAN, C used this type of compilation. So, the machine code
obtained was not platform independent.

2
Java Compilation Process
Java uses both compiler(jdk) and interpreter(JVM) to translate Source code to
Machine code.
1. First Java uses compiler(jdk) to translate high level language (source
code) to Byte code. This byte code is independent of the computer
system it has been compiled.
2. Secondly, Java uses an interpreter (called JVM) which reads the byte
code line by line and converts it to machine code (native executable
code) depending on the platform or computer on which the application or
program is to executed.

Bytecode : is a code which is obtained after compiling the source code. It is


independent of the machine that it has to run upon.
Source code → compile (using jdk compiler) → Byte code

Java Virtual Machine is an (interpreter) abstract machine. It is implemented


on top of existing processors and hides the OS from Java application. It
executes the byte code one line at a time and converts it to native executable
code.
The JVM is a software program and not a hardware. Therefore it is called a
virtual machine. These JVM programs (.class files) are portable and can run on
any machine that has the java program.

Byte code → Interpret (using JVM) →Native executable code

Java byte Code Native executable code


Java byte code is obtained after the Byte code is executed line by line
compilation process. This code is using JVM to obtain Native executable
independent of the machine that it has code which is native (dependent) to the
to execute upon. machine it has to execute upon.

Types of Java Program


There are two different platforms for writing java programs. They are:
 Java Applets
 Java Application

3
Java Applets Java Application
 A small program.  A large program.
 Created by extending the  Created by writing the program
java.applets.Applets inside the main method.
 They are executed on web  They are executed using java
browser. compiler jdk.

BlueJ
BlueJ is a window based IDE(Integrated Development Environment), for JDK
(Java Development Kit) which includes an editor, a debugger and a viewer. It
offers an easy way to run java program and view the documents.
There are many more java IDE’s, which includes an editor, a debugger and a
viewer. Some of them are JCreator, NetBeans, Ecllipse, etc. All the IDE’s use
the same java jdk compiler. As the compiler is same the java language and the
syntax remains the same so, we can use any IDE to type the program and get the
result.

Similarity between Java Character Set and ASCII Character Set


ANSI- American National Standard Institute was set up to standardize the
code so that all the computer languages use the same code called ASCII code.
ASCII uses128 characters ie it contains all the alphabets of English and number.
As it cannot be universally accepted UNICODE was developed.

The first 128 characters in UNICODE character set and ASCII character set are
identical. i.e. They represent the same characters.

Java Character Set ASCII Character Set


(UNICODE)
1. It is a 2 byte character code set 1. It is 1 byte character code set
2. It represents 65536 characters, 2. It can represent only 128 characters
which means almost all alphabets and which is limited.
writing symbols around the world can 3. ASCII- American Standard Code
be represented. for Information Interchange.
3. UNICODE- UNIversal CODE

Assignment
1.Give one word for the following:
a) The original name for Java.
b) The program which can run anywhere without making changes
c) The software that can be downloaded
d) The language used to simulate real world objects.
e) Set of instruction
f) The program written by the programmer
4
g) The process of converting the source program to machine language
h) The code which is independent of the machine that it has to run upon.
i) It is implemented on top of existing processors and hides the OS from
Java application.
j) They are pre-compiled library code that can be used in your programs.
k) It needs a web browser to execute the program.
l) It can run independently on any platform using jdk compiler and JVM.
2.Give the full form:
i)WORA ii) IDE iii) UNICODE iv) ASCII v)JVM iv)API
3.Differentiate the following:
i) UNICODE & ASCII code
ii) Bytecode & Native executable code
iii) Jdk & JVM
iv) Compiler & Interpreter
v) Internet applets & Stand alone application
4.Answer the following:
i) How is java compilation process different from the ordinary
compilation process?
ii) What is byte code and JVM?
iii) What are the 2 types of Java program?

5
CHAPTER 2
INPUT - OUTPUT STREAMS

Stream : A stream in java is a sequence of data. There are two kinds of Streams −
 InputStream − The InputStream is used to read data from a source. Data comes
from the keyboard to the program.
 OutputStream − The OutputStream is used for writing data to a destination.
From the computer to the monitor.
Java provides the following three standard streams −
 Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
 Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.
 Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.

Package: It is a group of related classes and interfaces. Its main advantage is that, it
provides a convenient mechanism for managing a voluminous set of classes and
interfaces and avoiding name conflicts. One can also create their own package.
import : is a statement to include a package in the program.

Statement
A statement is a single line of instruction which is terminated by a semicolon.
To accept values using class Scanner
We can input to the program from the keyboard through the methods of the class
Scanner. To include the package of the class Scanner in a program we use import
statement.
import java.util.Scanner;

Statement to Name of the Name of the class present in


include a package package the package java.util

import java.util.Scanner;
Or
import java.util.*;

The former statement gives access only to the class Scanner present in the package
java.util.
5
The latter statement gives access to all the classes present in the package java.util.

Once the package is imported to the class then an object of the class is created to take the
control of the methods present in it. System.in is connected to the keyboard. It is passed
as parameter to Scanner class to create an object for the class Scanner.
Scanner sc = new Scanner(System.in);
int a = sc.nextInt()

Object of Method present in


Data
scanner the Scanner class
type class to accept integer

Variable of type int

Statements to accept different datatype using Scanner class


To Accept an integer data type : int a = sc.nextInt();
To Accept a long data type : long l = sc.nextLong();
To accept a double data type : double d = sc.nextDouble();
To accept a float data type : float f = sc.nextFloat();
To accept a word : String s=sc.next();
To accept a String : String s=sc.nextLine();
To accept a char data type : char ch = sc.next().charAt(0);

next() nextLine()
This is method of class scanner which This is a method of class scanner which
accepts a word from the keyboard accepts a String from the keyboard.

Simple Output Statement


System.out.println() is a way to send output to the monitor.
Note: 1) System.out refers to output stream and print() and println() are methods present
in the class System. 2) out is a data member of the class System.

print() println()
This methods prints the value and then the This method prints the value and moves the
cursor remains on the same line. So, cursor to the next line. So, println()
print() does not adds new line automatically adds new line
character(\n) at the end of the text being character(\n) at the end of the text being
printed. printed.

6
Comments
Comments are text notes or documents added by the programmer to explain the source
code or program. These comments are ignored by the compiler. There are two types of
comments in java. They are:
 Single Line comments
 Multiple Line Comments
Single line Comment Multiple line Comment
The comment can be given in a Single The comments can be given in Multiple
Line. lines.
Eg: Eg:
// This program adds 2 numbers /* This is a very trick program which need
to be figured out with lot of effort */

Write a program to accept two integers and find their sum. Print the result in the
following format: Sum of -------- and -------- is -----------
import java.util.Scanner;
class Addition
{ public static void main(String args[])
{Scanner Sc= new Scanner(System.in);
int n1,n2,sum;
System.out.println("Enter first number");
n1=Sc.nextInt();
System.out.println("Enter second number");
n2=Sc.nextInt();
sum=n1+n2;
System.out.println("Sum of "+ n1 +” and “+n2 +” is “+ sum);
}}

Write a program to accept roll number, name, Marks in English, Math and
computer. Find their total and average and print the result in a neat format- using
Scanner class
import java.util.Scanner;
class Student
{ public static void main(String args[])
{Scanner Sc= new Scanner(System.in);
String n;
int rn;
double eng,math,comp,t,av;
System.out.println("Enter your name");
n=Sc.nextLine();
7
System.out.println("Enter your rollnumber");
rn=Sc.nextInt();
System.out.println("Enter your marks in English");
eng=Sc.nextDouble();
System.out.println("Enter your marks in Maths");
math=Sc.nextDouble();
System.out.println("Enter your marks in Computer");
comp=Sc.nextDouble();

t=eng+math+comp;
av=t/3;
System.out.println("-----------------------------------");
System.out.println(" Marks Card");
System.out.println("------------------------------------");

System.out.println("Name is " + n + " Roll Number is " + rn);


System.out.println("Marks in English " + eng + " Marks in Math" + math + " Marks in
Computer " + comp);
System.out.println("Total Marks " + t + " Average Marks " + av);
System.out.println("--------------------------------------");
}
}

White Space: They are spaces bar, tabs and new lines for improving visual appearance
of the source code.
Escape sequence : Even escape sequence are used with output to improve visual
appearance.
Some of the escape sequence are: \n \t \\ \” \’

Exercise 2.1
Write a java statement to print the following:
a) This is the time for all the Good men in the world.
b) “It’s fine to celebrate success, but it is more important to heed to the lessons
of failure.” – Bill Gates.
c) To win big, you
sometimes have to take big risks. (use one print statement)
d) The only limit to the height of your achievement is –
the reach of your dreams and your willingness to work hard for them.
(use one print statement)
e) Todays date is 24\10\2000
8
Exercise 2.2
Write the output of the following statement
a) System.out.print("Writing program");
System.out.print(" is fun... \n Writing Java program is even more fun");

b) System.out.println("Ram said,\" We are going \n out Tomorrow\" ");


System.out.println(" hope it doesn’t rain");

c) System.out.println("Hello! \"where are you? \n");


System.out.println("going\" ");

d) System.out.print("I am coming to \n\n");


System.out.println("see you ");
System.out.println("\" Tomorrow\" ");

Exercise 2.3 Program


a)Write a program in Java to accept Principal, time and rate and calculate simple interest.
Print the result in the following format:
Principal is Rs ------------
Time is -------- years
Rate is --------%
Simple Interest is Rs. ------------

b) Write a program to accept Length and breadth and calculate area of Rectangle. Print
all in the following format: Length is --------- breadth is ------------ Area is -------------

c) Write a program to accept radius and calculate area of circle and its circumference.
Print the result in the following format:
Radius is -----------
Area is -----------=
Circumference is -------------
d)Write a program to accept 3 integer values (two sides and the height) and calculate
the area of trapezium using formula:
1
area= height (a  b)
2
e) Write a program to accept employee number, Name and basic salary. Calculate
House Rent Allowance which is 14.5% of the annual salary. Print the result in the
following format:
Employee Number -------- Name -------------
Basic Salary ------------------ House Rent allowances --------------
****************************************************************

9
CHAPTER 3

Programming constructs
In a program, statements may be executed sequentially, selectively or iteratively. Every
programming language provides constructs to support sequence, selection or iteration.
Sequence: In sequence construct the statements are executed one after the other in a
sequence. In java, program starts with the first statement of the main () and ends with the last
statement of the main.
Selection: In selection construct, execution of the statement(s) depends upon a condition-
test. If the condition evaluates true then the statements following the condition is evaluated.
Iteration: The iteration construct means repetition of set of statements depending on a
condition test. As long as the condition is satisfied the set of statements are executed. It is
also called as looping statements. The set of statements that are repeated again and again are
called the body of the loop. The condition on which the execution or exit of the loop depends
is called the exit condition or test condition.

Selection/ condition Statement


The selection statement in java is if-then statement. Selection allows to execute set of
instruction depending upon the condition. Java provides 2 types of selection statements.
They are if and switch. In addition ternary operators (? : ) can also be used as conditional
statement. They are also called as decision statement.
Syntax and example of if statement

Sl.no Syntax Example


1 if( cond1 ) if( age < 10 )
{ {
System.out.println ("Child");
} }

2 if( cond1 ) if ( marks >= 60 )


{ {
System.out.println ("Pass");
} }
else else
{ {
System.out.println ("Fail");
} }
3 if(cond1) if ( marks >=80 )
{ ….. {
} System.out.println ("I class");
else if(cond2) }
9
{………. else if(marks >= 60)
} {
else if( cond3) System.out.println (" II class");
{ …… }
} else if(marks >= 40)
else {
{ System.out.println (" III class");
………… }
} else
{
System.out.println (" Fail");
}
3 if(cond1 && cond2) if ( marks >=60 && marks < 80)
{ {
} System.out.println ("I class");
else if(cond3 && cond4) }
{ else if(marks >= 40 && marks < 60)
} {
System.out.println (" II class");
else }
{ else
} {
System.out.println (" Fail");
}
4 if(cond1 || cond2) if ( sub.equals("Lang") ||
{ sub.equalsIgnoreCase("Social"))
} {
else if(cond3 || cond4) System.out.println ("Part I");
{ }
} else if( sub.equalsIgnoreCase("Sci") ||
(sub.equalsIgnoreCase("Mat"))
{
System.out.println (" Part II");
}
else
{
System.out.println ("Part III");
}
5 if ( ! (cond1 ) ) if ( ! ( age > 10) )
{ {
} System.out.println ("Child");
10
else }
{ else
} {
System.out.println ("Not Child");
}
6 if(cond1) if ( ( age >= 0))
{ if( cond2 ) { if( age < 10)
{ {
....... System.out.println ("Child");
} }
} }
else else
{if( cond3) {
{ } System.out.println ("Not Child");
} }

Relational operator

The following are the relational operators which are used in condition to compare the values.

Relational Name
operator
> Greater than
< Lesser than
>= Greater than equal to
<= Lesser than equal to
== Equal to
!= Not equal to

Note : A condition always returns a boolean value ( true or false)


Example of a condition is if(a > b) a and b are variables, > is relational operator, if is an
statement and the condition results in true or false.

11
Logical operator
When 2 or more conditions i.e compound condition are to be given then a (connective)
logical operator is used to connect them. The 3 logical operators are:
Logical Name
Operator
! NOT
&& AND
|| OR

Example of condition with Logical operator &&


if( a > b && a > c) a > b is one condition a > c is another condition both are connected
with a logical operator &&.
&& (AND) :It is a Binary Logical operator as it works on 2 or more conditions.
Truth table
Condition Condition Condition 1 &&
1 2 Condition 2
false false false && false = false
false true false && true = false
frue true true && false = false
true true true && true = true

|| (OR) : It is a BinaryaaaaaLogical operator as it works on 2 or more conditions.

Condition Condition Condition 1 || Condition


1 2 2
false false false || false = false
false true false || true = true
true false false || true = true
true true true|| true = true

! (NOT): It is a Unary Logical operator as it works on a single condition.


Condition ! (condition)
True false
False true

Give the output of the following condition:


int a=3,b=2,c=5;
( a>b ) || !( a>c ) && ( b>a )

12
(true) || ! (false) && (false) It will execute the condition
(true) || (true) && (false) It will execute the !(NOT) according to hierarchy
(true) || (false) It will execute && (AND) according to hierarchy
(true) It will execute || (OR) according to operator
precedency

Exercise on Conditional statement or selection statement

I Write Java statements for the following:


1. Check and print if the variable n is a positive number, negative number or zero
2. Check and print if the variable n is a single digit number or a double digit number or
a triple digit number.
3. Check if variable n it is an even or odd number
4. Check if the country name is equal to “INDIA” then a proud Indian “ else print the
message “You are not an Indian”.
5. Check if the variables n1 is both positive number and even numbers then print the
message “They are positive even numbers” else print the message “They are odd
numbers”.
6. Check if a variable n1 is even and positive
7. Check if the number is divisible by 5 and 7
8. Check if the number is divisible by 5 or 7

II. Programs on Conditional statements

1. Write a program to Create a class named “Student” to accept Roll number, name,
marks in English, maths and computers. Calculate total and average. Find the result
based on the condition:

Result
Average
>=80 “Distinction”
>=60 and <80 “First Class”
>=40 and <60 “II Class”
Else “Fail”
Print the result in the following format:
Roll number is -------- name is ------
Marks in English is ----- Maths is ----- Computers is -----
Total is ---- average is -----
Result is -------

13
2. Write a program to create a class named “Electricity” to accept meter numbers, Name of
the consumer, Previous meter reading and the present meter reading. Calculate units
consumed and cost based
on the following condition:

Units consumed Cost


UC <=100 80p per unit
UC>100 and <=200 Rs 120+60p for every unit greater then
100
UC >200 and less then Rs 230+ 50p for every unit greater than
300 200
Else Rs.340+ 30p for every unit greater then
300

Print all the details in a neat format:


Meter Number is -----
Name is -----
Previous meter reading -----
Present meter reading -----
Units Consumed is ----
Cost is -----

3. A telephone department wishes to compute telephone bills for the customers using the
following rules: minimum Rs. 250 for the first 50 units plus Rs. 1.20 per unit for the
next 200 units, plus Rs.1.10 for the next 150 units and Rs 1.00 for every unit above
that. Write a java code to take the following as input: customer number and number of
units. The output should contain : customer number, Number of units and amount of
bill.

4. Define a class name Employee ( int) pan to store personal account number, ( String)
name to store name, (double) taxincome to store annual taxable income. Calculate tax
based on the condition:
Total Annual Income Tax Rate
Upto Rs.1,00,000 No Tax
From 1,00,000 to 1,50,000 10% of income exceeding Rs.1,00,000
From 1,50,000 to 2,00,000 Rs. 5000 + 20% of income exceeding Rs 1,50,000
Above 2,00,000 Rs. 25000 + 30% of the income exceeding Rs.
2,00,000
Print the result in the following format:
14
Pan number Name TaxIncome Tax
----- ---- ----- --

5. Accept the distance traveled by the passenger and calculate the cost based on the
conditions:
Distance Cost/km
10km Rs. 10
next 20kms Rs. 6
next 30kms Rs. 4
Calculate cost and print it.

Programs using OR logical operator


1. Write a program to accept an alphabet and print if it a vowel or a consonant
2. Write a program to accept 3 sides of a triangle and print if it a right angle triangle or
not
3. Write a program to accept 3 sides of a triangle and print if it an equilateral triangle,
scalene triangle or isosceles triangle
4. Write a program to accept month as number and print the maximum number of day in
the given month
The switch Statement
Java provides a multiway-branching selection statement known as switch. This selection
statement successively tests the value of an expression against a list of integer or character or
String constants. When a match is found, the statements associated with that constant are
executed until it encounters the break statement. The default statement gets executed when
no match is found. Both break and default statements are optional. If you omit the break,
execution will continue on to the next case. This is called Fall Through. In case default
statement is not present, no action takes place if all matches fail.

Control variable : The variable passed as an argument to the switch statement that decides
which statements is to be executed is known as a control variable.
break statement: The statement used at the end of each case which acts as the case
terminator. As soon as the break is encountered the control is forced to move out of the
switch block.
default case: If no case is matched in the switch block for a given values of the control
variable, default case is executed implicitly.
System.exit(0): exit() is a method in the class System, in the package java.lang. This method
terminates the running program by terminating JVM.
exit(0) : Generally used to indicate successful termination.
exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful
termination.
15
Note : A case statement cannot exit by itself so a break statement is used.
Syntax
switch( integer/char)
{
case constant1 :
…..
break;
case constant2:
…….
break;
case constant3:
……..
break;
default:
……..
}
Characteristics of switch
1. A switch statement can only work on == relational operator.
2. Switch statements works only with integer, character and String data types.
3. No two case labels in the same switch can have identical values. If we compile the
program which has a switch statement containing two cases with identical values then
the compiler will flash a syntax error message “duplicate case label”.
4. When a value of a variable or an expression is to be compared with the list of possible
integer or character or String constants switch is preferred over nested if. As it faster
than nested-if.
Switch If-else
 The switch statement test only for  It can work on all the relational
equality operations
 It works on int(byte, short, int, long)  if works on all the datatypes
datatype, char datatype and String
datatype.  If can handle a range of values along
with logical OR (||)
 The switch statement selects its
branches by testing the value of the
expression with the one in the case  Nested if is not efficient
constant. It can handle a range of
16
values

 It is more efficient and faster than


nested if
Note: If you need to select among a large group of values, a switch will run much faster
than if–else. This is because the compiler knows all the case constants and must compare
only with equality with the switch expression.
Write a menu driven program to add, subtract, Multiply and divide 2 numbers
depending on the users choice using switch-case statement
import java.util.*;
class menu
{ public static void main(String args[])
{Scanner sc= new Scanner(System.in);
int n1,n2,res, ch;
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice :");
ch=sc.nextInt();
switch(ch)
{ case 1:
System.out.println("Enter a number");
n1= sc.nextInt();
System.out.println("Enter another number");
n2= sc.nextInt();
res=n1+n2;
System.out.println("The sum of "+ n1 +"and"+ n2 +" is "+res);
break;
case 2:
System.out.println("Enter a number");
n1= sc.nextInt();
System.out.println("Enter another number");
n2= sc.nextInt();
res=n1-n2;
System.out.println("The difference of "+ n1 +"and"+ n2 +" is "+res);
break;
case 3:
System.out.println("Enter a number");
n1= sc.nextInt();
17
System.out.println("Enter another number");
n2= sc.nextInt();
res=n1*n2;
System.out.println("The product of "+ n1 +"and"+ n2 +" is "+res);
break;
case 4:
System.out.println("Enter a number");
n1= sc.nextInt();
System.out.println("Enter another number");
n2= sc.nextInt();
res=n1/n2;
System.out.println("The quotient of "+ n1 +"and"+ n2 +" is "+res);
break;
case 5:
System.exit(0);

default:
System.out.println("Wrong Entry......");
}}}
Write the equivalent switch case for the following if- else if
{ if(a==2 || a==4 || a==6 || a==8) switch(a)
System.out.println(" Even Digit"); {case 2 : case 4: case 6: case 8:
else if(a==1 || a==3 || a==5 || a==7 || a==9) System.out.println(" Even Digit");
System.out.println(" Odd Digit"); break;
else case 1: case 3:case 5: case 7: case 9:
System.out.println("Zero"); System.out.println(" Odd Digit");
} break;
default:
System.out.println(" Zero");
}

Switch statement
1. Write a program to accept day of the week as number and print it in words
2. Write a program to accept month as number and print the maximum number of day in
the given month
3. Write a program to accept an alphabet and print if it a vowel or a consonant

18
Ternary operator (conditional operator)
The ternary operator ?: can replace if-else statement. They work on 3 operands and so the
name ternary operators. They are more concise compared to if statement. But when it comes
to nested if they become more complex.
Syntax:
(Condition)? Expression1:expression2
Expression1 is evaluated, if the condition results in true else Expression3 is executed
eg. int c = (a>b) ? a : b

Comparing if and ?:
 Ternary operator is more concise and compact
 Only single values can be assigned or evaluated. Whereas in if multiple statements
can be assigned or evaluated.
Ternary ( >: ) Operator if-else statement
1. Ternary operator can give only one 1.If statement is flexible and can have
value more than one statement in a block.
ii. This operator is more concise, clean ii. if in its nested form is also not so
and compact but in its nested form it is complex.
more complex.

Exercise on Conditional statements and switch statement


i) Give the output of the following : i) a= 1 ii) a=2 iii) a=3 iv)a=4
{ int a;
switch(a)
{ case 1:
System.out.println("Good");
case 2:
System.out.println("Super");
break;
case 3:
System.out.println("Excellent");
default:
System.out.println("Bad");
}}
a) Give only conditional statement for each of the following statement.
i) Check if the value of a = 5 b=5
ii) Check if the value of a is equal to any one of these 5 7 8
iii) Check if the character ch is equal to capital A a
iv) Check if the string S is equal to any of the following : "AAA" "BBB"
"CCC"
v) Check if n is equal to any of the single digit even numbers.
19
b) Give the output of the following program if a=5 b=7 and c=8
{ int a=5,b=7,c=8;
if(a>b)
{ if(a>c)
System.out.println(a);
}
else if(b>c)
System.out.println(b);
else
System.out.println(c);
}
c) Convert the following if statement to ternary operator
i) { if(a>b)
System.out.println(a);
else
System.out.println(b);
}
------------------------------------------------
ii) { if(b>=10000)
c=5/100*b;
else
c=7/100*b;
}
----------------------------------------------
d) Convert the following if-else statement to 2 separate if statements

i) if( a>=10 && a<=100)


System.out.println("Double Digit Number");
else
System.out.println("Not a Double Digit Number");
--------------------------------------------
e) Convert the following switch-case to if statement with logical operator
{ int a;
switch(a)
{case 1:
System.out.println("Good");
break;
case 2:
System.out.println("Good");
break;
20
default:
System.out.println("Bad");
}}
--------------------------------------------------------------------

Assignments to be done in Practical Record

Question 1
Create a class named Shop which offers discount on the purchase made based on the
following condition:
Purchase Amount Discount
<=5,000 10% on the purchase amount
>5,000 & <=12,000 12% on the purchase amount
>12,000 18% on the purchase amount

Write a program to accept Bill number(bno), Name (n), Amount purchase (ap). The
program should calculate the discount based on the amount purchased and and also
calculate amount paid and print the result in the given format:
Bill Number Name Purchased amount Discount Amount paid
-------- ---- --------- ---- ---

Question 2
Define a class taximeter to accept int taxino – to store taxi number String name – to store
passenger’s name
int km – to store number of kilometer travelled
Calculate bill for a customer according to given conditions
Kilometers travelled(km) Rate/km
≤1 km Rs.2
>1 km ≤ 6 Rs. 5
>6 km ≤ 12 Rs. 7
>12 km ≤ 18 Rs.9
>18 km Rs. 10
Display the details in the following format:
Taxino Name Kilometers travelled Bill amount
- - - -
Question 3
Define a class to accept employee number, name and their basic salary. Calculate bonus
based on the following condition:

Basic Salary Bonus


21
<=50,000 10% of Basic salary
>50000 and <1,00,000 20% of Basic salary
>1,00,000 30% of Basic salary

Print the result in the following format:


Employee number---- Name ----
Basic Salary --- Bonus --------
Question 4 (2013)
Define a class named FruitJuice to accept
Int p_code : stores the product code number
String flav : store the flavor of the juice
String p_type: stores the type of packing(eg. Tetra-pacl, PET bottle, etc)
Int pack_size : stores package size(eg. 200ml, 400ml, etc)
Int p_price : stores the price of the product
Int qty : to store quantity (no. of packs)
Calculate discount based on the following conditions and return it.
No. of packs Discount on total cost
≤ 50 Nil
≤ 100 2% on the total cost
≤ 300 Rs. 200 + 3% of total cost of packs greater than 100
≤ 500 Rs. 500 + 4% of total cost of packs greater than 500
else Rs. 700 + 5% of total cost of packs greater than 500

Print all the details


Note: totalcost = qty * p_price
---------------------------------------------------------
Question 3
Write a program to accept the age, gender(male or female) and taxable income of a person.
If the age is more than 65 years or gender is female, display “ Wrong Category”. If the age
is less than 65 and the gender is male then compute and display the income tax based on the
following conditions.
Given below is a hypothetical table showing rates of Income tax for male citizens below
the age group of 65 years:
Taxable Income (TI) in Rs. Income Tax in Rs.
Does not exceed Rs. 1,60,000 Nil
Is greater than Rs.1,60,000 less than or (ti – 1,60,000) x 10 %
equal to Rs. 5,00,000
Is greater than Rs. 5,00,000 and less ((TI – 5,00,000)x20%)+34,000
than or equal to Rs. 8,00,000
Is greater than Rs. 8,00,000 ((TI-8,00,000)x30%)+94,000
Question 5
22
Write a program to accept roll number, name, class, section, marks in English, Math and
Computers. Find the total and average. Based on the average print the result according to
the given table.
Average Result
>=80 “Distinction”
>=60 “I class”
>=40 “II Class”
Else “Fail”

Question 6
Create a class named Shop which offers discount on the purchase made based on the
following condition:
Purchase Amount Discount
<=5,000 10%
>5,000 & <=12,000 Previous discount + 6% on the amount
>5,000
>12,000 Previous discounts + 8% on the amount
>12,000

Write a program to accept Bill number(bno), Name (n), Amount purchase (ap). The
program should calculate the discount based on the amount purchased and print the result in
the given format:
Bill Number Name Purchased amount Discount
-------- ---- --------- ----
Question 7
Write a menu driven program with the following options:
1. Area of Rectangle
2. Area of Circle
3. Perimeter of a Square

23
WORKSHEETS ON CONDITIONAL STATEMENT AND ITERATION

Question 1

Write a program to accept roll number, name, class, section, marks in English, Math
and Computers. Find the total and average. Based on the average print the result
according to the given table.

Average Result
>=80 “Distinction”
>=60 “I class”
>=40 “II Class”
Else “Fail”

Question 2

Create a class named Shop which offers discount on the purchase made based on
the following condition:
Purchase Amount Discount
<=5,000 10% on the purchase amount
>5,000 & <=12,000 12% on the purchase amount
>12,000 18% on the purchase amount

Write a program to accept Bill number(bno), Name (n), Amount purchase (ap). The
program should calculate the discount based on the amount purchased and and also
calculate amount paid and print the result in the given format:
Bill Number Name Purchased amount Discount Amount paid
-------- ---- --------- ---- ----
-------------------------------------------------------------------------------------------------------------

Question 3

Write a program to generate a random number between 1 to 100 using the built-in
Math function. Give the user 10 chances to guess the number. If the number guessed
by the user is greater than the number the computer has generated then print the
message “Think of a smaller number”. If the number guessed by the user is lesser than
the number the computer has generated then print the message “ Think of a bigger
number”. If the number the computer has generated is same as the on guessed by the
user then print the message that “you have guessed the correct number” and print
the number of chances they have taken to guess the number and exit the program. If
30
the user fails to guess the number if 10 chances then print the number generated by
the computer and exit the program.

-------------------------------------------------------------------------------------------------------------

Question 4

Write a program to generate a quiz. Choose any 5 questions with four choices. Display
each question with the choice(1/2/3/4). Accept the answer ( ie. Choice). If the answer
is correct add 5 marks to each question. At the end print the total score.

Question 5

Write a menu driven program depending on the user’s choice for the following:

1. Area of square
2. Area of rectangle
3. Area of Triangle

If the user enters a wrong choice print the message “Wrong choice”

---------------------------------------------------------------------------------------------------------------

Question 6

Write a menu driven program to accept principal(p), time (t) and rate(r) and calculate
simple interest.

i. Repeat the whole process 5 times


ii. Repeat the whole process n times
iii. Repeat the whole process as long as the user wants
iv. Repeat the whole process until the value of principal is 0

----------------------------------------------------------------------------------------------------------------

Question 7

There are different 100 coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour as char data type (R-Red G-Green B-Blue W-White) and
do the job of sorting the beads and print the number of beads of each colour.

----------------------------------------------------------------------------------------------------------------
31
Question 8

There are different n coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour as char data type (R-Red G-Green B-Blue W-White) and do
the job of sorting the beads and print the number of beads of each colour.
----------------------------------------------------------------------------------------------------------

Question 9

There are different coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour a colour as char datatype (R-Red G-Green B-Blue W-
White) and do the job of sorting the beads and print the number of beads of each
colour.
---------------------------------------------------------------------------------------------------------

Question 10

There are different coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour as char datatype (R-Red G-Green B-Blue W-White) and do
the job of sorting the beads and print the number of beads of each colour. The
program should stop when the last colour entered is ‘0’.

32
CHAPTER 6
CHARACTER SET OF JAVA
The character set used in java is Unicode character set. This Unicode is a 16-bit
character coding system and currently supports more than 34,000 defined characters derived
from 24 languages all over the world. The first 128 characters in Unicode character set are
identical to ASCII character set.

The set of valid characters in Java comprises of:


Letters : A-Z or a-z
Digits : 0-9
Arithmetic operator : + -/*%
Relational operators : > < >= <= != ==
Special symbol : space, {, } [ ] etc

TOKENS OF JAVA
Tokens are the smallest elements/unit of the Java Program. There are 5 types of
tokens. They are
1. Reserved words
2. Identifiers
3. Literals
4. Separators
5. Operators

1.Reserved WordsReserved words are also called Keywords. They have specific meaning
in Java and cannot be used as names for variables, classes, and methods. All keywords
37
are written in lower case letters. Since java is case sensitive, one can use these words as
identifiers by changing one or more letters to upper case.

2.Identifiers
They are programmer-defined tokens. They are names of the classes,
methods, variables, objects in a program.
Java identifiers follow the following rules:
 They should begin with an alphabet, or an underscore or dollar sign characters.
 They can be followed by an alphabet or underscore or a digit.
 Uppercase and lowercase letters are distinct
 They can be of any length
 They must not be a boolean literal( true/ false) , keyword, or null literal.

Note : Identifiers must be meaningful, short enough to be quickly and easily typed and
long enough to be descriptive and easily read. Java developers have some naming
conventions.
 Names of all public methods and instance variables start with a leading lowercase
letter.
eg. total
 When more than one word is used in a name, the second and subsequent words are
marked with a leading uppercase letters.
eg. simpleInterest
 All private and local variables use only lowercase letters combined with underscores.
eg. sales_commission
 All classes start with a leading upper case letter
eg. Student
 Variables that represent constant values use all uppercase letters and underscores
between words.
eg. MAX_VALUE

1) Classify the following a valid or invalid identifier


i) %as ii) _De34 iii) Simple Interest iv)goto iv)break v) Data_rec

3.Literals
Literals (often referred as a constant) are data items that have fixed data
values.
Java allows several kids of literals. They are:
 Integer literals
 Floating literals
 Character literals

38
 String literals
 boolean literals
 null literal

Integer Literals are whole numbers without any fractional part. Eg. 453, -53556
Rules for Integer literals
 An integer constant must have at least one digit and must not contain any decimal
point.
 It may contain either + or – sign.
 A number with no sign is assumed to be a positive number.
 Comma cannot appear in integer constant.

Floating Literal: They are also called as real literal. They are numbers having fractional
parts. They can be expressed in 2 forms. They are:
 Fractional form eg : 134.65
 Exponent Form eg : 13465E2
Boolean Literal can have only 2 values true or false.

Character literals: A character literal is any character enclosed in single quotes. Eg. ‘S’ ‘3’
‘+’
Java allows nongraphic characters in character constants. Nongraphic characters are those
characters that cannot be typed directly from keyboard. Eg. backspace, tab, carriage return
etc. They can be represented by using Escape sequences. A Escape sequences is represented
by a backslash followed by one or more characters. The following are some of the escape
sequence in java.

Escape Sequence Nongraphic Character


\a Audible bell
\b Backspace
\n Newline or linefeed
\r Carriage return
\\ Backslash
\’ Single quotes
\” Double quotes
\0 Null
\t tab

Following are some of the examples of char literals:


‘a’ ‘%’ ‘\t’ ‘\\’ ‘\’

39
String Literals
A string is a sequence of zero or more characters enclosed by double quotes. Each
character may be represented by an escape sequence.
Eg. “abc” “\abc” “Ash\’s book”

The Null Literal


A null type has one value, the null reference, represented by the literal null.

4. Seperators : They are symbols to separate variables, statements or methods. The


following 9 ASCII characters are separators (punctuators).
() {} [] ; , .

5. Operators
An operator is a symbol representing an operation. It tells the computer to perform certain
mathematical or logical operation. Operators are used in program to manipulate data and
variable. The operators can be classified into 3 broad classification. They are:
UNARY OPERATOR BINARY OPERATOR TERNARY OPERATOR
It works on a single It works on two operands. It works on three operands.
operand. The binary operators are : It is a conditional operator
The unary operators in Arithmetic Operators: that
java are Increment +-*/% provides a shorter syntax
operator ++: Increments Assignment Operator for the if..then..else
the value of the operand by = statement. The ternary
1. The increment can be Logical Operator operator in java is ? :
divided into 2: NOT ! (Unary) AND && (Condition ?
Prefix Increment eg OR || Expression 1 :
:++a Relational Operator
Postfix Increment < > >= <= == != Expression 2)
eg:a++ Shorthand Operator Eg: (a>b? c=a : c=b)
Decrement operator –- : += -= *= /= %=
Decrements the value of
the operand by 1. The
decrement operator can be
divided into two types.
They are:
Prefix Decrement eg: --a
Postfix Decrement eg: a--
Logical NOT ! : eg
if(!(a>5))

40
Precedence Of Java Operators
Sl. no Operators (From Highest Precedence) Associativity
1 () [] Left to Right
2 ++ -- ! Right to Left
3 * / % Left to Right
4 + - Left to Right
5 > >= < <= Left to Right
6 == != Left to Right
7 && Left to Right
8 || Left to Right
9 ?: Right to Left
10 = += -= *= /= %= Right to Left

Answer the following


1. What is a token? Name all the tokens in Java.
2. What is a reserve word? Give another name for the same.

41
3. Classify the following as reserve words and non-reserve words
i) new ii) ans iii) Good iv) system v) Void vi) token
4. What is Identifier? Give the rules for an identifier.
5. Classify the following as valid or invalid identifier
i) 6hgf ii) Simple_int iii) _acb iv) $abc v) Ans
6. What is a literal? What are different types of literals in java.
7. Name the type of literal to which the following belong
i) 6744 ii)’A’ iii)”A” iv) 7 v) ‘7’ vi) “7” vii) 75.66 viii) false ix) “DGF”
8. What is an operator? What are the 3 major classification of operators.
9. Define the following: i) Unary operator ii) Binary operator ii) Ternary operator
10. What are the classifications of Unary operator? Name all the 3 unary operators present
in java.
11. Explain the following: i) Arithmetic operator ii) Assignment operator iii) Relational
operator iv) Logical operator v) Shorthand operator
12. What is a separator? Name all the separators present in Java.
13. Differentiate the following: i) = and == ii) ++ and -- iii) s=++a and s=a++ iv) !
and != v) && and || vi) Unary operator and Binary operator
14. Classify the following as unary and binary operator and also name the type of
operator.
i) + ii)++ iii) -= iv) *= v) = vi) != vii) % viii) > ix) ! x) –
16. Evaluate the following based on the precedence of the operator if initial value of
a=3b=2c=5
i) 400 / 3 + 6 * 8 /2 - 4 ii) 400 /3.0 + 6 * 8 / 3 – 6
iii) 30- 45 > 50 ? 60 :90 iv) 45 > 60 && 60 <70 || 30 == 50
v) ++a + b++ * c-- + --a + --b vi) a+= ++a + ++b * c-- + --a
17. Name the reserve word, literal, identifier, operator and separators
i) int a = 56; ii) if( a > 50) { s= 70};

42
CHAPTER 7
DATA TYPES
Data Types are means to identify the type of data and associated operations to handling it. Data types can be
classified into 2 types. They are:
1. Primitive data type
2. Non-primitive (Referenced) Data type

Primitive Data Type comes as a part of java compiler. Primitive data type can be classified into 2
types. They are :
1) Numeric data type
2) Non-numeric data type or Reference data type

Numeric Data type: They are used to store numeric literals (constants). They are further divided into 2
parts. They are:
 Integer data type : The integer data type in java are – byte, short, int and long
 Floating-point data type : The floating data type in java are – float, double
Non-numeric Data type : They are used to store character literals. They are further divided into 2. They
are :
 Character data type : The character data type in java is – char
 Boolean data type : The Boolean data type to store Boolean literals is – Boolean

Referenced Data Type: are constructed from primitive data type. These are objects, arrays and interface. A
reference datatype is used to store the memory address of an object. These variables used to store memory address
is known as reference variables and their datatype is called as a reference data type.

Data Type Size Range Description Default Values


Byte 8 bits (1 byte) -128 to +127 Byte-length Integer 0b
Short 16 bits( 2 - 32, 768 to 32, 767 Short Integer 0s
bytes)
Int 32 bytes (4 -231 to 231 -1 Integer 0
bytes)
Long 64 bits (8 -263 to 263 -1 Long Integer 0L
bytes)
float 32 bits (4 -.3.4E+38 to Single Precision floating 0.0f
bytes) 3.4E+38 point
Double 64 bits (8 -1.7E+308 to Double precision floating 0.0
bytes) 1.7E+308 point
char 16 bits ( 2 0 to 65,536 Unicode characters '\u0000'
bytes)
boolean 8 bits but uses True or false Used as flag variable false
only1bit

42
Primitive Data Types Reference Data Type
1. These are basic or fundamental data 1. These are constructed from
types supported by java. primitive data types by the user.
2. These primitive data type variable store 2. The reference data type variable
the actual value and their operations deals store the address or the reference of
with rvalue. eg. int, double, char. the memory location of the actual
data. eg. arrays, classes
3. Use of new operator is not required. 3. Use of new operator is required.
4. The size of these data type are fixed 4. the size of this data types are not
fixed as it depends on the data
member
5.They are available in all part of the 5. Their availability depends on their
program scope

43
int a = 50;
double b = 77.77;
char ch = ‘\U0000’
String s = “XYZ”
char z = ‘T’;

Data types
Literals/ constant
Identifiers

44
CHAPTER 8
JAVA EXPRESSION
An Arithmetic expression is a combination of variables, constants and operators
arranged as per the syntax of language.
Eg: a+b-c*d/t%2

Rules for an arithmetic expression


 It may contain just one numeric variable or constant
 It may have more than 2 variables or constants.
 Two or more expressions joined by valid arithmetic operators
 Two or more variables or operators should not occur in continuation

Evaluation Of Expression
Expressions are evaluated using an assignment statement of the form
Variable = expression
Variable is a valid java variable name. The expression is evaluated and the result is
replaced with the previous value of the variable.
Precedence Of Arithmetic operators
An arithmetic expression without any parentheses will be evaluated from left to right using
the rules of precedence of operators.
Type of Expression
Java expression can be divided into 2 types. They are:
1. Pure Expression
2. Impure expression

1.Pure Expression
In a pure expression all the operands are of same data type. Pure expression can be
broadly divided into 2 types. They are:
 Pure Integer Expression
 Pure Real Expression

Pure Integer Expression : They are formed by connecting integer constants and / or
integer variables arithmetic operators.
Eg. int a,b,c
i) c=a+b ii) c=a+40

Pure Real Expression : : They are formed by connecting real constants and / or real
variables arithmetic operators. (note : % is not real arithmetic operator)
Eg. double a,b,c;
i) c = a/b ii)c=a+b*3.5

44
2. Impure Expression
In impure expression the operands are of mixed data type. In a impure expression one
data type is converted into another data type.
The process of converting one pre-defined type to another is called Type conversion.
There are 2 types of type conversion. They are :
 Implicit type conversion or Automatic type conversion or coercion
 Explicit type conversion
Automatic Type Conversion or Implicit type conversion or coercion
It is performed by the compiler automatically when there are mixing of constants
and variables of different types in an expression. But during evaluation it adheres to very
strict rules of type conversion. We know that computer considers one operator at a time,
involving two operands. If the operands are of different types, then the ‘lower’ type is
automatically converted (promoted) to ‘higher’ type. If byte, short and int variables are
used in an expression, the result is always promoted to int type to avoid overflow. If a long
datatype is used in an expression, the whole expressions promoted to long. Remember all
int are considered to be integers unless they have l or L appended to it. If an expression
contains a float datatype operand, the entire expression is promoted to float. If any operand
is double, result is double.

However, for the following are to be noted during the assignment:


1. float to int causes truncation of factional part.
2. double to float causes rounding of digits
3. long to int causes dropping of excess higher order bits.

Type Casting a Value or Explicit type conversion


There are instances when the user forces type conversion to a specific data type.
Such conversions are called Explicit type conversion.
For eg. c = a/b;
If a and b are of int type and division results in a decimal value the decimal value will
be lost. So, converting one of the variable to float will solve the problem.
For eg. c=(float)a/b;

Example Action
x=(int)7.5 7.5 is converted to integer by truncation
a=(int)21.3/(int)4.5 Evaluated as 21/4 and the result would be 5
b=(double)sum/n Division is done in floating point mode.
y=(int) (a+b) The result of a+b is converted to integers.
Z=(int)a+b a is converted to integer and then added to b.

45
Pure expression Impure Expression
In pure expressions all the operands are of In Impure expressions all the operands are
same data types. of different data types.
Eg, int a,b,c; Eg. int a; double b; long c;
c = a+b; b = a + c;

Implicit type Conversion Explicit type Conversion


 It is performed by java compiler  It is performed by the user

 Here the smaller data types are  Here the data types are promoted to
promoted to higher data types by the the required data type by the user
java compiler. This is also called explicitly.It is also called Type
coercion. Casting.

46
Class Work
i) Define Expression. What are the two main categories of expression?
ii) What are the classifications of impure expression? Define each with an example.
iii) What is type casting or type conversion?
iv) What data type will the following expression give?
i) int + float + double ii) char + int iii) String + char iv) int + String v) char +
char
vi) 34.6 + ‘A’ vii) false + “ABC” viii) false + ‘D’
v) float a = 4.5 + 50 *2; What type of conversion is performed in the given statement
and what value is store in the variable?
vi) int a = (int) 40/3; What type of conversion is performed in the given statement and
what value is store in the variable?
vii) Classify the following as pure and impure expression.
a) int + char b) char + float c) int + int d) float + float

47
CHAPTER 3
CLASS MATH
The Math class contains all the floating-point functions that are used for geometry and trigonometry.
Math defines 2 double constants: E(approximately 2.72) and PI(approximately 3.14). It is present in the
default package java.lang.
Trignometric functions
Sl.no Method Syntax Description
1 double = Math.sin(double) Returns the sine of the angle specified by arg in radians
2 double = Math.cos(double) Returns the cosine of the angle specified by arg in radians
3 double = Math.tan(double) Returns the tangent of the angle specified by arg in radians

Exponential Functions
Sl.no Method Syntax Description
2 double=Math.log(double) Returns natural logarithm of the argument
3 double=Math.pow(double y,double x) Returns y raise to x
4 double=Math.sqrt(double ) Returns the square root of the positive argument
5. double=Math.cbrt(double) Returns the cube root of a positive or negative
argument. Eg. 3  8 =-2

Rounding Functions
Sl Method Syntax Description
no
1 int=Math.abs(int) Returns the absolute value of argument
2 long=Math.abs(long) Returns the absolute value of argument
3 float=Math.abs(float) Returns the absolute value of argument
4 double=Math.abs(double) Returns the absolute value of argument
5 double=Math.ceil(double) Returns the next highest whole number greater then or equal to
argument
6 double=Math.floor(double) Returns the lowest whole number less than or equal to
argument
7 int=Math.max(int x, int y) Returns the maximum of x and y
8 long=Math.max(long x, long y) Returns the maximum of x and y
9 float=Math.max(float x, float y) Returns the maximum of x and y
10 double=Math.max(double x, Returns the maximum of x and y
double y)
11 int =Math.min(int x,int y) Returns the minimum of x and y
12 long =Math.min(long x,long y) Returns the minimum of x and y
13 float =Math.min(float x,float y) Returns the minimum of x and y
14 double =Math.min(double x, Returns the minimum of x and y
double y)
15 int=Math.round(float) Returns arg rounded upto the nearest int
16 long=Math.round(double) Returns arg rounded upto the nearest long
17 double=Math.random() Returns a pseduorandom number between 0and 1
18 double=Math.rint( double) Returns double value to the nearest argument

52
Difference between rint() and round()
round() rint()
 It returns an int or long value  It returns a double value
i)long r =Math.round(8.7); double r =Math.rint(8.7);
Output : 9 Output : 9.0
ii)int r =Math.round(8.7f );
Output : 9
 When the argument is exactly  When the argument is exactly
halfway between two integers it halfway between two integers it
rounds up in the normal way. rounds to an even integer.
i)long r =Math.round(8.5);
Output : 9 double r =Math.rint(8.5);
Output :8.0
ii)int r =Math.round(8.5f );
Output : 9

Program 1
// Example on trigonometric function
class math
{
public static void main(String args[])
{
double sin,cos,num,num1,rad;
num=30;
// All trigonometric functions works on radians. So the angle should be converted to radians
rad = num/180.0*Math.PI;
System.out.println("radians ="+ rad);

// To find sin of angle 30 as radians


sin=Math.sin(rad);
System.out.println("sine of 30 "+sin);
// To get back the angle
rad= Math.asin(sin);
System.out.println("Radians ="+ rad);
}}
Output:
radians =0.5235987755982988
sine of 30 0.49999999999999994
Radians =0.5235987755982988
----------------------------------------------------------------------------------
// Program 2
// Example program on log, pow, abs, max and min
class math
{
public static void main(String args[])
{

53
double log,pow, absfloat,absdouble,maxdou,mindou;
int absint, maxint,minint;
long abslong,maxlong,minlong;
float maxflo,minflo;
// To find logarithm of 4.222
log = Math.log(4.22);
System.out.println("Logarithm of 4.22 = "+ log);

// To find 3 to the power of 6


pow= Math.pow(3.0,6.0);
System.out.println("3 to the power of 6 = "+ pow);

// To find absolute value of an integer


absint = Math.abs(-56);
System.out.println("Absolute value of -56 = "+ absint);

// To find absolute value of a long


abslong = Math.abs(-56987669);
System.out.println("Absolute value of -56987669 = "+ abslong);

// To find absolute value of a float


absfloat = Math.abs(-56.987669f);
System.out.println("Absolute value of -56.987669f = "+ absfloat);

// To find absolute value of a double


absdouble = Math.abs(-56.987669f);
System.out.println("Absolute value of -56.987669 = "+ absdouble);

// To find maximum of 2 integers


maxint = Math.max(50,45);
System.out.println("Maximum of 2 integers = "+ maxint);

// To find maximum of 2 long integers


maxlong = Math.max(507889,844459990);
System.out.println("Maximum of 2 long integers = "+ maxlong);

// To find maximum of 2 float point numbers


maxflo = Math.max(50.77f,34.457f);
System.out.println("Maximum of 2 floating point numbers = "+ maxflo);

// // To find maximum of 2 double numbers


maxdou = Math.max(50.77,34.457);
System.out.println("Maximum of 2 double numbers = "+ maxdou);

// To find minimum 2 integers


minint = Math.min(50,45);
System.out.println("Minimum of 2 integers = "+ minint);

54
// To find minimum of 2 long integers
minlong = Math.min(507889,844459990);
System.out.println("Minimum of 2 long integers = "+ minlong);

// To find minimum of 2 float point numbers


minflo = Math.min(50.77f,34.457f);
System.out.println("Minimum of 2 floating point numbers = "+ minflo);

// // To find minimum of 2 double numbers


mindou = Math.min(50.77,34.457);
System.out.println("Minimum of 2 double numbers = "+ mindou);
}}
Output:
Logarithm of 4.22 = 1.4398351280479205
3 to the power of 6 = 729.0
Absolute value of -56 = 56
Absolute value of -56987669 = 56987669
Absolute value of -56.987669f = 56.9876708984375
Absolute value of -56.987669 = 56.9876708984375
Maximum of 2 integers = 50
Maximum of 2 long integers = 844459990
Maximum of 2 floating point numbers = 50.77
Maximum of 2 double numbers = 50.77
Minimum of 2 integers = 45
Minimum of 2 long integers = 507889
Minimum of 2 floating point numbers = 34.457
Minimum of 2 double numbers = 34.457
-----------------------------------------------------------------------------------------------
// Program 3
// Example program on floor, ceil,round, random
class math
{
public static void main(String args[])
{
double floor,floor1, ceil,ceil1,roundint,roundlong,random;

floor = Math.floor(5.6);
System.out.println("Floor of 5.6 = "+ floor);

ceil = Math.ceil(5.6);
System.out.println("Ceil of 5.6 = "+ ceil);

floor1 = Math.floor(-5.6);
System.out.println("Floor of -5.6 = "+ floor1);

ceil1 = Math.ceil(-5.6);

55
System.out.println("Ceil of -5.6 = "+ ceil1);

// Round of a float gives an integer


roundint = Math.round(65.7766f);
System.out.println("Round of a float = "+ roundint);

// Round of a double gives a long


roundlong = Math.round(65.7766656666);
System.out.println("Round of a double = "+ roundlong);

// To generate a random number


random = Math.random();
System.out.println("Random number = "+ random);
}}
Output:
Floor of 5.6 = 5.0
Ceil of 5.6 = 6.0
Floor of -5.6 = -6.0
Ceil of -5.6 = -5.0
Round of a float = 66.0
Round of a double = 66.0
Random number = 0.9671914399866155

56
CHAPTET 5
ERRORS IN COMPUTER PROGRAMMING
Bug is an error in a program. Removing an error is called debugging.
Programming errors can broadly be divided into 3. They are :
 Compile-time errors : These are the errors resulting out of
violation of programming language’s grammar rule. They are also
called Syntax error. They are reported during compilation time.
Eg. for(i=0, i<5, i++).

 Logical Error: The error in the logic of the program is called


logical error. The program will compile in case of logical error but
the output is incorrect. Logical error is difficult to debug.
eg. If the program is to print numbers from 1 to 100, the for loop
given as below would result in logical error. for(i=100;i>=1;i--)

 Run-time Error: This error occurs during program execution and


results in abnormal termination of the program. Some of the run-
time errors are:
*Divisible by zero (which occurs when a number is divided by
zero)
*Array index out of bounds
*Arithmetical errors like square root of negative numbers
*Range error
Runtime errors are handled through Exception

57
CHAPTER 4
ITERATION / LOOPING STATEMENTS

The Iterations are also called as Loop or Looping statements. The loops are used when we need to
repeat the statements. Java provides 3 kinds of looping statements: for loop, while loop and do-while
loop.
Elements that control a Loop:
 Initialization : The control variable must be initialized before entering the loop. This
statement(s) is executed only once, before the loop begins.
 Test Expression (condition): the test expression decides whether the loop-body will be
executed or not. If the condition is true then the loop is executed else the loop is terminated.
 Update Expression(s): The update expression(s) change the value(s) of the loop variable(s)
 Body-of-Loop: The statement that are executed repeatedly forms the body of the loop.

Program to print XYZ 5 times using different loops


while loop do-while for loop
class Loop1 class Loop1 class Loop1
{ public void main() { public void main() { public void main()
{int c; {int c; {int c;
Initialization Initialization
c=1; n c=1; for(c=1;c<=5;c=c+1)
while(c<=5) do Condition
Condition
{ { {System.out.println("XYZ");
System.out.println("XYZ"); System.out.println("XYZ"); }
c=c+1; Increment c=c+1; }}
} }while(c<=5); Increment
}} }}

While loop
Program to print XYZ 5 times
class Loop1
{ public void main()
{int c;
c=1;
while(c<=5)
{
System.out.println("XYZ");
c= c +1;
}
}}
Output
XYZ
XYZ
XYZ
XYZ
XYZ
Working/dry run: c =1
Slno while(c<=5) System.out.println(“XYZ”) C=C+1
1 while(1<=5) true XYZ 2=1+1
2 while(2<=5) true XYZ 3 =2+1

21
3 while(3<=5) true XYZ 4=3+1
4 while(4<-5) true XYZ 5=4+1
5 while(5<=5) true XYZ 6=5+1
6 while(6<=5) false Won’t enter the loop (control is transferred outside
the loop

Explanation : Initially c takes the value 1 then it checks for the condition i.e is c <= 5 and the
condition returns true. As the condition is true the control enters the body of the loop and prints
“XYZ” once. Then the control goes to c=c+1, where the value of c is incremented by 1. When the
control comes to the closing bracket the control goes back to the condition (as it is a looping
statement ) and check for the condition again. The process repeats until the condition is false. When
the condition is false the control is transferred to the statement after the loop. As there is no other
statement after the loop, program ends. As the condition is checked at the beginning of the loop while
is called Entry Control loop.

Do-while loop
Program to print XYZ 5 times
class Loop1
{ public void main()
{int c;
c=1;
do
{System.out.println("XYZ");
c=c+1;’
} while(c<=5) ;
}}
Output
XYZ
XYZ
XYZ
XYZ
XYZ
Working/Dry run c=1
lno System.out.println(“XYZ”) C=C+1 while(c<=5)
1 XYZ 2=1+1 while(2<=5) true
2 XYZ 3 =2+1 while(3<=5) true
3 XYZ 4=3+1 while(4<=5) true
4 XYZ 5=4+1 while(5<=5) true
5 XYZ 6=5+1 while(6<=5) false

Explanation : Initially c takes the value 1 then it prints “XYZ” once. Then the control goes to c=c+1,
where the value of c is incremented by 1. Then it checks for the condition i.e is i<=5 and the condition
returns true. As the condition is true the control enters the body of the loop again. The process repeats
until the condition is false. When the condition is false the control is transferred to the statement after
the loop. As there are no other statements after the loop the program ends. As the condition is checked
at the end of the loop do-while is called Exit Control loop.

22
for Loop- Fixed Number Of Iterations
It works as Entry control loop.
In for loop all the elements(initial value ; test expression; update expression) of the loop are in
one statement.
Syntax
for(initial value ; test expression; update expression)
{
…………..
…………..
}

Program to print “XYZ” 5 times


class Loop1
{ public void main()
{int c;
for( c=1 ; c<=5 ; c=c+1)
{
System.out.println("XYZ");

}
}}
Output
XYZ
XYZ
XYZ
XYZ
XYZ

Explanation :
c=1 (Initialization expression) c<=10 (test expression) c=c+1 (update expression)
1. Firstly, initialization expression is executed ci=1) which gives the first value to the variable.
2. Then, the test expression is evaluated (c<=10) which results true
3. since the test expression is true, the body of the loop is executed which prints the current value
of c.
4. The update expression (c=c+1) is executed which increments the value ofci (c becomes 2).
5. test expression is again evaluated. If it is true the sequence is repeated from step 3 , else the
loop terminate.

The for loop variations


In for loop, initialization expression, test expression and update expression are optional. You can skip
any or all of these expressions.
int i; int i=1; int i=1; int i=1; int i,k;
for(i=1;i<=5;i++) for(;i<=5;i++) for(;i<=5;) for(;;) for(i=1,k=2; i<=5 && k<=10; i++,
{ { { { if(i==5) k+=2)
i++; break; { System.out.println(+"/"+k);
} } } i++; }
}

In the above the fourth (iv) example is also called Infinite loop.

23
Entry controlled Loop Exit Controlled Loop
 While is an entry controlled loop because  Do-while is an exit controlled loop
it checks for the condition before it enters because it executes the statements in the
the loop. If the condition is satisfied then body of the loop first and then it checks
the statements in the loop is executed as for the condition. It will execute the
long as the condition is satisfied /true. statements and then checks for the
condition. Depending on the condition
 It will not execute the statements in the the loop is repeated as long as the
loop even once if the condition is false. condition is satisfied.

 It will execute the statements in the loop at


least once even if the condition is not
satisfied.

Selection Construct(if) Iteration Construct


1. In this construct a statement or a set of 1. In this construct a statement or a set of
statement is either executed or skipped statement are executed repeatedly until a test
depending on the test condition. condition becomes false.
2. Execution of a set of statements can ne only 2. Execution of a set of statements can be more
once or none. than once.

Jump Statement
This statements transfers the control from one part of the program to another part. There are 3 jump
statements in java. They are: break, continue and return
Break continue return
This statement terminates the This statement continues with This statement transfers the
loop. the next iteration in the loop control back to the calling
Eg: Eg: function.
for(int i=1;i<=5;i++) for(int i=1;i<=5;i++)
{ if(i==3) { if(i%2==0) This will be done in the
break; continue; chapter constructor and
else else methods.
system.out.println(i); system.out.println(i);
} }

Repeat Constant Times


1) // Program to print "Computer" 5 times
class count1
{ public static void main(String args[])
{ int c;
c=1;
while(c<=5)
{ System.out.println("Computer");
c=c+1;
}} }

24
// Accept a name. Print it 5 times
import java.util.*;
class count1
{ public static void main(String args[])
{ Scanner sc = new Scanner(System.in);
int c; String name;
System.out.println("Enter your name:");
name=br.nextLine();
c=1;
while(c<=5)
{ System.out.println(name);
c=c+1;
}} }

//Accept Radius and calculate area of circle. //Accept radius. Calculate area of circle.
Repeat the whole process 5 times. Repeat the whole process n times
import java.util.Scanner; import java.util.Scanner;
class test class test
{ public static void main(String args[]) { public static void main(String args[])
{ Scanner sc = new Scanner(System.in); { Scanner sc = new Scanner(System.in);
double rad, ar; double rad, ar;
int c; int c,n;
c=1; System.out.println("enter value for n");
while(c<=5) n=sc.nextInt();
{ System.out.println("Enter radius"); c=1;
rad=sc.nextDouble(); while(c<=n)
ar=Math.PI*rad*rad; { System.out.println("Enter radius");
System.out.println("area is :"+ar); rad=sc.nextDouble();
c=c+1; ar=Math.PI*rad*rad;
} System.out.println("area is :"+ar);
} c=c+1;
} }
}
}

Repeat constant Time Repeat n times


c=1; int c, n;
while(c<=5) System.out.println("”Enter value for n”);
{ n = sc.nextInt();
Statements c=1;
to repeat while(c <= n )
{
c=c+1; Statements
} to repeat
c=c+1;
}

25
//Accept Principal, time and rate. //Accept Principal, time and rate.
Calculate simple interest and print all Calculate simple interest and print all
the information in a neat format. Repeat the information in a neat format. Repeat
the whole process in a neat format. the whole process n times
import java.util.Scanner; import java.util.Scanner;
class test class test
{ public static void main(String args[]) { public static void main(String args[])
{ Scanner sc = new { Scanner sc = new
Scanner(System.in); Scanner(System.in);
double pr,t,r,si; double pr,t,r,si;
int c; int c,n;
c=1; System.out.println("Enter principal");
while(c<=5) n=sc.nextInt();
{ System.out.println("Enter c=1;
principal"); while(c<=n)
pr=sc.nextDouble(); { System.out.println("Enter
System.out.println("Enter time"); principal");
t=sc.nextDouble(); pr=sc.nextDouble();
System.out.println("Enter rate"); System.out.println("Enter time");
r=sc.nextDouble(); t=sc.nextDouble();
si=pr*t*r/100; System.out.println("Enter rate");
System.out.println("Principal is r=sc.nextDouble();
"+pr); si=pr*t*r/100;
System.out.println("Time is "+t); System.out.println("Principal is
System.out.println("Rate is "+r); "+pr);
System.out.println("simple Interest System.out.println("Time is "+t);
is :"+si); System.out.println("Rate is "+r);
c=c+1; System.out.println("simple Interest
} is :"+si);
} c=c+1;
} }
}
}

a) Write a java program to accept length and breadth. Calculate area of Rectangle. Print area of
Rectangle.
i) Repeat the whole process 7 times
ii) Repeat the whole process n times

26
b) Write a program to Create a class named “Student” to accept Roll number, name, marks in
English, maths and computers. Calculate total and average. Find the result based on the
condition:
Average Result
>=80 “Distinction”
>=60 and <80 “First Class”
>=40 and <60 “II Class”
Else “Distinction”
Print the result in the following format:
Roll number is -------- name is ------
Marks in English is ----- Maths is ----- Computers is -----
Total is ---- average is -----
Result is -------
iii) Repeat the whole process 5 times
iv) Repeat the whole process n times

c) **Accept empno, name and salary for 10 customers. If salary <=10000 then bonus = 15% of
salary. If salary>10000 and salary<30000 then bonus = 20% of salary else bonus = 30% of
salary. Print employee number, name, salary and bonus.

d) **Create a class named “Electricity” to accept Meter numbers, Name of the consumer, Previous
meter reading and the present meter reading. Calculate Units Consumed and cost based on the
following condition :
If UC <=100 then cost if 80p per unit
If UC>100 and <=200 then cost is Rs 120+60p for every unit greater then 100
If UC >200 and less then 300 then cost is Rs 230+ 50p for every unit greater than 200 else cost
is Rs.340+ 30p for every unit greater then 300
Print all the details in a neat format:
Meter Number is ----- Name is ----- Previous meter reading ----- Present meter reading -----
Units Consumed is ---- Cost is -----
Repeat the whole process n times

f) **Accept telephone number, name and number of calls. If the number of calls is less than 100 then
charges=Re1. per call. If the number of calls is >100 and <=200 then charges = plus+0.80p for calls
greater than 100 else charges =plus+1.20 for calls greater than 200. Print telephone number, name,
number of calls and charges. Repeat the process 3 times

d) **Write a program to accept name and height of a person. If the height is <=5ft then Print “You
are a short person”. If the height is >5ft and height <=5.5ft then print “Your height is medium”
else print “You are a tall person”. Repeat the whole process n times

Print the odd problems using while and even problems using do-while
1. 5 5 5 5 5
2. 1 2 3 4 5
3. 5 4 3 2 1
1 1 1 1 1
4.
1 2 3 4 5
1 1 1 1 1
5.
2 4 6 8 10

27
6. 2 4 6 8 10
3 6 9 12 15
7. 2 4 6 8 10
15 12 9 6 3
8. 1 2 3 4……n
9. 2 2 4 2 6 2 8 2 10 2
10. 1x2 2x3 3x4 4x5 5x6
11. 1+3 2+5 3+7 4+9 5+11
12. x1 x 2 x 3 x 4 x 5
13. 2x3x4 4x6x8 6x9x12 8x12x16 10x15x20
14. 1x1=1 15. 2x1=2
1x2=2 2x2 =4
. .
. .
1x10=20 2x10=20
15. Accept n and print 10 multiples of it in table form
16. Number Square Cube
1 1 1
2 4 8
. . .
. . .
n
17. Accept a number and print 10 multiples of the same in table form
18. Accept 2 number and print all the alternate number from the first number to second number
19. 0 1 1 2 3 5 8 ……….50 terms (To be done in the Practical Record)
20. 0 3 8 15 24 ……… n terms (To be done in the Practical Record)

28
Chapter 9
Nested Loops

A loop which contain another loop in its body is called Nested Loop.

for( i = 1 ; i <= 5 ; i++)


{
for( k = 1 ; k <= 5 ; k++)
{
……
}
}
Values of Outer loop and Inner loop
Outer loop i Inner loop k
1 12345
2 12345
3 12345
3 12345
4 12345
5 12345

break statement : If a break statement is used in nested loop it comes out of the inner most loop.
Similarly, if continue is used in nested loops it continues with the inner most loop. To come out of a
outer most or particular loop/ to continue with the outer most loop we use labels.
Labels : In java we can label a block or statements. A label should be a valid identifiers.
In following program the label name is outer

Ex:1 : outer: for(int i=0;i<5;i++) Ex: 2 outer:for(int i=0;i<5;i++)


{ {
for(int k=0;k<=5;k++) for(int k=0;k<=5;k++)
{ {
System.out.println(m*n); System.out.println(m*n);
if(i>2) if(i>n)
continue outer; break outer;
}} }}

Finate Loop Infinite Loop Empty Loop Nested Loop


A loop which is A loop which goes on A loop which has no A loop within
executed constant endlessly because the body is called empty another loop is
number of times is condition is not satisfied loop. It also called called nested loop.
called a finate loop. is called Infinite loop. Time Delay loop.

while(true)
{ …..

47
ASSIGNMENT ON NESTED LOOP

Write a program to print the following:


i)1 2 3 4 5 ii) 5 4 3 2 1 iii) 1 1 1 1 1 iv) 2 4 6 8 10 v)5 5 5 5 5 vi) 8 8 8 8 vii) * * * *
12345 54321 22222 2 4 6 8 10 4 4 4 4 4 6666 +++++
12345 54321 33333 2 4 6 8 10 3 3 3 3 3 4444 * ****
12345 44444 2 4 6 8 10 2 2 2 2 2 2222 +++++
*****
+++++

viii) 1 1 12 13 14 21 22 23 2 4 31 32 33 34 4 1 42 4 3 4 5

ix) 111 121 131 141 212 222 232 2 42 313 323 333 343

x) 1 1 1 1 2 1 1 3 1 1 4 1 xi) 1 2 1 1 4 1 1 6 1 1 8 1 xii) 2*2 2*2 2*2 xiii) 1 2 3


212 222 232 242 222 242 262 282 4*4 4*4 4*4 456
313 323 333 343 323 343 363 383 6*6 6*6 6*6 789
424 444 464 484 8*8 8*8 8*8
Write a program to print the following
i)1 ii) 1 2 3 4 5 iii) 5 7 9 11 iv) 17 15 13 11 v) 7
12 1234 579 15 13 11 57
123 123 57 13 11 579
1234 12 5 11 5 7 9 11
12345 1 5 7 9 11 13

vi) 4 vii) 8 vii)1 ix)7 7 7 7 7


4 6 8 10 2 2 6 6 6 6
4 6 8 8 10 12 3 3 3 5 5 5
4 6 8 10 8 10 12 14 4 4 4 4 4 4
4 6 8 10 12 8 10 12 14 16 5 5 5 5 5 3

x) 5 xi)15 15 15 15 xii) 11 xiii) 11 12 13 14


7 7 17 17 17 13 11 15 16 17
9 9 9 19 19 15 13 11 18 19
11 11 11 11 21 17 15 13 11 20

Give the output of the following program. Also, how many times is the loop k executed.
{ int i,k;
for(i=1;i<4;i++)
{ for(k=1;k<5;++k)
{
System.out.print(k+i);
}
System.out.print("\n");
}}
Find the sum of the following program
1) S=1+1+2+1+2+3+1+2+3+4+1+2+3+4+5
2) S=1+2+2+3+3+3+4+4+4+4+5+5+5+5+5

48
3) S=1+2+1+3+2+1+4+3+2+1+5+4+3+2+1
4) S=5+5+5+5+5+4+4+4+4+3+3+3+2+2+1
5) S=1+2+3+1+2+3+1+2+3+1+2+3+1+2+3
1 2 3 4 5
6) S     
1! 2! 3! 4! 5!
1 2 3 4 n
7) S     ....
1! 2! 3! 4! n!
x x2 x3 x4 xn
8) S     ........
1! 2! 3! 4! n!
1 2 3 4 n
9) S     ...........
1! 2! 3! 4! n!
1 2 3 4
x x x x xn
10) S     .......
1! 2! 3! 4! n!
Application of Nested Loops
a) Write a program to print 10 multiples of all the tables from 1 to 5.
b) Write a program to calculate simple interest for rate being constant 4.5% and principal varying
from 1000 to 10000 in steps of 1000 and time varying from 1 to 5 years. Also, print the result
in the following format:

1000 4000 6000 8000 10000


1
2
3
4
5

c) Write a program to simulate tossing of a coin 10 times; 100 times and 1000 times. Keep a
count of number of heads and tails for each of the group.
d) Three natural numbers a,b and c are said to from a Pythagorean triplet, if a 2  b 3  c 2 . Write a
program to print all the Pythagorean triplet from 1 to 50.

e) Print the following using nested loops:


1 1
1 2 3
1 2 3 6
1 2 3 4 10
1 2 3 4 5 15
f) Write a menu driven program using nested loops:
i) to print a square of side mxm filled with the char ‘+’
ii) to print a rectangle of length l and breadth b filled with any given character
g) Using the switch statement – write a menu driven program for the following : (2016)
(i) To print the Floyd’s triangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
(ii) To display the following pattern

49
I
I C
I C S
I C S E
For an incorrect option, an appropriate error message should be displayed.
***********************************************************************

50
ASSIGNMENTS ON NESTED LOOPS

1)2 4 6 8 10 2) 5 5 5 5 5 5 3) 22 20 18 16 14 4) 51 51 51 51
2 4 6 8 10 7 7 7 7 7 7 22 20 18 16 14 53 53 53 53
2 4 6 8 10 9 9 9 9 99 22 20 18 16 14 55 55 55 55
22 20 18 16 14

1)5 7 9 11 2) 8 10 12 14 3) 15 17 19 21 4) 21 23 25
5 7 9 10 12 14 17 19 21 21 23
5 7 12 14 19 21 25
5 14 21

5 5 5 5 5 12 12 12 12 8 1
7 7 7 7 14 14 14 10 10 333
9 9 9 16 16 12 12 12 55555
11 18 14 14 14 14 7 777777

* ** * * * * * * * * ** * *
* ** * * * * * * * * * ** *
* * * * * * * * * * * ** **
* * * * * * * * * *

1 2 3 12 3 4 1 15
4 5 6 3 4 5 6 2 3 14 13
7 8 9 7 8 9 10 4 5 6 12 11 10
7 8 9 10 9 8 7 6

111 121 131 111 212 313 2 1 22 23


212 222 232 121 222 323 4 1 42 43
313 323 332 131 232 333 6 1 62 63

1) S= 1+2+3+1+2+3+1+2+3
2) S= 1+2+3+6+1+2+3+6+1+2+3+6+1+2+3+6
3) S=1+1+1+3+2+2+2+6+3+3+3+9

1 2 3 4 5
1) s     
1! 2! 3! 4! 5!

x 2 x 4 x 6 x 8 x10
2) s     
2! 4! 6! 8! 10!
x 2 x 4 x 6 x 8 x10 x n
3) s      ....
2! 4! 6! 8! 10! n!

51
‘1 *
1 * 3 1 2
1 * 3 * * * *
1 * 3 * 5 1 2 3 4

1 2 3 4 5 1 *
1 2 3 1 2 3 * * *
1 1 2 3 4 5 * * * * *

*
* * *
* * * * *
* * * * * * *
* * * * *
* * *
*

**********************************************************************************

52
CHAPTER 5 ACCUMULATOR

The word Accumulate means to accumulate or add or store values or numbers.


Example to add the series 1+2+3+4+5. To do this, we need a counter which goes from 1 to
5 and an accumulator to store the values.

To find s= 1+2+3+4+5
class sum
{ public static void main(String args[])
{ int c, s;
s=0;
c=1;
while(c<=5)
{ s=s+c;
c=c+1;
}
System.out.println("Sum is "+ s);
}}

Dry run
Initial values : c= 1 s=0
Slno while(c<=5) s=s+c c=c+1
1 while(1<=5) true 1=0+1 2=1+1
2 while(2<=5) true 3=1+2 3=2+1
3 while(3<=5) true 6=3+3 4=3+1
4 while(4<=5) true 10= 6+4 5=4+1
5 while(5<=5) true 15=10+5 6=5+1

Problems on Summation
1. 1+2+3+4+5
2. 2+4+6+8+10
1 1 1 1 1
3.    
1 2 3 4 5
1 1 1 1 1
4.    
2 4 6 8 10
2 4 6 8 10
5.    
3 6 9 12 15
6. find 5!
7. Find n!
3 X !5Y !
8.
X !Y !
9. 1  2 3  34  4 5  56
2

10. x1  x 2  x 3  x 4  x 5

32
Application of Accumulator
Example 1
//Repeat constant times //Repeat variable times
// Accept 5 numbers and find their // Accept n numbers and find their sum.
sum. import java.io.*;
import java.util.*; class sum1
class sum1 { public static void main(String args[])
{ public static void main(String args[]) {Scanner sc = new
Scanner sc = new Scanner(System.in);
Scanner(System.in); int c,no,sum,n;
int c,sum; System.out.println("Enter a
sum=0; c=1; number:");
c=1; n = sc.nextInt();
while(c<=5) sum=0; c=1;
{ System.out.println("Enter a while(c<=n)
number:"); {System.out.println("Enter a
no= sc.nextInt(); number:");
sum=sum+no; no = sc.nextInt();
c=c+1; sum=sum+no;
} c=c+1;
System.out.println("The sum is }
"+sum); System.out.println("The sum is
}} "+sum);
}}

EXAMPLE 2
Repeat Constant times Repeat Variable Times
//Accept 10 numbers and find the // Accept n numbers and find the
number of positive numbers and sum number of positive numbers and
of negative numbers sum of negative numbers
import java. util.*; import java.util.*;
class acc class acc
{ public static void main(String args[]) { public static void main(String
{ Scanner sc = new args[])
Scanner(System.in); { Scanner sc = new
int num,pcou=0,nsum=0,c; Scanner(System.in);
c=1; int num,pcou=0,nsum=0,c,n;
while(c<=10) System.out.println("Enter value
{ System.out.println("Enter a for n");
number");
num=sc.nextInt(); n=Integer.parseInt(br.readLine());
if(num>0) c=1;
pcou=pcou+1; while(c<=n)
else if(num<0) { System.out.println("Enter a
33
nsum=nsum+num; number");
c=c+1; num=sc.nextInt();
} if(num>0)
System.out.println("Sum of pcou=pcou+1;
negative numbers is "+nsum+" else if(num<0)
Number of positive numbers is nsum=nsum+num;
"+pcou); c=c+1;
}} }
System.out.println("Sum of
negative numbers is "+nsum+"
Number of positive numbers is
"+pcou);
}}

a) Accept 10 numbers. Find the sum of only positive numbers. Print the sum.
b) Accept n numbers. Find the sum of only positive numbers. Print the sum

c) Accept empno, name and salary for 50 customers. If salary <=10000 then bonus =
15% of salary. If salary>10000 and salary<30000 then bonus = 20% of salary else
salary = 30% of salary. Print employee number, name, salary and bonus. Also, print
the number of employees in each category.

f) Accept Roll number , name, marks in English, Math and Computers. Calculate total and
average. Also calculate result based on the following condition :
If average is greater than equal to 80 then return the message “Distinction”
If the average is greater than equal to 60 and less then 80 then return the message
“I class”
If the average is greater than equal to 40 and less then 60 then return the message
“II class”
Then return the message “Fail”
Print the result in the following format:
Roll number is -------- name is ------
Marks in English is ----- Maths is ----- Computers is -----
Total is ---- average is -----
Result is -------
Find the number of students whose average is greater than equal to 80.

h) Write a program to determine out of n students, the number of students who have
scored greater then equal to 80, greater than equal to 60 and less then 80 and less than 60.

i) Govt. of India is interested to determine the opinion of general public about the
education policy. The response to this question is to be one of the follows:
1 - means in favour
34
2 - means in oppose
3 - means no opinion
Write a program to input the response of each persons, calculate the number of responses
of each type and print the them, assuming that n persons have were interviewed.

************************************************************

35
CHAPTER 10
MODULUS OPERATOR

Modulus operator gives the remainder of a division. eg.


8%3=2
2%8= 2
Some points to remember.
1. If the divisor is smaller than dividend then modulus operator returns the
divisor.
Eg. 67 % 78 = 67

2. n % 10 always gives the last digit of n.


eg: 567 % 10 = 7
Similarly, n % 100 gives the last 2 digit of the number n. eg. 4532 % 100 = 32
Similarly, n%1000 gives the last 3 digits of the number n. eg. 4532 % 1000 =
532

4. n=n / 10 eliminates the last digit of the number.


eg. 456 / 10 = 45. As both 456 and 10 are integers and integer division results
in an integer.
// To print one digit per line in // To count the number of // To sum all the digits
reverse order digits
import java.util.Scanner; import java.util.Scanner; import java.util.Scanner;
class mod1 class mod1 class mod1
{ public static void main(String { public static void main(String { public static void main(String
args[]) args[]) args[])
{ int no, r; { int no, r,c; { int no, r,s;
Scanner Sc=new Scanner Sc=new Scanner Sc=new
Scanner(System.in); Scanner(System.in); Scanner(System.in);
System.out.println("Enter System.out.println("Enter System.out.println("Enter
a number"); a number"); a number");
no=Sc.nextInt(); no=Sc.nextInt(); no=Sc.nextInt();
while(no!=0) c=0; s=0;
{r=no%10; while(no!=0) while(no!=0)
System.out.println(r); {r=no%10; {r=no%10;
no=no/10; c=c+1; s=s+r;
} no=no/10; no=no/10;
}} } }
System.out.println("The System.out.println("The
count is "+c); sum is "+s);
}} }}

Application of Sum of digits – Armstrong number eg: 153 = 13 +5 3+33


import java.util.Scanner;
class mod1

53
{ public static void main(String args[])
{ int no,no1, r,s;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
no=Sc.nextInt();
no1=no; // To copy the original number
s=0;
while(no!=0)
{r=no%10;
s=s+r*r*r;
no=no/10;
}
if(no1==s)
System.out.println(no1+"It is an Armstrong number ");
else
System.out.println(no1+"It is not an Armstrong number ");
}}

To reverse a number eg: n=123 reverse number of n = 321


import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int no,no1, r,rn;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
no=Sc.nextInt();
no1=no; // To copy the original number
rn=0;
while(no!=0)
{r=no%10;
rn=rn*10+r;
no=no/10;
}
System.out.println("Reverse of "+ no1+" is "+ rn);
}}

Application of reverse number- Palindrome number eg: 12321 is a Palindrome


import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int no,no1, r,rn;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
no=Sc.nextInt();
no1=no; // To copy the original number
rn=0;
while(no!=0)
{r=no%10;
rn=rn*10+r;
no=no/10;
54
}
if(rn==no1)
System.out.println(no1+ " is a Plindrome Number ");
else
System.out.println(no1+ " is not a Plindrome Number ");
}}

Application of Reverse number – Print each digit in words


import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int no,no1, r,rn;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
no=Sc.nextInt();
no1=no; // To copy the original number
rn=0;// reverse the number
while(no!=0)
{r=no%10;
rn=rn*10+r;
no=no/10;
}
// Extract each digit in the number and print it
while(rn!=0)
{ r=rn%10;
switch(r)
{case 0:
System.out.print(" Zero ");
break;
case 1:
System.out.print(" One ");
break;
case 2:
System.out.print(" Two ");
break;
case 3:
System.out.print(" Three ");
break;
case 4:
System.out.print(" Four ");
break;
case 5:
System.out.print(" Five ");
break;
case 6:
System.out.print(" Six ");
break;
case 7:
System.out.print(" Seven ");
break;
55
case 8:
System.out.print(" Eignt ");
break;
case 9:
System.out.print(" Nine ");
break;
}
rn=rn/10;
}
}}

//To print all factors of a // To count number of factors // To add all the factors
number
import java.util.Scanner; import java.util.Scanner; import java.util.Scanner;
class mod1 class mod1 class mod1
{ public static void main(String { public static void main(String { public static void main(String
args[]) args[]) args[])
{ int no,i; { int no,i,c; { int no,i,s;
Scanner Sc=new Scanner Sc=new Scanner Sc=new
Scanner(System.in); Scanner(System.in); Scanner(System.in);
System.out.println("Enter System.out.println("Enter System.out.println("Enter
a number"); a number"); a number");
no=Sc.nextInt(); no=Sc.nextInt(); no=Sc.nextInt();
for(i=1;i<=no;i++) c=0; s=0;
{if(no%i==0) for(i=1;i<=no;i++) for(i=1;i<=no;i++)
System.out.println(i); {if(no%i==0) {if(no%i==0)
} c=c+1; s=s+i;
}} } }
System.out.println("Sum of
System.out.println("Number of all the factors is "+s);
factors are "+c); }}
}}

// Application of Count the number of factors – Prime Numbers


import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int no,i,c;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
no=Sc.nextInt();
c=0;
for(i=1;i<=no;i++)
{if(no%i==0)
c=c+1;
}
if(c==2)
System.out.println(no+" is a prime number");
else
56
System.out.println(no+" is not a prime number");
}}

// Application of Prime number + Nested loop – To print all prime numbers from 1 to 100
import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int no,i,c;
Scanner Sc=new Scanner(System.in);
for(no=1;no<=100;no++)
{ c=0;
for(i=1;i<=no;i++)
{if(no%i==0)
c=c+1;
}
if(c==2)
System.out.println(no+" is a prime number");
}
}}

// Application of prime numbers – Twin Prime 3 and 5 (both are prime numbers and the
difference between them is two)
import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int no1,no2,i,c1,c2;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
no1=Sc.nextInt();
System.out.println("Enter a number");
no2=Sc.nextInt();
c1=0;
for(i=1;i<=no1;i++)// count the factors of no1
{if(no1%i==0)
c1=c1+1;
}
c2=0;
for(i=1;i<=no2;i++)// count the factors of no2
{if(no2%i==0)
c2=c2+1;
}
if(c1==2 && c2==2 && Math.abs(no1-no2) == 2)
System.out.println(no1+" and "+ no2+" are twin prime ");
else
System.out.println(no1+" and "+ no2+" not are twin prime ");
}}

// Application of Sum of Factors – Perfect Number : eg: 6 = 1+2+3=6 Sum of factors other than the
number is equal to the given number
import java.util.Scanner;
57
class mod1
{ public static void main(String args[])
{ int no,s,i;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
no=Sc.nextInt();
s=0;
for(i=1;i<no;i++) // sum of factors other than the number
{if(no%i==0)
s=s+i;
}
if(s==no)
System.out.println(no+" is a Perferct number ");
else
System.out.println(no+" is not a Perferct number ");
}}

// Application of sum of factors – Amicable Numbers-n1 and n2 are amicable numbers if, sum of
factors of n1 is equal to n2 and sum of factors of n2 is equal to n1.
import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int n1,n2,sfn1,sfn2,i;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
n1=Sc.nextInt();
System.out.println("Enter a number");
n2=Sc.nextInt();
sfn1=0;
for(i=1;i<n1;i++)// sum of factors of n1
{if(n1%i==0)
sfn1=sfn1+i;
}
sfn2=0;
for(i=1;i<n1;i++)// sum of factors of n2
{if(n1%i==0)
sfn2=sfn2+i;
}
if(sfn1==n2 && sfn2==n1 && Math.abs(n1-n2)==2)
System.out.println(n1+ " and "+ n2 +" Amicable numbers ");
else
System.out.println(n1 + " and "+ n2 +" are not Amicable numbers");
}}

Automorphic Number
Long and inefficient method-Works upto 3 Short and efficient method- works for any
digits number of digits
import java.util.Scanner; import java.util.Scanner;
class mod1 class mod1
{ public static void main(String args[]) { public static void main(String args[])
58
{ int n1,sq,r=0; { int n1,sq,n2,c=0,r;
Scanner Sc=new Scanner(System.in); Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number"); System.out.println("Enter a number");
n1=Sc.nextInt(); n1=Sc.nextInt();
sq=n1*n1; n2=n1;
if(n1>1 && n1<10) c=0;
r=sq%10; while(n1!=0)
else if(n1>9 && n1<=99) {c=c+1;
r=sq%100; n1=n1/10;
else if(n1>99 && n1<=999) }
r=sq%1000; sq=n2*n2;
if(r==n1) r=sq%(int)Math.pow(10.0,(double)c);
System.out.println(n1+" is an Automorphic if(r==n2)
number"); System.out.println(n2+" is an Automorphic
else number");
System.out.println(n1 + "is not an else
Automorphic number"); System.out.println(n2 + "is not an
}} Automorphic number");
}}

Strong Number 145 = 1!+4!+5!


import java.util.Scanner;
class mod1
{ public static void main(String args[])
{ int n1,n2,s,r,f,i;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
n1=Sc.nextInt();
n2=n1;
s=0;
while(n1!=0)
{r=n1%10;
f=1;
for(i=1;i<=r;i++)
f=f*i;
s=s+f;
n1=n1/10;
}

if(s==n2)
System.out.println(n2+" is a Strong number");
else
System.out.println(n2 + " is not a Strong number");
}}

To Print the denomination for the given number


Long and inefficient method Short and efficient method
import java.util.Scanner; import java.util.Scanner;
class mod1 class mod1
59
{ public static void main(String args[]) { public static void main(String args[])
{ int n1,r; { int n1,r,i;
Scanner Sc=new Scanner(System.in); int d[]={1000,500,100,50,20,10,5,2,1};
System.out.println("Enter a number"); Scanner Sc=new Scanner(System.in);
n1=Sc.nextInt(); System.out.println("Enter a number");
if(n1>=1000) n1=Sc.nextInt();
{ r=n1/1000; for(i=0;i<d.length;i++)
System.out.println(r+"x 1000 = "+ r*1000); { if(n1>=d[i])
n1=n1%1000; { r=n1/d[i];
} System.out.println(r+"x"+d[i]+"="+
if(n1>=500) r*d[i]);
{ r=n1/500; n1=n1%d[i];
System.out.println(r+"x 500 = "+ r*500); }
n1=n1%500; }
}
if(n1>=100) }}
{ r=n1/100;
System.out.println(r+"x 100 = "+ r*100);
n1=n1%100;
}
if(n1>=50)
{ r=n1/50;
System.out.println(r+"x 50 = "+ r*50);
n1=n1%50;
}
if(n1>=20)
{ r=n1/20;
System.out.println(r+"x 20 = "+ r*20);
n1=n1%20;
}
if(n1>=10)
{ r=n1/10;
System.out.println(r+"x 10 = "+ r*10);
n1=n1%10;
}
if(n1>=5)
{ r=n1/5;
System.out.println(r+"x 5 = "+ r*5);
n1=n1%5;
}
if(n1>=2)
{ r=n1/2;
System.out.println(r+"x 2 = "+ r*2);
n1=n1%2;
}
if(n1==1)
System.out.println("1 x 1 = "+ 1);
}}

60
To convert Decimal number to Binary number (Not in syllabus)
// Convert decimal to binary equvalent
import java.util.Scanner;
class st1
{
public static void main(String args[])throws IOException
{

int dnum,i,k,r,t;
int bnum[]=new int[15];

Scanner Sc=new Scanner(System.in);


System.out.println("Enter a number");
n1=Sc.nextInt();

t=dnum;
i=0;

while(dnum!=0)
{
r=dnum%2;
bnum[i]=r;
i++;
dnum=dnum/2;
}
System.out.print("Binary equivalent of "+ dnum +" is ");

for(k=i-1;k>=0;k--)
System.out.print(bnum[k]);
}}

// To accept 2 number and print their highest common factor and their lowest common factor
import java.io.*;
class m1
{ public static void main(String args[])
{
int n2,n1,sn,lcm,hcf=0,i;
Scanner Sc=new Scanner(System.in);
System.out.println("Enter a number");
n1=Sc.nextInt();
n2=Sc.nextInt();
sn=Math.min(n1,n2);
for(i=1;i<=sn;i++)
{
if(n1%i==0 && n2%i==0)
hcf=i;
}
lcm=(n1*n2)/hcf;
61
System.out.println("The HCF of "+n1+" and "+ n2 +" is "+hcf);
System.out.println("The LCM is "+n1+" and "+ n2 +" is "+lcm);
}}

// Sum of all the prime digits in the given number


import java.util.*;
class m1
{
public static void main(String args[])throws IOException
{

int n,n1,r,s=0;

Scanner Sc=new Scanner(System.in);


System.out.println("Enter a number");
n=Sc.nextInt();

n1=n;
while(n!=0)
{
r=n%10;
if(r==1 || r==2 || r==3 || r==5 || r==7)
s=s+r;
n=n/10;
}
System.out.println("The sum of all prime digits in "+n1+" is "+s);
}}

/*The International Standard Book Number (ISBN) is a unique numeric book identifier which is printed
on every book. The ISBN is based upon a 10-digit code. The ISBN is legal if 1*digit1 + 2*digit2 + 3*digit3
+ 4*digit4 + 5*digit5 + 6*digit6 + 7*digit7 + 8*digit8 + 9*digit9 + 10*digit10 is divisible by 11.
Example: For an ISBN 1401601499
Sum=1*1 + 2*4 + 3*0 + 4*1 + 5*6 + 6*0 + 7*1 + 8*4 + 9*9 + 10*9 = 253 which is divisible by 11.
Write a program to:
(i) input the ISBN code as a 10-digit number
(ii) If the ISBN is not a 10-digit number, output the message “Illegal ISBN” and terminate the program
(iii) If the number is 10-digit, extract the digits of the number and compute the sum as explained above.
*/
import java.util.Scanner;
class ISBN
{public static void main(String args[])
{Scanner sc = new Scanner(System.in);
long c=0,i,s=0; long r,rn=0,n,n1;
System.out.println("Enter a number");
n = sc.nextLong();
n1=n;
while(n1!=0)
{ r=n1%10;
62
rn=rn*10+r;
n1=n1/10;
}
System.out.println("Reverse="+rn);
for(i=1;i<=10;i++)
{ r=rn%10;
s=s+r*i;
rn=rn/10;
}
System.out.println("sum="+s);
if(s%11==0)
System.out.println("It is an ISBN number");
else
System.out.println("It is not an ISBN number");
}
}

/*GCD (Greatest Common Divisor ) of two integers is calculated by continued division


method. Divide the larger number by smaller; the remainder then divides the previous
divisor. The process is repeated till the remainder is zero. The divisor then results in the
GCD. */

import java.util.Scanner;
class GCD
{public static void main(String args[])
{Scanner sc = new Scanner(System.in);
int n1,n2,hn,sn,r;
System.out.println("Enter a number");
n1 = sc.nextInt();
System.out.println("Enter another number");
n2 = sc.nextInt();
if(n1>n2)
{ hn=n1; sn=n2;}
else
{ hn=n2; sn=n1; }

while(true)
{ r=hn%sn;
if(r==0)
break;
hn=sn;
sn=r;
}
System.out.println("GCD ="+sn);
}}

Write a Java statements for the following using modulus operator:


a) Check if n is an even number or not
b) Check if n is divisible by 5
63
c) Check if n is divisible by 5 and 7
d) Check if the number n ends with an even digit
e) To extract the first and the last digit of a 4 digit number
f) To extract the last 2 digit of a 5 digit number

ASSIGNMENT ON MODULUS OPERATOR


Question 1 (2009)
Write a menu driven program to accept a number from the user and check whether it is a
“BUZZ” number or to accept any two number and print the GCD of them.
a) A BUZZ number is a number which ends with 7 or divisible by 7.
b) GCD (Greatest Common Divisor ) of two integers is calculated by continued division
method. Divide the larger number by smaller; the remainder then divides the
previous divisor. The process is repeated till the remainder is zero. The divisor then
results in the GCD.

Question 2 (2015)
Using the switch statement, write a menu driven program to:
i) To find and display all the factors of a number input by the user( including 1 and
excluding number itself).
Example :
Sample Input : n=15
Sample output :1,3,5

ii) To find and display the factorial of a number input by the user( the factorial of a non-
negative number n, denoted n by n!, is the product of all integers less than or equal to n.
Examples :
Sample Input : n=5
Sample Output : 5! = 1x2x3x4x5 = 120
For an incorrect choice, an appropriate error message should be displayed.

Question 3 (2014)
A special two-digit number is such that 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 it digits = 5x9 = 45
Sum of 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
digit. If the value is equal to the number of input, output the message “Special 2-digit
number” otherwise, output the message “Not a special 2-digit number”.

Question 4
Write a program to accept a number and check if the first and the last digit of the number
are same or not. Note: The number can have any number of digits.
Example : Input: Enter a number : 343
Output : They are same

64
Question 5 (2017)
Write a program to accept a number and check and display 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 : Consider the number 1124 Sum of digits = 1+1+2+4=8
Product of digits = 1x 1x2x4=8

Question 6 ( 2018)

Write a program to accept a number and print if it is a Pronic number or not


Pronic number is the product of two consecutive numbers
Eg: 12 = 3x4
20 = 4x 5
42 = 6x7

Question 7(2019)
A tech number has even number of digits. If the number is split in two equal halves, then the
square of sum of these halves is equal to the number itself. Write a program to generate and
print all the four digits tech numbers.
Example:
Consider the number 3025
Square of sum of the halves of 3025 = (30+25)2
= (55)2
=3025 is a tech number

*******************************************************************************

65

You might also like