Conditional Statements

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Version : 2nd Draft

CHAPTER 2
Conditional Statements

Prepared by
Manoranjan Parhi,
Swadhin Kumar Barisal

Learning Outcomes
Upon successful completion of this chapter, students should be able to:
1. define a condition for any decision making problem. (Section 2.1)
2. identify the attributes and values associated with the given condition.
(Section 2.2, 2.3,2.4,2.5)
3. state and explain the syntax and semantics of different conditional
statements in Java. (Section 2.2, 2.3,2.4,2.5)
4. analyze and explain the behavior of the decision making problem
involving the control flow diagram, pseudo code and java statements.
(Section 2.2, 2.3,2.4,2.5)

Contents

Conditional Statements
2.1 Motivation . . . . . . . . . . . . . . . . .
2.2 Single Attribute and Single Value . . . .
2.3 Single Attribute and Multiple Values . .
2.4 Multiple Attributes and Single Value . .
2.5 Multiple Attributes and Multiple Values
2.6 Exercises . . . . . . . . . . . . . . . . . .
Minor Assignments . . . . . . . . . . .
Major Assignment . . . . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

2-1
2-1
2-1
2-4
2-11
2-13
2-17
2-20
2-23

CHAPTER 2
Conditional Statements

2.1

Motivation

In order to solve any decision making problem, we are interested to perform


certain action depending on whether certain condition is true or false. First
we have to identify the attribute and value associated with the given condition
and then determines the action after evaluation of the condition (True or
False). There are 4 possible combinations of attribute/value pairs.
Single Attribute and Single Value
Single Attribute and Multiple Values
Multiple Attributes and Single Value
Multiple Attributes and Multiple Values

2.2

Single Attribute and Single Value

Let us consider a problem statement as follows.


Problem Statement-1:
A university conducts an examination of 100 marks in a subject named as ICP. If the
marks secured by a student in ICP is greater than or equal to 40 then print he/she
is pass in ICP.
First we have to find out the attribute and value associated with given
condition in the above problem.
Here,
Attribute: mark
Value:>= 40
Condition: (mark>=40)
Action: He/She is pass in ICP

2-1

We can show the control flow of the stated problem as follows.


Control Flow Diagram:

mark40

He/She is pass in ICP

Stop

Pseudo Code:
step 1: Input the mark secured by the student in ICP
step 2: If the mark of ICP is greater than or equal to 40 then
Print He/She is pass in ICP
Otherwise
Exit
In Java the above problem statement can be represented with the help of
simple if statement.
if Statement Syntax :
if (condition)
{
statement(s);
}

Java Statement:
if (marks >= 40)
{
System.out.println("He/She is pass in ICP");
}

Let the problem to be redefined as follows.


Problem Statement-2:
A university conducts an examination of 100 marks in a subject named as ICP. If the
marks secured by a student in ICP is greater than or equal to 40 then print he/she
is pass in ICP otherwise print he/she is fail in ICP.
Control Flow Diagram:

mark40

He/She is pass in ICP

He/She is fail in ICP

Pseudo Code:
step 1:Input the mark secured by the
step 2:If the mark of ICP is greater
Print He/She is pass in
Otherwise
Print He/She is fail in

student in ICP
than or equal to 40 then
ICP
ICP

