Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

Chapter -5

CONDITIONALS AND NON- NESTED


LOOPS………..

Introduction:-

Generally the normal flow of execution in high level languages is


sequential, i.e. in the order of their appearance from top to bottom.
Each statement is executed only once. Those programs in which
these statements are sequentially executed are called sequential
control structure programs. These programs are very easy to modify
and understand. But these programs work on limited area and do
not fully utilize the capabilities of programming languages.

Sometimes the statement is to be altered by the user. This means the


execution of the program will be selectively or repetitively.
Flow of processing can be controlled by various Java control
structures. Sometimes the statement is to be altered by the user. This
means the execution of the program will be selectively or repetitively.
Flow of processing can be controlled by various Java control
structures.

 COMPOUND STATEMENT :
A compound statement is a grouping of statements in which each
individual statement ends with a semicolon. The group of statements is
also called Block. Compound statement is encised between the pair of
braces ({). The opening The opening brace ({}) signifies the beginning and
closing brace (}) signifies the end of the block .. The following branching
takes place without any decision . It is an unconditional branching.

Illustration :

{
Perimeter = 2* (length + breadth );
System . out. Print(“perimeter =” + perimeter );
}

 PROGRAMMING CONSTRUCTS

In a program , statements may be executed sequentially, selectively and


repetitively. All programming languages provide program constructs.
They are used to control the order (flow ) in which statements are
executed ( or not executed). Let us study three different types of
Statement 1
programming constructs.

Sequence :
Statement 2

A sequence is a control structure in which a set of


Instructions is each executed once in the order in which
Statement 3
they are written . In the order in which they are written .
In a sequence has been pre- determined by the programmer.
Statement 4
s
Iteration :

Iteration is control structure in which a group of statements is executed


repeatedly, the computer iterates through the loop to allow each command to
be executed over and over . It is also called a loop or repetition
 BRANCHING :

In a sequential form of statements, the program flows simply and


unconditional without many decisions. Many times it is required to alter the
flow of sequence of instructions . Java languages provides statements that can
change the flow of a sequence of instructions.
These statements are called control statements . These statements help to
jump from one part of the program to another. The control transfer may be
conditional or unconditional.
The statements used for decision making or conditional control, are as follows:

 CONDITIONALS IN JAVA :

Some times the program is to be executed depending upon a particular


condition . If statement is used for this selective execution (conditional
statements) .
A conditional statement executes a code segment based on a condition,
such as an equality test (a=b), a comparison test ( a>b) or a Boolean
test .
The branching which is based on a particular condition is called
conditional branching.
Java supports the following conditionals which are called decision
making statements ( conditionals):

1. If statement 2. Switch statement

3.Conditional operator statement

If Statement
The ` if ‘ statement helps in selecting one alternative out of the two. The execution of `if’
statement starts with the evaluation of condition . This is a powerful decision making
statement.

