0% found this document useful (0 votes)
58 views

Branching Control Statements

The document discusses different branching control statements in Java including if, if-else, and switch statements. It provides details on: - The if statement evaluates a condition and executes the statement if true. Conditions use relational operators like ==, !=, <, >, <=, >=. - The if-else statement executes one group of statements if the condition is true and another group if false. - Nested if-else statements allow placing if-else blocks within the if or else blocks of another if-else statement. - Multiple statements can be executed in the if or else block by enclosing them in curly braces.

Uploaded by

Shivam Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Branching Control Statements

The document discusses different branching control statements in Java including if, if-else, and switch statements. It provides details on: - The if statement evaluates a condition and executes the statement if true. Conditions use relational operators like ==, !=, <, >, <=, >=. - The if-else statement executes one group of statements if the condition is true and another group if false. - Nested if-else statements allow placing if-else blocks within the if or else blocks of another if-else statement. - Multiple statements can be executed in the if or else block by enclosing them in curly braces.

Uploaded by

Shivam Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

-: Branching Control Statements: -

 The if statements
 The if-else statement
 switch
 The conditional operators
The if Statement Like most languages, JAVA uses the keyword if to implement
the decision control instruction. The general form of if statement looks like
this: if (this condition is true) execute this statement; The keyword if tells the
compiler that what follows is a decision control instruction. The condition
following the keyword if is always enclosed within a pair of parentheses. If the
condition, whatever it is, is true, then the statement is executed. If the
condition is not true then the statement is not executed; instead the program
skips past it. But how do we express the condition itself in JAVA? And how do
we evaluate its truth or falsity? As a general rule, we express a condition using
JAVA’s ‘relational’ operators. The relational operators allow us to compare two
values to see whether they are equal to each other, unequal, or whether one is
greater than the other. Here’s how they look and how they are evaluated in
JAVA.

This expression is true if


x == y x is equal to y
x != y x is not equal to y
x<y x is less than y
x>y x is greater than y
x <= y x is less than or equal to y
x >= y x is greater than or equal to y
The relational operators should be familiar to you except for the equality
operator == and the inequality operator !=. Note that = is used for assignment,
whereas, == is used for comparison of two quantities. Here is a simple
program, which demonstrates the use of if and the relational operators .
//Example of if statement
Import java.util.Scanner;
public class Main
{
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
System.out.println(“Enter the Number less than 100”);
int num=sc.nextInt();
if(num<100)
System.out.println(“what an Obedient Student you are!”);
}
}
On execution of this program, if you type a number less than or equal to 100,
you get a message on the screen through println( ). If you type some other
number the program doesn’t do anything. The following flowchart would help
you understand the flow of control in the program.
Example: While purchasing certain items, a discount of 10% is offered if the
quantity purchased is more than 1000. If quantity and price per item are input
through the keyboard, write a program to calculate the total expenses.

//Calculation Of total expenses


import java.util.Scanner;
public class Expenses
{
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
System.out.println(“enter the quantity:”);
int qty=sc.nextInt();
System.out.println(“Enter the rate”);
float rate=sc.nextFloat();
int dis=0;
if(qty>1000)
dis=10;
float total=(qty*rate)-(qty*rate*dis/100);
System.out.println(“Total expenses “+total+” Rs..”);
}
}
Here is some sample interaction with the program.
Enter quantity
1200
Enter rate
15.50
Total expenses = Rs. 16740.0
Enter quantity
200
Enter rate
15.50
Total expenses = Rs. 3100.0

In the first run of the program, the condition evaluates to true, as


1200 (value of qty) is greater than 1000. Therefore, the variable
dis, which was earlier set to 0, now gets a new value 10. Using this
new value total expenses are calculated and printed.
In the second run, the condition evaluates to false, as 200 (the value
of qty) isn’t greater than 1000. Thus, dis, which is earlier set to 0,
remains 0, and hence the expression after the minus sign evaluates
to zero, thereby offering no discount.

The Real Thing


We mentioned earlier that the general form of the if statement is as follows
if ( condition )
statement ;
Truly speaking the general form is as follows:
if ( expression )
statement ;
Here the expression can be any valid relational that evaluates to a Boolean
value. We cannot use arithmetic expressions in if statement. For example,
all the following if statements are invalid.
if ( 3 + 2 % 5 )
printf ( "this doesn’t work" ) ;
if ( a = 10 )
printf ( "Even this does’nt work" ) ;
if ( -5 )
printf ( "this too does’nt work" );
Multiple Statements within if
It may so happen that in a program we want more than one
statement to be executed if the expression following if is satisfied.
If such multiple statements are to be executed then they must be
placed within a pair of braces as illustrated in the following ex.

