Professional Documents
Culture Documents
Chapter - 5 Conditionals and Non-Nested LOOPS .. Introduction
Chapter - 5 Conditionals and Non-Nested LOOPS .. Introduction
Introduction:-
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
Sequence :
Statement 2
CONDITIONALS IN JAVA :
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.
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 :
5.switch construct
INTRODUCTION :
Develop a Java program to find the greatest number out of the three positive numbers using
if construct.
Class iftesting {
Int greatest ;
greatest =a;
If (b>greatest) {
Greatest =b;
If ( c> greatest){
Greatest =c;
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
Now the `if’ statement compares the value of `c’ with the greatest. If c> greatest then
greatest is assigned the value of c.
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 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{
If (x>y) {
X=x - y;
X=x + y;
X=y - x;
If (y>x) {
Y = y - x;
X= x + y ;
Y = x-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:
If (x>-1){
If( x! =0)
If (x>0)
If ( x<0){
If ( x >0){
If (x==0){
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){
else {
If ( x>0){
System . out. Println ( x +”is positive”);
else {
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 .
ILLUSTRATION :
Program to solve a quadratic equation .
Class If ElseTest {
Int y;
If (x>=4){
Else{
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){
Else if (condition 2 ){
.
.
Else if (condition n) [
else {
statements which will be executed if none of the above conditions is true.
}
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) {
} else
{
System.out.println( You got a D Grade.");
H
}
}
>
\
else if (mark >= 65) {
}
else {
•
-
}
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);
class rootsEquatfon {
}else if((b * b - 4 * a * c) == 0) {
rl =-b I (2 * a);
r2 = -b/(2*a);
•
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;
}
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
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;
.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;
}
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)
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);
}
}
m
else if(p > 57000 && P < =100000) {
d = (7.5 / 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
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.
(Assume that there are 15 customers, first customer is given the serial no (SI.No.) j next
customer 2......... and so on)
} 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
//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