General form of` if’ statement :

If (expression) statement ;
Any expression can appear in the parentheses of if statement . If the expression has 0(zero)
value, it is considered as false . If the value is non- zero, this is true. Java provides the
following constructs for implementing the selection control structure :

1. If construct 2. If – else construct

3. if – else – if construct 4. If-if-else construct

5.switch construct

Flow chart of if Construct


From the flow chart it is clear if the condition is True (Yes), statement 1 is executed and then
statement 2 is executed. If the condition is False (No), statement is not executed and
statement2 is executed directly .

INTRODUCTION :
Develop a Java program to find the greatest number out of the three positive numbers using
if construct.

Class iftesting {

Public void iftest (int a, int b, int c) {

Int greatest ;

System .out .print ( “Value of a =” + a ) ;

System .out. print();

greatest =a;

System . out. print(“Value of b=” +=b);


System .out . println ();

If (b>greatest) {

Greatest =b;

System. Out. Print ( “ Value of c=”+c);

System . out. Println ();

If ( c> greatest){

Greatest =c;

System .out . println (Value of the Greatest of the Numbers =”=greatest)

Explanation;
In this Java program, the variable greatest is assigned the value of `a’ . The value of
`b’ is compared with that of greatest. If b> greatest is true, then the statement

greatest =b; is executed

if b<greatest, the statement

greatest =b; is ignored.

Now the `if’ statement compares the value of `c’ with the greatest. If c> greatest then
greatest is assigned the value of c.

No semicolon should follow the if statement.

Use of Semicolon
Using and placing semicolon with if statement is of utmost important. If you put
semicolon in the line having test condition, the program will give error.

If (a>b); //This may work but it is wrong.


In the above example, the if will stop just at semicolon and it will understand the end
of the statement. The statement following this line will not be considered as the part
of that if.

Therefore placement of semicolon should be carefully.

It should also be that expression in if ( )should be Boolean type.

If Boolean type is not use, the program will give error.For example –

Int x=5;
This will produce error
If (x) {

Statement;
This is accurate use.
} x>=5 is a Boolean
If (x >=5 { expression.

Statement;

INTRODUCTION :
Write a program for swapping of numbers using if statement.

Class Swap{

Public void main (int x, int Y) {

If (x>y) {

X=x - y;
X=x + y;

X=y - x;

If (y>x) {

Y = y - x;

X= x + y ;

Y = x-y;

System .out. println ( “Number after Swapping x is = “ +x);

System . out. Prntln (“Number After Swapping Y is = “+Y) ;

Nested Ifs
Using the if statement, you can choose a single action or choose a single action or choose
between two actions. It is also possible to choose between several actions (three or more)
using the if statements. The most basic and straightforward way to accomplish this work, is
using multiple if statements. Let us have a look on the following example:

Class nested If{

Public void main (int x ) {

If (x>-1){

If( x! =0)

If (x>0)

System .out. printin ( “x is a positive number having value “ +x);


}

It checks number is zero, positive or negative using nested if statement.

Let us have a look on another example:

Example : Determine Whether a value is negative, positive or Zero.

If ( x<0){

System . out. Println (x +” is negative “);

If ( x >0){

System . out. Println ( x+”is positive “);

If (x==0){

System . out. Println ( x+ “ is zero”);

This is very simple code using Ifs and it works completely but it is not very efficient because it
always performs three comparisons . A more efficient way of writing the same code involves
putting one if statement inside another.

If(x<0){

System . out . println ( x+”negative”);

else {

If ( x>0){
System . out. Println ( x +”is positive”);

else {

System . out. Println (x+” is zero “);

This code is more efficient . When x is negative , only one comparison is needed (is x<0 ?) .If
the first comparison is false, only one more Is required to distinguish between positive and
zero, so there will be a maximum of two comparisons . There seems no problem of running
the program when the programming is simple, but for programs running thousands of lines of
code, millions of times over, it can make the difference between fast and slow performance.

If – else Construct
Instead of using two if statements, you can use an if –else statement . The execution of the`
if-else’ statement starts with the evaluation of the condition. The method of testing one
condition and then the other works but it is a complex one . The keyword else provides
readable code .

If ( expression)

Statement ;

Else

Statement ;
When the computer executes an if statement, it evaluates the expression . If the value is true,
the computer executes the first statement and skips the statement that follows the “else”. If
the value of the expression is false , then the computer skips the first statement and executes
the the second one. Note that in any case, one and only one of the two statements inside the
if statement is executed . Two these courses of action based on the value of the expression .

Flow Chart of If – else Statement


In the flowchart, if the condition is true, statement1 is executed followed by rest of the code
but the statement 2 is not executed . If the condition is false, Statement2 is executed
followed by rest of the code but the statement1 is not executed.

ILLUSTRATION :
Program to solve a quadratic equation .

To find the value of y= ax 2 + bx +c

If x>=4 and y= -ax 2+bx – c; if x< 4