Example : The current year and the year in which the


employee joined the organization are entered through the
keyboard. If the number of years for which the employee has
served the organization is greater than 3 then a bonus of Rs. 2500/-
is given to the employee. If the years of service are not greater
than 3, then the program should do nothing.
public class Main
{
public static void main(String []args)
{
int bouns,cy,yoj,yos;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter current year”);
cy=sc.nextInt();
System.out.println(“Enter year of joining”);
yoj=sc.nextInt();
yos=cy-yoj;
if(yos>3)
{
bouns=2500;
System.out.println(“Bouns=Rs.”+bouns);
}
}
}
Observe that here the two statements to be executed on satisfaction
of the condition have been enclosed within a pair of braces. If a
pair of braces is not used then the java compiler assumes that the
programmer wants only the immediately next statement after the if
to be executed on satisfaction of the condition. In other words we
can say that the default scope of the if statement is the immediately
next statement after it.

The if-else Statement


The if statement by itself will execute a single statement, or a
group of statements, when the expression following if evaluates to
true. It does nothing when the expression evaluates to false. Can
we execute one group of statements if the expression evaluates to
true and another group of statements if the expression evaluates to
false? Of course! This is what is the purpose of the else statement
that is demonstrated in the following example:
In a company an employee is paid as under:
If his basic salary is less than Rs. 1500, then HRA = 10% of basic
salary and DA = 90% of basic salary. If his salary is either equal to
or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic
salary. If the employee's salary is input through the keyboard write
a program to find his gross salary.
public class Main
{
public static void main(String arg[])
{
float bs,gs,da,hra;
Scanner sc= new Sacnner(System.in);
System.out.println(“Enter basic salary”);
bs=sc.nextFloat();
if(bs<1500)
{
hra=bs*10/100;
da=bs*90/100;
}
else
{
hra=500;
da=bs*98/100;
}
gs=bs+hra+da;
System.out.println(“Gross salary=Rs.”+gs);
}
}

A few points worth noting...


(a) The group of statements after the if upto and not including the else is called an ‘if block’.
Similarly, the statements after the else form the ‘else block’.
(b) Notice that the else is written exactly below the if. The statements in the if block and
those in the else block have been indented to the right. This formatting convention is
followed throughout the book to enable you to understand the working of the program
better.
(c) Had there been only one statement to be executed in the if block and only one
statement in the else block we could have dropped the pair of braces.
(d) As with the if statement, the default scope of else is also the statement immediately
after the else. To override this default scope a pair of braces as shown in the above
example must be used.
Nested if-elses:

It is perfectly all right if we write an entire if-else construct within


either the body of the if statement or the body of an else statement.
This is called ‘nesting’of ifs. This is shown in the following program.

public class Main


{
public static void main(String args[])
{
int i;
Scanner sc=new Scanner(Sytem.in);
System.out.println(“Enter either 1 or 2”);
int i=sc.nextInt();
if(i==1)
System.out.println(“you would go to Heaven”);
else
{
if(i==2)
System.out.println(“Hell is where you belong”);
else
System.out.println(“How about mother earth!!”);
}
}
}
Note that the second if-else construct is nested in the first else
statement. If the condition in the first if statement is false, then the
condition in the second if statement is checked. If it is false as
well, then the final else statement is executed.
You can see in the program how each time a if-else construct is
nested within another if-else construct, it is also indented to add
clarity to the program. Inculcate this habit of indentation,
otherwise you would end up writing programs which nobody (you
included) can understand easily at a later date.
In the above program an if-else occurs within the else block of the
first if statement. Similarly, in some other program an if-else may
occur in the if block as well. There is no limit on how deeply the
ifs and the elses can be nested.
Forms of if
The if statement can take any of the following forms:
(a) if ( condition )
do this ;

(b) if ( condition )
{
do this ;
and this ;
}

(c) if ( condition )
do this ;
else
do this ;

(d) if ( condition )
{
do this ;
and this ;
}
else
{
do this ;
and this ;
}

(e) if ( condition )
do this ;
else
{
if ( condition )
do this ;
else
{
do this ;
and this ; }}
(f) if ( condition )
{
if ( condition )
do this ;
else
{
do this ;
and this ;
}
}
else
do this ;

Use of Logical Operators


JAVA allows usage of three logical operators, namely, &&, || and !.
These are to be read as ‘AND’ ‘OR’ and ‘NOT’ respectively.
There are several things to note about these logical operators. Most
obviously, two of them are composed of double symbols: || and
&&. Don’t use the single symbol | and &. These single symbols
also have a meaning. They are bitwise operators, which we would
examine in Future examples..
The first two operators, && and ||, allow two or more conditions
to be combined in an if statement. Let us see how they are used in
a program. Consider the following example.