In Java the above problem statement can be represented with the help of
if-else statement.
if-else Statement Syntax :
if ( condition )
{
statement(s);
}
else
{
statement(s);
}
Java Statement:
if (marks >= 40)
{
System.out.println("He/She is pass in ICP");

}
else
{
System.out.println (\He/She is fail in ICP.");
}

Practice Questions
1. A Gramya bank gives housing loan only to indians. Find the attribute
and value associated with the said problem statement and draw the
control flow diagram. Finally write the pseudo code and implement
using java syntax.
2. A candidate can apply for an oil company only having a GATE score. Find
the attribute and value associated with the said problem statement and
draw the control flow diagram. Finally write the pseudo code and
implement using java syntax.
3. Siksha 0 Anusandhan University allows the applicants to take admission if
they have SAAT rank only.Find the attribute and value associated with
the said problem statement and draw the control flow diagram. Finally
write the pseudo code and implement using java syntax.
4. I can purchage a mobile if that mobile price is less than Rs. 10000. Find
the attribute and value associated with the said problem statement and
draw the control flow diagram. Finally write the pseudo code and
implement using java syntax.

2.3

Single Attribute and Multiple Values

Let us consider a problem statement as follows.


Problem Statement-1:
Let 3 types of passengers are travelling in a bus. The category of each
passenger is defined as follows.
If the age of the person is less than 18 then print the person is Minor
otherwise
If the age of the person is greater than or equal to 18 and less than 60
then print the person is Adult otherwise
If the age of the person is greater than or equal to 60 then print the
person is Senior citizen. We have to determine the category of each
passenger in the bus.
Here,
Attribute: age,
Value: <18,
>=18 and <60, >=60,

We can show the control flow of the stated problem as follows.


Control Flow Diagram:

start

age<18

Minor

age18
AND

age<60

Adult
age60

Senior Citizen

Stop

Pseudo Code:
Step 1:Input the age of the person
step 2:If the age of the person is less than 18 then
Print the person is Minor
Otherwise
If the age of the person is greater than or
equal to 18 and less than 60 then
Print the person is Adult.
Otherwise
If the age of the person is greater than
or equal to 60 then
Print the person is Senior Citizen.
Otherwise
Exit

We can draw the truth table for the condition age18 AND age<60
Truth Table:
age18
T
T
F
F

age<60
T
F
T
F

(age18) && (age<60)


T
F
F
F

Here the logical operator && is used for AND operation.

There are three so-called logical operators that operate on the Boolean
conditions:
Operator
&&
||
!

Meaning
Logical AND
Logical OR
Logical NOT

Example
(x 1) && (x 100)
(x < 1) || (x > 100)
!(x == 8)

Truth Table for logical AND


A
T
T
F
F

B
T
F
T
F

A && B
T
F
F
F

Truth Table for logical OR


A
T
T
F
F

B
T
F
T
F

A || B
T
T
T
F

Truth Table for logical NOT


A
T
F

!A
F
T

In Java the above problem statement can be represented with the help of if
else if ladder statement.
if-else-if ladder statement Syntax:
if(condition1)
{
statement 1;
}
else if (condition2)
{
statement 2;
}
else if (condition 3)
{
statement 3;
}
else
{
statement 4;
}
Java Statement:
if(age<18)
System.out.println("The person is Minor");
else if(age>18 && age<60)
System.out.println("The person is Adult");
else if(age>=60)
System.out.println ("The person is Senior citizen");
else
{
System.exit(0);
}

Let us consider another problem as follows.


Problem Statement-2:
Enter a number to represent the day of the week.
Example: if the inputted number is 1 then the day is SUNDAY Similarly, if
the inputted number is 2 then the day is MONDAY and so on.
if the inputted number does not lie between 1 to 7 then print Wrong Choice.
We can show the control flow of the stated problem as follows.
Control Flow Diagram:

Start

Read a number

T
number==1

SUNDAY

F
T
number==2

MONDAY

F
T
number==3

TUESDAY

F
T
WEDNESDAY

number==4

F
T
THURSDAY

number==5
F
T

FRIDAY

number==6

F
T
number==7
F
Wrong Choice

Stop

SATURDAY

Pseudo Code:
Step 1: Input a number
Step 2: if number == 1
Then Print SUNDAY
Otherwise
if number
Then Print MONDAY
Otherwise
if number
Then Print TUESDAY
Otherwise
if number
Then Print WEDNESDAY
Otherwise
if number
Then Print THURSDAY
Otherwise
if number
Then Print FRIDAY
Otherwise
if number
Then Print SATURDAY
Otherwise
Print wrong choice

== 2

== 3

== 4

== 5

== 6

== 7

In Java the above problem statement can be represented with the help of
switch statement.
switch statement Syntax:
switch (expression)
{
case value1:
statement(s)
// when expression == value1;
break;
case value2:
statement(s)
//when expression == value2;
break;
case value3:
statement(s)
//when expression == value3;
break;
default:
statement(s) //if no previous match;
}
A break statement is used as the last statement in each cases statement
list. The break statement causes the switch statement to end and control to
transfer to the end of the switch statement. The program continues executing
with the statement that follows the switch statement. A switch statement
can have an optional default case.

Java Statement:
int number = 3;
switch (number)
{
case 1:
System.out.println ("SUNDAY.");
break;
case 2:
System.out.println ("MONDAY ");
break;
case 3:
System.out.println ("TUESDAY ");
break;
case 4:
System.out.println ("WEDNESDAY ");
break;
case 5:
System.out.print ("THURSDAY ");
break;
case 6:
System.out.print ("FRIDAY ");
break;
case 7:
System.out.print ("SATURDAY ");
break;
default :
System.out.println ("wrong choice ");
}

Practice Questions
1. A Gramya bank announces to give bonus to employees whose salary is greater
than 5000 and less than 10000.Find the attribute and value associated
with the said problem statement and draw the control flow diagram.
Finally write the pseudo code and implement using java syntax.
2. If your GATE score is greater than 900 and less than 1000 then you may be
allowed for interview directly without any written test. Find the attribute
and value associated with the said problem statement and draw the
control flow diagram. Finally write the pseudo code and implement
using java syntax.
3. If your SAAT rank lies between 500 to 1000 then there is a possibility to get
Computer Science Branch. Find the attribute and value associated with
the said problem statement and draw the control flow diagram. Finally
write the pseudo code and implement using java syntax.
4. If you have rupees more than 10000 and less than 15000 then you can
purchase MOTO G mobile . Find the attribute and value associated with
the said problem statement and draw the control flow diagram. Finally
write the pseudo code and implement using java syntax.

2.4

Multiple Attributes and Single Value

Let us consider a problem statement as follows.


Problem Statement-1:
Input the percentage of the theory and lab attendance of a student. If the
theory attendance is greater than or equal to 75 percentage and the lab
attendance is greater than or equal to 75 percentage, then the student is
eligible to appear the semester examination otherwise the student is not
allowed to appear the exam.
Here,
Attribute: - Theory attendance, Lab attendance
Values: - 75
Pseudo Code:
step 1: Input the Theory-attendance and Lab-attendance of
a student.
step 2: If the Theory-attendance is greater than or equal to 75
and Lab-attendance is greater than or equal to 75
Then Print Eligible to appear semester exam.
Otherwise
Then Print Not Eligible to appear semester exam.

We can show the control flow of the stated problem as follows.


Control Flow Diagram:

Theory-Attendance75
AND
Lab-Attendance75

Not eligible to appear the

Eligible to appear the

Semester Examination

Semester Examination

Truth Table:
TA75
T
T
F
F

LA75
T
F
T
F

(TA75) && (LA75)


T
F
F
F

Java Statement:
if((Theory_attendance>=75) && (Lab_attendance>=75))
System.out.println("Student is eligible to
appear semester exam");
else
System.out.println("Student is not eligible to
appear semester exam ");

Practice Question
1. if the water temperature is less than 10-degree C and the air temperature
is less than 10-degree C then the weather is snowy otherwise the weather
is pleasant. Find the attributes and values associated with the said
problem statement and draw the control flow diagram and truth table.
Finally write the pseudo code and implement using java syntax.

2.5

Multiple Attributes and Multiple Values

Let us consider a problem statement as follows.


Problem Statement-1:
If the CGPA of a student is greater than or equal to 9 and theory attendance
is greater than or equal to 75 percentage or behavior is good then he/she can
appear Infosys campus recruitment drive without any written test.
Here,
Attribute: - CGPA, Behavior, Theory-attendance
Value: - Greater than or equal to 9, Good, Greater than or equal to 75
We can show the control flow of the stated problem as follows.

Control Flow Diagram:

CGPA9 AND Theory-Attendance75


OR
Behavior==good

Appear Infosys Campus

Stop

without any written test

Pseudo Code:
step 1:Input the Theory-attendance and CGPA and behavior
of a student.
step 2:If CGPA is greater than or equal to 9 and Theory-attendance
is greater than or equal to 75 or behavior is equal to good then
Print Eligible to appear Infosys campus without
any Written test.
Otherwise
Exit.
Truth Table:
Let CGPA 9 represents A
Theory-attendance 75 represents B

Behavior = = good represents C


A
T
T
T
T
F
F
F
F

B
T
T
F
F
T
T
F
F

C
T
F
T
F
T
F
T
F

(A && B)||C
T
T
T
F
T
F
T
F

Java Statement:
import java.util.Scanner;
public class CGPA
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the CGPA");
int a=sc.nextInt();
System.out.println("Enter the behavoiur");
String s=sc.next();
System.out.println("Enter the theory attendance");
int x=sc.nextInt();
String str="GOOD";
if((a>=9 && x>=75) || (s.equalsIgnoreCase(str)))
System.out.println("Can appear Infosys campus without any written test");
}
}

Let us consider another problem statement for multiple attributes and


multiple values.
Problem Statement-2:
Find the largest among three numbers.

We can show the control flow of the stated problem as follows.

Control Flow Diagram:

Start

Input A, B, C

T
A>B

B>C

Print B is largest number

T
A>C

Print C is largest number

Print A is largest number

Stop

Pseudo Code:
step 1: Input three numbers A, B, C
step 2: if A is greater than B then
If A is greater than C then
Print A is largest
Otherwise
Print C is largest
Otherwise
If B is greater than C then
Print B is largest
Otherwise
Print C is largest

Java Statement:
if(A>B)
{
if(A>C)
max=A;
else
max=C;
}
else
{
if(B>C)
max=B;
else
max=C;
}
System.out.println(max);

Practice Questions
1. A bank gives special ROI (10 %) only to those customers whose citizenship
is Indian and gender is female.Find the attribute and values associated
with the said problem statement and draw the control flow diagram
and truth table. Finally write the pseudo code and implement using
java syntax.
2. A candidate will get selected in an Oil company directly (without any written
exam) if his category is SC or ST and has GATE score more than 90 %. Find
the attributes and values associated with the said problem statement
and draw the control flow diagram and truth table. Finally write the
pseudo code and implement using java syntax.
3. A bank awards rank of an employee to officer rank and grade pay 10000 if
his year of experience is more than 10 years and having a very good character
certificate. Find the attributes and values associated with the said
problem statement and draw the control flow diagram and truth table.
Finally write the pseudo code and implement using java syntax.
4. if temperature is less than 25-degree C and greater than 10-degree C or
humidity is less than 90 % then the day is dry otherwise if temperature
is greater than 25-degree C and less than 35-degree C and humidity is
greater than 90 % then the day will be cloudy or the day is sunny. Find
the attributes and values associated with the said problem statement
and draw the control flow diagram and truth table. Finally write the
pseudo code and implement using java syntax.

2.6

Exercises

1. Identify the attribute and value of the following control flow diagram.
Write the pseudo code and express in terms of java statement.

height6

The Person is tall.

Stop

2. Identify the attribute and value of the following problem statement


and fill up the control flow diagram and also write the pseudo code.
Problem Statement: Input the mark of a student. If the student mark is
greater than or equal to 40, it generates the following message. Congratulation! You have passed the exam. Otherwise the output message
is Sorry! You have failed the exam.

3. Write the pseudo code and java statement that reads the temperature of
a given day and prints a message according to the following conditions
in the table.
temp (degree-C)
40
30 AND <40
20 AND <30
<20

Message
The day is extreamly hot
The day is hot
The day is normal
The day is cold

4. Convert the following control flow diagram into pseudo code and
implement using java statements.
Start

water-temp 0

water-temp>0

Frozen

AND
water-temp<100
T

Liquid

water-temp100

F
Steam

Exit

5. Write a java program that reads the lengths of the three sides of
a triangle and determines the type of the triangle according to the
following pseudo code.
Step 1: Input the length of three sides of a triangle
Step 2: compare each pair of sides and count how many
pairs are equal
Step 3: if the number of equal pairs is 0 then
it is irregular
otherwise if the number of equal pairs is 1
it is symmetric
otherwise
it is regular
6. Identify the attributes and corresponding values of the following problem statement and also represent the information on a flow diagram.
Implement using java statements.

Problem Statement: If a cricket player scores greater than or equal


to 50 and takes more than 3 wickets in a match then print the player is
all rounder.
7. Identify the attributes and corresponding values of the following problem statement and also represent the information on a flow diagram.
Finally write the pseudo code and implement using java syntax.
Problem Statement: If the student 10th mark is greater than or equal to 60
percentage or 12th mark is greater than or equal to 60 percentage and
B. Tech mark is greater than equal to 75 percentage then the student
is directly allow for PI (Personal Interview) round otherwise if the B.
Tech mark is greater than or equal to 60 percentage and less than 75
percentage then he/she will appear the written round otherwise he/she
is not allowed to sit in the exam.
8. Identify the attributes and corresponding values of the following problem statement and also represent the information on a flow diagram.
Draw the truth table. Finally write the pseudo code and implement
using java statement.
Problem Statement: In university examination, if the student will score
greater than equal to 75 percentage marks in compulsory paper and
greater than 65 percentage in elective paper then student will pass
with a distinction otherwise if the student will score greater than equal
40 percentage in both paper then student will only pass the exam
otherwise student will fail in the exam.
9. Write the pseudo code, control flow and java statement to check whether
a year is leap year or not.
10. Write the pseudo code, control flow and java statement to find largest
among three numbers.

Minor Assignments

1. Write a java program that determines a students grade. The program


will read three types of scores (quiz, mid-term, and final scores) and
determine the grade based on the following rules:
if
if
if
if

the
the
the
the

average
average
average
average

score=90% =>grade=A
score>= 70% and <90%=>grade=B
score>=50% and <70%=>grade=C
score<50% =>grade=F

2. Write a java program which inputs a persons height (in centimeters) and
weight (in kilograms) and outputs one of the messages: underweight,
normal, or overweight, using the following criteria:
Underweight: weight < height/2.5
Normal: height/2.5 <= weight <= height/2.3
Overweight: height/2.3 < weight
3. Write a java program which inputs one positive integer specifying
the year of birth of a person and returns an output the name of the
generation that the person is part of (X, Y, or Z ) according to the
table below. For births before 1966, return O for Old and for births
after 2012, return K for Kid.
Generation
X
Y
Z

Born
1966-1980
1981-1999
2000-2012

4. A college conducts a 100 mark exam for its student and grades them as
follows.
Marks Range
90
80 AND <90
70 AND <80
60 AND <70
50 AND <60
40 AND <50
< 40

Letter Grade
O
A
B
C
D
E
F

Assigns a grade based on the value of the marks. Show the work flow
and write the pseudo code to calculate the grades for a student. Finally
represent the pseudo code in terms of java syntax.

5. Assuming that n is 20, what will the output of the following code
fragment, when executed?
if (n >= 0)
if (n < 10)
System.out.println("n is small");
else
System.out.println("n is negative");

6. Write a java program which inputs a date in the format dd/mm/yy and
outputs it in the format month dd, year. For example, 25/12/14 becomes:
December 25, 2014
7. What will be output when you will execute following java code?
class A
{
public static void main(String args[]){
int a=100;
if(a>10)
System.out.println("M.S. Dhoni");
else if(a>20)
System.out.println("Mike Hussey");
else if(a>30)
System.out.println("A.B. de villiers");
else
System.out.println("Manoranjan Parhi");
return 0;
}
}
8. What will be output when you will execute following java code?
class B{
public static void main(String args[])
{
int x=-1,y=-1;
if(++x=++y)
System.out.println("R.T. Ponting");
else
System.out.println("C.H. Gayle");
return 0;
}
}

9. What will be output when you will execute following java code?
class C
{
public static void main(String args[])
{
int x=1,y=2;
if( (x>y) && (x!=y))
System.out.println("x= "+x+"and y="+y);
else
System.out.println("Welcome to ITER");
return 0;
}
}
10. Rewrite the following java code using switch statement:
if(ch==a || ch==A) countA++;
else if(ch=e || ch=E) countE++;
else if(ch=i || ch=I) countI++;
else if(ch=o || ch=O) countO++;
else if(ch=u || ch=U) countU++;
else System.out.println("No vowel letter");

Major Assignment

Objective of the Assignment


As all of you aware, Conditional statements allow a program to execute
a certain piece of code based on a decision. Hence, the objective of this
assignment is to give you practice in this regard and to also, through doing,
help you to better understand the use of Conditional Statements in Java.
Problem Statement
An Electricity Supply Company supplies electricity for domestic and commercial usage all over the country. You are required to write a program for
calculating the amount of bill paid by the customer for both domestic and
commercial usage. User will enter customer number and amount of units
consumed, and the program will calculate the amount of bill accordingly.
The program should take usage type (domestic/commercial) as input
which must be 1 or 2and the number of units consumed.
If the user enters 1 then he/she is a domestic user.
If the user enters 2 then he/she is a commercial user.
If user enters any other number except 1 or 2, the program should
terminate after displaying a message Invalid usage type.
After taking valid usage type from user, program should ask user to
enter the customer number, number of units consumed and number of
days.
The power tariff is as follows.
No of units consumed
300
100AND < 300
> 0AND < 100

Domestic rate
Rs. 3.50
Rs. 2.50
Rs. 1.50

Commercial rate
Rs. 5.00
Rs. 3.50
Rs. 2.00

If user deposits bill within 10 days, he/she will not be incurred for any
extra charges.
If user deposits bill after 10 days, he/she will be charges for Rs. 50 as
extra charges.

Finally on the basis of usage type, customer number, consumed units


and number of days, calculate and generate the bill for the customer.
NOTE 1: For implementation use necessary conditional statement (if/if. . . else/ifelse-if Ladder/nested if. . . else/switch case) in Java.
NOTE 2: The bill can be calculated by using the following formula.
Bill=units*rate
NOTE 3: You are required to submit a java program named as ElectricityBill.java.
Please dont plagiarize.

You might also like