Class If ElseTest {

Public void main (int a , int b, intc,intx) {

Int y;

System . out.println ( “Value of x =” + x);

System . out.println ( “Value of a= “+a );


System . out.println ( “Value of b=”+b );

System . out.println ( “Value of c =” +c);

If (x>=4){

System . out. Println (“ Value of y =” +(a*x* x + b * x + c ));

Else{

System . out. Println (“ Value of y =” +(a*x* x + b * x-c ));

The if – else – if Statement


For more than two choices, the if – else-if statement can be used. First the condition 1is
tested and if it is true then, statement 1 is executed and all other is false – else-if constructs
ends.

If condition 1 is false, then the statement 1 is ignored and condition 2 is tested .. If it is true
then statement 2 is executed and remaining if-else-if construct is terminated and if the
condition 2 is false, statement 2 is ignored and condition 3 is tested . This process continuous
in this way.

If (condition 1){

Statement 1 which will be executed if condition 1 is true

Else if (condition 2 ){

Statement 2 which will be executed if condition 2 is true

.
.

Else if (condition n) [

Statement n which will be executed if condition n is true

else {
statements which will be executed if none of the above conditions is true.
}

statements which will be executed always

If Ladders

The addition of the else keyword with the if statement allows you to specify actions for
the case where the condition is false. However, there may be cases where ycnj
would like to handle more than just two alternatives. Look at the following program
segment :
if(mark >= 80) {

System.out.printlnfYou got an A Grade.");


}
else {

if(mark >= 65) {

System.out.println("You got a B Grade.");


}
else {

if(mark >= 50) {

System.out.println("You got a C Grade.");

} else
{
System.out.println( You got a D Grade.");
H

}
}
>

Alternatively, you can use an if-ladder using the else-if phrase : if


(mark >= 80) {
System.outprintlnfYou got an A Grade.");

\
else if (mark >= 65) {

System.out.println("You got a B Grade.");


>
else if (mark >= 50) {

System, out. printlnfYou got a C Grade.");


•-

}
else {

-

System.out.println("You got a D Grade.");

}
Write a program to calculate we the commission of a salesman as per following data

sale Commission
More than & equal to 100000 25%
80000 to 99999 22.5%
60000 to 79999 20%
40000 to 59999 15%
Less than 40000 12.5%

class IfElselfTest {
public void main(double sales) {
double comm;
comm = 0;
System.out.println("Value of Sales =" +sales);
if(sales > 100000) {
comm = sales * (0.25);
System.out.println("Commission =" +comm);
} else
if(sales >= 80000) {
comm = sales * (0.225);
java
System.out.println("Commission =" +comm);
}
else if(sales >= 60000) {
comm = sales * (0.20);
System.out.prlntln("Commission = +comm);
II

} else
if(sales >= 40000) {
comm = sales * (0.15);
system.out.println("Commission =+comm);
}
}s

else {
comm = sales * (0.125);
}
} System.oUt.println(''Commiission ="+comm)
;
>
SBI HOME FINANCE revised its rate of interest for Public Deposits

Deposit under the cumulative scheme is accepted for a period between 3 and
5 years only.
Write a program in Java to find the :
•.

(a) amount (A) due for sum (P) invested under the cumulative option scheme,
by using the formula A = P * (1 +.01. rf
(b) interest (I) for each year, under the annual interest scheme, using the formula I
= .01 x p x r

class Investment {
public void investment(int year, double r, double p)
{ double a = 0;
double i = 0;
System.out.println("Amount invested :" +p );
System.out.println("UNDER CUMULATIVE SCHEME");
for(year = 1;
year <= 5; year++) { if (year <= 2) {
r = 0;
Java
}
else {
r = 0.115;
a = p * (1+r);
System.out.println("Amount After Year" +(year+l)+ " =" +a);
}
}
System.out.println("ANNUAL INCOME SCHEME");
for(year = 1; year <= 5; year++) {
if(year == 1) {
ism
r = 0.10;
}
else if (year =- 2){ r = 0.105;
>
else {
r = 0.115;
r = p * r?
}
System.out.printfn(“intrest after year =+(year+1+=”+i);

Develop a Java program to solve the quadratic equation


\Noti3t
ax2 + bx + c = 0 (a>0) n
The two values ofx can be given byx = 2a
I one of many possible statements to execute.

If b2-4ac>0 roots are real and unequal.

ifb2 -4ac – o roots are equal and real.

Ifb2 - 4ac < 0 roots are imaginary and unequal.

class rootsEquatfon {

public void Roots(doubIe a, double b, double c) {

double rl, r2;


rl = 0;
r2 = 0;
System.out.println("Entered Value of a = " +a);
System.out.printlnf'Entered Value of b = " +b);
System.out.printlnfEntered Value of c = " +c);
if ((b * b-4 * a * c) > 0) {
rl = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
rl = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
System.out.println("One Root is =" +rl);
System.out.println("Second Root is =" +r2);

}else if((b * b - 4 * a * c) == 0) {
rl =-b I (2 * a);
r2 = -b/(2*a);

System.out.prlntln(,,Root One is =" +rl);


System.out.println("Root Second is =" +r2);
}
else if((b *b-4*a*c)<0){
rl = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
r2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
System.out.print("Roots are imaginary");
>
}
}
Implement a class calculator that models handheld calculator. It should have
(atleast) the following functionality:
addition, subtraction, multiplication, integer division, remainder.
class Calculator {
public void Calculate(double nl, double n2, char chr) {
double result = 0.0; {
System.out.println("First Number = " +nl);
System.out.println("Second Number = " +n2);
}
switch(chr) {
case '+' : result = nl + n2;
System.out.println("Addition of numbers is=" +result);
break;
case '-' : result = nl - n2;
System.out.print("Subtraction of numbers is=" +result
break;
case '*' : result = nl * n2;
System.out.print("Multiplication of numbers is=" +result);
break;
case '/' : result = nl / n2; System.out.print("Result of Division is=" +result);
break;
case '%' : result = nl % n2;
System.out.print("Result of Modulus Operator is =" +result);

break;
default: System.out.println("Operator Selected is Wrong");
}
}
}
The switch Statement
The syntax of switch statement is as follows : switch (expression) {
case constant 1 :
Statement-blockl;
break;
case constant 2 :
Statement-block2;
break;
---------------
-----------
case constant n :
statement-block n;
break;
default:
Statement-block n+1;
}

Execution of Switch Statement


The execution of switch statement begins with the evaluation of expression. If the
expression evaluates as constant the execution of switch starts with the
statement
with constant n. All other statements following this statement execute
sequentially.
If the value of expression does not reconcile with the constantl, constant2 the
statement with default is executed.
Flow Chart for Switch Statement
The switch statement first starts with the switch keyword and followed by an
expression. The Java code for
expression must be integer or character expression. The value of expression
must be an Integral constant.
There are various case labels such as 1, 2, 3 etc. These case labels must be
evaluable to integral constants.
When the switch is executed, value of expression is compared with case labels
value starting from top and

moving towards bottom. If any of case labels that matches with expression, the
block of code that follows
case gets executed. After block of code gets executed there is a break statement
at the end of block code
which breaks the switch statement and transfer control to rest-of-code to
execute. If break statement is not
written, the control starts comparing with next case that follows. At the last
default is an optional case
which is placed when no case matches with expression. If no expression value
matches with case labels value
then default case is triggered and code associated with it gets executed

use of break statement with switch statement

a few things to keep in mind:

A switch cannot work for non-equality comparisons. Therefore, do not use switch in
such comparisons.
M 2. The case labels of switch statements must be literals or constants.

3. Switch statement works with integral types like byte, short, Int, long and char data
type.
4. Two case labels in the same switch can have the identical value. In case of nested
switch statements, the case constants of the inner and outer
switch can have common values. .
example : the statement that tests a value against a set of consants.
if (day = = 'a') {
……….
………
}
else if (day == 'b') {
}
else if (day == 'c') {
…….
……
}
else {
…..
…..
}
The abow program axle can IK? written using r.witc h Matemcnt in the following manner :
switch(dciy) {

case a: …….
break;

case 'b' :……


break;
case V :……..
break;
default :
break;
}
Distinction between switch and if statement

To convert the numerals into equivalent words using switch statement

.For example:
Input-124
Output-One Two Four
class switchCase {
public void main(int num) {
Int reverse = 0, remainder;
while(num > 0) {
remainder = num % 10;
0h *
reverse = reverse * 10 + remainder;
-•
num » num / 10;
}

String result- " HJ


whlle(rever§e "- 0) ( :

remainder s reverse % 10;


reverse = reverse /10;
switch(remainder) (
ease 0:
result + result+zero”;
break;
case 1 ;
result * result » "One M;

break;
case 2 ;
result - result t "Two ";
break;
case 3 ;
result a result + "Three ";
break;
case 4 :
result = result + "Four";
break;
case 5 :
result = result + "Five ";
break;
case 6 :
result = result + "Six ";
break;
case 7 :
result = result + "Seven ";
break;
case 8 :
result = result + "Eight";
break;
J
case 9 :
result = result + "Nine ";
break;

default:
result = " ";
}
}
System.out.println(result);
}

}
Conditional Operator (?:)
The conditional operator ?: has been introduced as a shorthand replacement for the if-
then-else conditional statement. This operator Is also known as the ternary operator
because it uses three operands. The
conditional operator can be evaluated and it can return a value.
In the following example, this operator should be read as: "If some Condition is true,
assign the value of valuel otherwise assign the value of va!ue2\
someCondition ? valuel : value2

example 1.
String result-
result = (score > = 100) ? "Century" : "Half Century";

The above statement can be read as if score is 100 or more than 100, produce the result
as "Century" and if the score is less than 100, produce the result as "Half Century".
Example 2.
Rewrite the following using Ternary operator:
if(income <= 10000)
tax = 0;
else
tax = 12;
Solution ; income < = 10000 ? 0 : 12
Or it can be written as
Income < = 10000 ? 0 : 10000 * 0.12
(assuming that tax rate is 12% if the income is greater than I 10000)

1.rewriter the following program segment using the if-else statement

String grade =(mark >= 90) ? "A": (mark >= 80) ? "B" : "C ;
Answer, if (mark > = 90) {
grade = "A";
}
else if (mark >= 80) {
grade = "B";
} else
grade = "C;
2.Rewrite the following program se*
common= (sale > 15000) ? sale * 5 / 100 :
Answer.ff (sale > 15000)
comm = sale * 5 / 100;
else
comm = 0
3.a cloth shoeroom has announced the following festival discounts on the purchase of
items, based on the total cost pf the items purchase:
Total cost diacount (in percentage)
Less than -2000 5%
2001 to 5000 25%
5001 to 10000 35%
Above 10000 50%
Write a program to input the total and disply the amount to be paid by the customer after
availing the discount.
Answer. class Amount {
public void main(double cost) {
System.out.printlnfAmount of purchase: " +cost);
double discountRate,
discountAmt, finalAmt; discountRate = 2.0;
if((cost > 2000) && (cost <= 5000)) discountRate = 25.0;
else if((cost > 5000) && (cost <= 10000)) discountRate = 35.0;
else
discountRate = 50.0;
discountAmt = cost * discountRate / 100.0;
finalAmt = cost - discountAmt;
// display the results System.out.println(MTotal cost : " +cost);
System.out.println("Discount % : M +discountRate);
System.out.println(MDiscount Amt.: 11 +discountAmt);
System.out.println("Final Price : " +finalAmt);
}
}

4. define a class called mobikr with the following decription:


instance variables / data members :
int bno - to store the bike's number
int phno - to store the phone number of the customer
String name - to store the name of the customer
int days - to store the number of days the bike is taken on rent
int charge - to calculate and store the rental charge
Member methods:
void input() - to input and store the detail of the customer
void compute() - to compute the rental charge.
The rent for a mobike is charged on the following basis :
First five days ? 500 per day.
Next five days ? 400 per day.
Rest of the days ? 200 per day.
void display() - to display the details in the following format:
Bike No. Phone No. Name No. of days Charge
Answer:. class mobike { int bno;
int phno;
String name;
int days;
int charge;
public void get(int cbno, int cphno, String cname, int rdays, int ccharge) {
bno = cbno;
phno = cphno;
name = cname;
days = rdays;
charge = ccharge;
}
public void compute() {
If (days <= 5)
charge = days * 500;
If (days > 5 && days <= 10)
charge = (days - 5) * 400 + 500 * days;
if (days > 10)
charge = (days - 10) * 200 + 5 * 400 + 500 * days;
}
Public void display() {
System.out.println ("Bike No." + "\t" + "Phone No." + "\t" + "Name" + “\t”+”no.of days”+ "\
t" + "charge");
System.out.println(bno + "\t" +phno +"\t" +name +"\t" + days + "\t" +charge);
}
}
5. Write a program which finds whether a given year is a leap year or not
Answer, public class LeapYear {
public void find(int year) { if (year % 100 == 0) {
if (year % 400 == 0) {
System.out.println(year + " is a leap year");
}
else {
System.out.println(year + " is not a leap year");
}
>
else {
if (year % 4 == 0) {
System.out.println(year + " is a leap year");
}
else {
System.out.println(year + " is not a leap year");
}
}
}
}
6 an electronics shop has announced the following seasonal discount on the purchase of
certain items:
Purchase amount in rupees Discount on laptop Discount on besktop/pc
0-25000 0.0% 5.0%
25001-57000 5.0% 7.5%
57001-100000 7.5% 10.0%

More than 100000 10.0% 15.0%


Write a program based on the above to input name, address amount of purchase
and the type od purchase (l for laptop and d for desktop) by a customer.
Computer and print the net amount to be paid by a customer along with his name
and address.
(hint; discount=(discount rate/100)* amount of purchase
Net amount=amount of purchase-discount)

Answer: import java.io.*;


class laptoPPC{
mi imP°rt java.io.*;
public static void main(String args[]) throws lOException {
double p, d, net;
String name,address;

System.out.println("********* BILL PROGRAM ************


System.out.println("Enter Name of the Customer-)-
InputStreamReader reader = new InputStreamReader(System.);
BufferedReader input = new BufferedReader(reader);
name = input.readLine();
-

System.out.println("Enter address ::");


address = input.readLine();
System.out.println("Enter Value of Purchases =");
String x = input.readLine();
p = Double.parseDouble(x);
System.out.println("Name of the Customer::" +name);
System.out.println("Address of the Customer::"+address);
System.out.println("L. Enter L for Laptop");
System.out.println("D. Enter D for Desktop");
System.out.println(); System.out.println("Enter your choice::");
char choice;
choice = (char)System.in.read();
System.out.printlnfName of the Customer::" +name);
System.out.println("Address of the Customer::" +address);
switch(choice) {
case V : if(p <= 25000){
d = 0;
net = p - d;
System.out.printlnfAmount to be paid" +net);
else if(p > 25000 && p <= 57000) {
d = (5.0/100)*p;
net = p - d;
System.out.println("Amount to be paid" +net);

m
else if(p > 57000 && P < =100000) {
d = (7.5 / 100) * P;
net = p - d;
System.out.println("Amount to be paid" +net);

}

else if(p > 100000) {


d = (10.0 / 100) * p;
net = p - d;
System.outprinUn("Amount to be paid" +net);
} break;
case 'D': if(p <= 25000) {
d = (5.0 / 100) * p;
net = p - d;
System.out.println("Amount to be paid" +net);
}

d = (7.5 / 100) * p;
net = p - d;
System.out.println("Amount to be paid" +net);
}
else if(p > 57000 && p <= 100000) { d = (10.0 / 100) * p;
net = p - d;
System.out.print\n(" Amount to be paid" +net);
}
else if(p > 100000) {
d = (15.0 / 100) * p; net = p - d;
System.out.phntlnCAmount to be paid" +net);
} break;
}
}
Output of the program:
7.using a switch statement ,write a menu driven program to convert progam to convert a
given temperature from Fahrenheit to celcius and vie versa. For an incorrect choice, an
apporopriate error message should be displayed.
(HINT : C = 5/9x(F-32) and
F = 1.8xC +32)
1 ff nr V/ce versa For

Answer, import java.io.*;


class Temperature {
public void main(int choice) throws IOException {
float c = 0;
float f = 0;
InputStreamReader reader = new InputStreamReader(System in);
<

BufferedReader input = new BufferedReader(reader);


System.out.println("Enter 1. Fahrenheit to Celcius ");
System.out.println("Enter 2. Celcius to Fahrenheit");
switch(choice) {
case 1:
System.out.printlnfEnter Temperature in Fahrenheit");
String a = input.readLine();
f = Float.parseFloat(a);
c = 5/9F*(f-32);
System.out.println("Equivalent Temperature in Celcius is ="+c);
break;
case 2:
System.out.printlnfEnter Temperature in Celcius");
String b = input.readLine();
c = Float.parseFloat(b);
f = (1.8F * c) + 32;
System.out.println("Equivalent Temperature in Fahrenheit is ="+f);
break;
default:
System.out.println("Incorrect Choice");
break;
}
Out put of the Program :
;

Enter 1. Fahrenheit to Celcius Enter


2. Celcius to Fahrenheit
Enter Temperature in Fahrenheit
58.6
Equivalent Temperature in Celcius is=37.0
8.'civen below is a hypothetical table showing rates of income tax for mal[ below the age of
65 years:
income Tax in ? Taxable Income (TI) in ?
Nil
Does not exceed ? 1,60,000
Is greater than t 1,60,000 and less than (TI - 1,60,000) x 1Q% or equal to f
5,00,000
Is greater than * 5,00,000 and less than [(TI - 5,00,000) x 2 o/o] + 34,000 or equal
0

to ? 8,00,000
Is greater than ? 8,00,000

[fn - 8,00,000) x 30%] + 94,000

Write a program to input the age, gender (male or female) and Taxable Income 0f person.
If the age is more than 65 years or the gender is female, display "wrong category". If the
age is less than or equal to 65 years and the gender is male, compute d/f
display the Income Tax payable as per the table given above.

Answer, import java.io.*;


class IncomeTax {
public static void main(String argsf]) throws lOException { int age;
int gender;
double income;
double tax;
double p,d,net;
String name,address;
System.out.printlnf********* INCOME TAX **********»);
System.out.println("Enter Age of the Person::");
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String x = input.readLineQ;
age = Integer, parselnt(x);
System.out.println("Enter Income of the Person::"); String y = Input.readLine();
income = Double.parseDouble(y);
System.out.println("M. Enter M for Male"); System.out.println("F. Enter F for Female");
System.out.printlnQ;
System.out.println(uEnter your choice::");
char choice;
choice = (char)System.in.readQ;
switch(choice) {
case W: if (age <= 65 && income <=
160000) { System.out.println("Tax Amount = Nil");
}
else if(age <- 65 m income > 160000 && income <= 500000){ tax = (income - 160000) * 0.1;
System.out.println("IncomeTax in Rupees=M +tax);
}
else if(age <= 65 && income > 500000 && income <= 800000){ tax = (income - 500000) *
0.2 + 34000;
System.out.println(“_____________“);

System.out.println("Income Tax in Rupees=" +tax);


System.out.println("____________________.");
}
else if (age <= 65 && income > 800000) {
tax = (income - 800000) * 0.3 + 64000;
System.out.println("Income Tax in Rupees=" +tax);
}
break;
case 'F' : if(age > 65) {
System.out.println(“_____________”);
System.out.println("Wrong Category");
System.out.printlnC'______________”);
}
break;
}
}
}
Output of the Program :
********* INCOME TAX ********** Enter Age of the Person::
25
Enter Income of the Person:: 382000
M. Enter H for Hale
F. Enter F for Female
Enter your choice::
m
Income Tax in Rupees=22200.0
9. Shasha Travels Pvt. Ltd. Gives the following discount to its customers
write a program to input the name and ticket amount for the customer and calculi the
discount amount and net amount to be paid. Display the output m the following
Ticket discount
Above 70000 18%
55001 to 70000 16%
35001 to 55000 12%
25001 to 35000 10%
Less than 25001 2%
s
format for each customer :
SI.No. Name Ticket charges Discount Net amount
1 _____ ____________ __________ _________

(Assume that there are 15 customers, first customer is given the serial no (SI.No.) j next
customer 2......... and so on)

Answer, import java.io.*; class Shasha {


public static void travel() throws lOException {
String name[] = new String[20];
double ticketcharges[] = new double[20];
double discounts = new double[20];
double netamountn = new double[20];
int i;
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
//The for loop will accept the names and details for 15 customers.
for(i=0; i < 15; i++) {
System.out.println("Name of the Customer::");
name[f| = buf.readiine();
System.out.println("Ticket Charges");
String t = buf.readiineQ;
ticketcharges[i] = Double.parseDouble(t);
if(ticketcharges[i] > 70000) {
discount^] = ticketcharges[i] * 0.18;
netamount[i] = ticketcharges[i] - discount[i];
}
CANDID ICSE COMPUTER APPLICATIONS" 1°
else if(ticketcharges[i] > 55000) {
discount^ = ticketcharges[i] * 0.16;
^ netamount[i] = ticketcharges[i] - discount[i];
else if(ticketcharges[i] > 35000) {
discount^] = ticketcharges[i] * 0.12;
netamount[i] = ticketcharges[i] - discounts
>
else if(ticketcharges[i] > 25000) {
discount^] = ticketcharges[i] * 0.10;
netamount[i] = ticketcharges[i] - discount[i];
} else
discount^] = ticketcharges[i] * 0.02;
netamount[i] = ticketcharges[i] - discount[i];
}
System.out.println("SHASHA TRAVELS");
System.out.println("TlCKET DETAILS");
System.out.println("SI.No. Name Ticket Charges Discount Net Amount");
System.out.println("=== ====== =========== ====== ========");
for(int k = 0; k < 2; k++) {
intp;
p = k + l;
System.out.printJn(p +""+name[k] +""+ticketcharges[k] +""-Kliscount[k]
+""+netamount[k]);
1

} System.out.println();
System.out.println("We wish you a happy and safe journey");
Output of the Program :
Name of the Customer:: Varun Sharma
Ticket Charges 56775
Name of the Customer:: Pranav Roy
Ticket Charges
13235
Name of the Customer::
10. Define a c/ass called Parking Lot with the following description :
Instance variables / data members :
int vno - To store the vehicle number
int hours - To store the number of hours the vehicle is parked in the parking lot
double bill - To store the bill amount
Member methods :
void input () - To input and store the vno and hours.
void calculate () - To compute the parking charge at the rate of ^ 3 for the first hour
or thereof and ? 1.50 for each additional hour or part thereof.
Par

void dispiay () - To display the detail


Write a main method to create an object of the class and call the above methods.
Answer, import java.io.*; class Parking Lot {s
private int vno;
private int hours;
private double bill;
void input() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.printlnf'Enter the vehicle number::");
String y = reader. readLine();
hours= Integer, parselnt(y);
System.out.println("Enter number of hours::");
String r = reader. readLine();
hours = Integer.parselnt(r);
}
void calculate() {
if (hours <= 0) {
System.out.println("Wrong Input");
System.exit(0);
>
else if(hours > 0 && hours <= 1) {
System.out.printlnf'Parking Charges=");
hill = hours * 3.0;
}
else {
System.out.printlnf'Parking Charges =");
bill = 3.0 + (hours - 1) * 3;
System, out.println(-fbill);
}
}
void display() {
System.out.println("Vehicle Number::"
System.out.println("Total Time::" +hours)-
+vno);
System.out.println('Total Charges::" +bi||);
}
public static void main(String args[]) throws lOException {
ParkingLot pk = new ParkingLot(V //,
pk.inputQ;
••

//creation of object
pk.calculate();
pk.display();
System.out.println();
}

}
Output of the Program :
Enter the vehicle number
3291
Enter number of hours:: 8
Parking Charges = 24.0
Vehicle Number:: 3291 Total Time:: 8
Total Charges:: 24.0
$ A statement is an instruction given to the computer for doing an action. • Statements
which are executable in Java end with a semicolon (;).
Q A compound statement contains a sequence of statements which are enclosed within
a pair of braces { }.
Comma operator connects multiple statements in one expression.
©An if statement is used when we have to select one alternative out of the two.
0An if is a decision making statement.
QNo semicolon should follow an if statement, otherwise the program will give error.
0If statement can be nested.
0A switch statement is used where there are several courses of actions and you have to
select one of them.
0A switch statement can work for equality comparisons. Do not use it for n non-equality
comparisons.
The case labels of switch statement must be a literal or constant’s

MORE PROGRAMS RELATED To THIS CHAPTER

You might also like