Example : The marks obtained by a student in 5 different


subjects are input through the keyboard. The student gets a
division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 – Fail
Write a program to calculate the division obtained by the student.
There are two ways in which we can write a program for this
example.

These methods are given below.


public class Main
{
public static void main(String args[])
{
int m1,m2,m3,m4,m5,per;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter marks five subject marks”);
m1=sc.nextInt();
m2=sc.nextInt();
m3=sc.nextInt();
m4=sc.nextInt();
m5=sc.nextInt();

per=(m1+m2+m3+m4)*100/500;
if(per>=60)
System.out.println(“First division”);
else
{
if(per>=50)
System.out.println(“Second division”);
else
{
if(per>=40)
System.out.println(“Third division”);
else
System.out.println(“Fail”);
}
}
}
}
This is a straight forward program. Observe that the program uses
nested if-elses. This leads to three disadvantages:
(a) As the number of conditions go on increasing the level of indentation also
goes on increasing. As a result the whole program creeps to the right.
(b) Care needs to be exercised to match the corresponding ifs and elses.
(c)Care needs to be exercised to match the corresponding pair of braces.

All these three problems can be eliminated by usage of ‘Logical operators’. The
following program illustrates this.
public class Main
{
public static void main(String args[])
{
int m1,m2,m3,m4,m5,per;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter marks five subject marks”);
m1=sc.nextInt();
m2=sc.nextInt();
m3=sc.nextInt();
m4=sc.nextInt();
m5=sc.nextInt();
per=(m1+m2+m3+m4)*100/500;
if(per>=60)
System.out.println(“First division”);

if(per>=50&&per<60)
System.out.println(“Second division”);

if(per>=40&&per<50)
System.out.println(“Third division”);

if(per<40)
System.out.println(“Fail”);
}
}
As can be seen from the second if statement, the && operator is
used to combine two conditions. ‘Second division’ gets printed if
both the conditions evaluate to true. If one of the conditions
evaluate to false then the whole thing is treated as false.
Two distinct advantages can be cited in favour of this program:
(a) The matching (or do I say mismatching) of the ifs with their
corresponding elses gets avoided, since there are no elses in this program.
(b) In spite of using several conditions, the program doesn't creep to the right.
In the previous program the statements went on creeping to the right. This
effect becomes more pronounced as the number of conditions go on
increasing. This would make the task of matching the ifs with their
corresponding elses
And matching of opening and closing braces that much more difficult.
The else if Clause
There is one more way in which we can write program for Example. This
involves usage of else if blocks as shown below:
public class Main
{
public static void main(String args[])
{
int m1,m2,m3,m4,m5,per;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter marks five subject marks”);
m1=sc.nextInt();
m2=sc.nextInt();
m3=sc.nextInt();
m4=sc.nextInt();
m5=sc.nextInt();
per=(m1+m2+m3+m4)*100/500;
if ( per >= 60 )
printf ( "First division" ) ;
else if ( per >= 50 )
printf ( "Second division" ) ;
else if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "fail" ) ;
}
}
You can note that this program reduces the indentation of the
statements. In this case every else is associated with its previous if.
The last else goes to work only if all the conditions fail. Even in
else if ladder the last else is optional.
Note that the else if clause is nothing different. It is just a way of
rearranging the else with the if that follows it. This would be
evident if you look at the following code:

if ( i == 2 )
printf ( "With you…" ) ;
else {
if ( j == 2 )
printf ( "…All the time" ) ;
}
if(i==2)
printf ( "With you…" ) ;
else if ( j == 2 )
printf ( "…All the time" ) ;

Another place where logical operators are useful is when we want


to write programs for complicated logics that ultimately boil down
to only two answers. For example, consider the following
example:
A company insures its drivers in the following cases:
− If the driver is married.
− If the driver is unmarried, male & above 30 years of age.
− If the driver is unmarried, female & above 25 years of age.
In all other cases the driver is not insured. If the marital status, sex and age of the driver are
the inputs, write a program to determine whether the driver is to be insured or not. Here
after checking a complicated set of instructions the final output of the program would be
one of the two—Either the driver should be ensured or the driver should not be ensured. As
mentioned above, since these are the only two outcomes this problem can be solved using
logical operators. But before we do that let us write a program that does not make use of
logical operators.
public class Main
{
public static void main(String args[])
{
char sex, ms ; int age ;
Scanner sc= new Scanner(System.in);
System.out.println(“Enter age, sex, marital status”);
age=sc.nextInt();
sex=sc.next().charAt(0);
ms=sc.next().charAt(0);
if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) ||
( ms == 'U' && sex == 'F' && age > 25 ) )
System.out. println ( "Driver is insured" ) ;
else
System.out. println ( "Driver is not insured" ) ;
}
}
In this program it is important to note that:
− The driver will be insured only if one of the conditions
enclosed in parentheses evaluates to true.
− For the second pair of parentheses to evaluate to true, each
condition in the parentheses separated by && must evaluate to
true.
− Even if one of the conditions in the second parentheses
evaluates to false, then the whole of the second parentheses
evaluates to false.
− The last two of the above arguments apply to third pair of
parentheses as well.
Thus we can conclude that the && and || are useful in the
following programming situations:
(a) When it is to be tested whether a value falls within a
particular range or not.
(b) When after testing several conditions the outcome is only one
of the two answers (This problem is often called yes/no
problem).
There can be one more situation other than checking ranges or
yes/no problem where you might find logical operators useful. The
following program demonstrates it.

Write a program to calculate the salary as per the following table:


class Main
{
public static void main(String arg[] )
{
char g ;
int yos, qual, sal ;
System.out.println ( "Enter Gender, Years of Service and Qualifications ( 0 =
G, 1 = PG ):" ) ;
g=sc.next().charAt(0);
yos=sc.nextInt();
qual=sc.nextInt();
if ( g == 'm' && yos >= 10 && qual == 1 )
sal = 15000 ;
if ( ( g == 'm' && yos >= 10 && qual == 0 ) ||
( g == 'm' && yos < 10 && qual == 1 ) )
sal = 10000 ;
else if ( g == 'm' && yos < 10 && qual == 0 )
sal = 7000 ;
else if ( g == 'f' && yos >= 10 && qual == 1 )
sal = 12000 ;
else if ( g == 'f' && yos >= 10 && qual == 0 )
sal = 9000 ;
else if ( g == 'f' && yos < 10 && qual == 1 )
sal = 10000 ;
else if ( g == 'f' && yos < 10 && qual == 0 )
sal = 6000 ;
System.out.println ( "Salary of Employee "+sal ) ;
}
}

The ! Operator
So far we have used only the logical operators && and ||. The third logical
operator is the NOT operator, written as !. This operator reverses the result of
the expression it operates on. For example, if the expression evaluates to a
non-zero value, then applying ! operator to it results into a 0. Vice versa, if the
expression evaluates to zero then on applying ! operator to it makes it 1, a
non-zero value. The final result (after applying !) 0 or 1 is considered to be false
or true respectively. Here is an example of the NOT operator applied to a
relational expression.

! ( y < 10 )

This means “not y less than 10”. In other words, if y is less than 10, the
expression will be false, since ( y < 10 ) is true. We can express the same
condition as ( y >= 10 ). The NOT operator is often used to reverse the logical
value of a single variable, as in the expression

if ( ! flag )
This is another way of saying
if ( flag == 0 )

Does the NOT operator sound confusing? Avoid it if you want, as the same
thing can be achieved without using the NOT operator
Hierarchy of Operators Revisited
Since we have now added the logical operators to the list of operators we
know, it is time to review these operators and their priorities. summarizes the
operators we have seen so far. The higher the position of an operator is in the
tabe , higher is its priority.

The Conditional Operators


The conditional operators ? and : are sometimes called ternary operators since
they take three arguments. In fact, they form a kind of foreshortened if-then-
else. Their general form is,
expression 1 ? expression 2 : expression 3
What this expression says is: “if expression 1 is true then the value returned
will be expression 2, otherwise the value returned will be expression 3”. Let us
understand this with the help of a few examples:
(A) int x, y ;
x=sc.nextInt();
y=(x>5?3:4);
This statement will store 3 in y if x is greater than 5,
otherwise it will store 4 in y.
The equivalent if statement will be,
if ( x > 5 )
y=3;
else
y=4;

(B) char a ;
int y ;
a=sc.next().charAt(0);
y = ( a >= 65 && a <= 90 ? 1 : 0 ) ;
Here 1 would be assigned to y if a >=65 && a <=90 evaluates to
true, otherwise 0 would be assigned.

(C) int a=sc.nextInt();


int b=sc.nextInt();
int big=a>b?a:b;
System.out.println(big);
(D) Nested conditional operators
int a,b,c;
int big=a>b&&a>c?a:b>c?b:c;
System.out.println(big);

You might also like