You are on page 1of 18

Study Guide in FM-AA-CIA-15 Rev.

0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Module No. 3
MODULE TITLE

DECISION CONTROL STRUCTURES

MODULE OVERVIEW

In the previous lessons, we have given examples of sequential programs, wherein statements are
executed one after another in a fixed order. In this lesson, we will be discussing control
structures, which allows us to change the ordering of how the statements in our programs are
executed.

LEARNING OBJECTIVES

At the end of the lesson, the student should be able to:


 Plan decision-making logic
 Make decisions with if and if...else structures
 Use multiple statements in an if and if...else structures
 Use the switch statement

LEARNING CONTENTS

Decision Control Structures

Decision control structures are Java statements that allows us to select and execute specific
blocks of code while skipping other sections.

if statement
The if-statement specifies that a statement (or block of code) will be executed if and only if a
certain boolean statement is true.

The if-statement has the form,

if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
. . .
}

where, boolean_expression is either a boolean expression or boolean variable.

PANGASINAN STATE UNIVERSITY 4


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Figure 1: Flowchart of If-Statement

For example, given the code snippet,

int grade = 75;


if( grade > 60 ) System.out.println("Congratulations!");

or
int grade = 75;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}

Coding Guidelines:
1. The boolean_expression part of a statement should evaluate to a boolean value. That means that
the execution of the condition should either result to a value of true or a false.
2. Indent the statements inside the if-block.For example,
if( boolean_expression ){
//statement1;
//statement2;
}

if-else statement
The if-else statement is used when we want to execute a certain statement if a condition is true,
and a different statement if the condition is false.
The if-else statement has the form,
if( boolean_expression ){
statement1;
statement2;
. . .
}
else{
statement1;
statement2;
. . .

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Figure 2: Flowchart of If-Else Statement

For example, given the problem and the source code for the if-else statement,

Get three exam grades from the user and compute the average of the grades. Output the average
of the three exams. Together with the average, also include a smiley face in the output if the
average is greater than or equal to 75, otherwise output :-(. Use BufferedReader to get input from
the user, and System.out to output the result.

import java.io.*;
/**
* Gets three number inputs from the user
* then displays the average on the screen
*/
public class Grades {
public static void main(String[] args){

//declares the variable reader as the


BufferedReader reader = new BufferedReader( new
InputStreamReader( System.in));

int firstGrade = 0;
int secondGrade = 0;
int thirdGrade = 0;
double average = 0;

try{
System.out.print("First grade: ");
firstGrade = Integer.parseInt(reader.readLine());

System.out.print("Second grade: ");


secondGrade = Integer.parseInt(reader.readLine());

System.out.print("Third grade: ");


thirdGrade = Integer.parseInt(reader.readLine());

PANGASINAN STATE UNIVERSITY 6


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

}catch( Exception e){


System.out.println("Input is invalid");
System.exit(0);
}
//solves for the average
average = (firstGrade+secondGrade+thirdGrade)/3;

//prints the average of the three exams


System.out.print("Average: "+average);

if(average>=75)
System.out.print(" Congratulations, you passed! :)");
else
System.out.print("Sorry, you failed!:( ”);

}
}

Example 2 – The following program determines an employee’s weekly wages. If the hours worked
exceed 40, then wages include overtime payment. Use Scanner to get input from the user

import java.util.Scanner;
public class WeeklyWages
{

public static void main(String[] args)


{
double rate;
double hoursWorked;
double regularPay;
double overtimePay;
double wages;
final int FULL_WEEK = 40;
final double OT_RATE = 1.5;

Scanner keyboard = new Scanner(System.in);

System.out.print("How many hours did you work this week? ");


hoursWorked = keyboard.nextDouble();
System.out.println();
System.out.print("What is your regular pay rate? ");
rate = keyboard.nextDouble();

if(hoursWorked > FULL_WEEK)


{
regularPay = FULL_WEEK * rate;
overtimePay = (hoursWorked - FULL_WEEK)*OT_RATE *rate;
wages = regularPay + overtimePay;

PANGASINAN STATE UNIVERSITY 7


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

else
{
regularPay = hoursWorked * rate;
overtimePay = 0.0;
wages = regularPay + overtimePay;
}

System.out.printf("Regular pay is $%.2f %n"+ regularPay +


"\n Overtime pay is $%.2f %n" + overtimePay +"\nTotal
wages is $%.2f %n"+ wages);

}
}

Coding Guidelines:
1. To avoid confusion, always place the statement or statements of an if or if-else block inside brackets
{}.
2. You can have nested if-else blocks. This means that you can have other if-else blocks inside another
if-else block.For example,
if( boolean_expression ){
if( boolean_expression ){
. . .
}
}
else{ . . .
}

if-else if-else statement

The statement in the else-clause of an if-else block can be another if-else structures. This
cascading of structures allows us to make more complex selections.

The if-else if statement has the form,

if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else if( boolean_expression3 )
statement3;
else if( boolean_expression4 )
statement4;
.
.
.
else
statement_n;

PANGASINAN STATE UNIVERSITY 8


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Take note that you can have many else-if blocks after an if-statement. The else-block is optional
and can be omitted. In the example shown above, if boolean_expression1 is true, then the
program executes statement1 and skips the other statements. If boolean_expression2 is true,
then the program executes statement 2 and skips to the statements following statement3.

Figure 3: Flowchart of If-Else-If Statement

Sample program for if-else if-else statement

Get a number as input from the user, and output the equivalent of the number in words. The
number inputted should range from 1-10. If the user inputs a number that is not in the range,
output, "Invalid number". Use an if-else statement to solve this problem.

import javax.swing.JOptionPane;

/**
* Transforms a number input from 1-10 to words
* using if-else
*/

public class NumWords


{
public static void main(String[] args){
String msg = "";
int input = 0;

//gets the input string


input = Integer.parseInt(JOptionPane.showInputDialog
("Enter number"));

PANGASINAN STATE UNIVERSITY 9


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

//sets msg to the string equivalent of input


if(input == 1) msg = "one";

else if(input == 2) msg = "two";


else if(input == 3) msg = "three";
else if(input == 4) msg = "four";
else if(input == 5) msg = "five";
else if(input == 6) msg = "six";
else if(input == 7) msg = "seven";
else if(input == 8) msg = "eight";
else if(input == 9) msg = "nine";
else if(input == 10)msg = "ten";
else msg = "Invalid number";

//displays the number in words if with in range


JOptionPane.showMessageDialog(null,msg);
}
}

Common Errors when using the if-else statements:

1. The condition inside the if-statement does not evaluate to a boolean value. For example,
//WRONG
int number = 0;
if( number ){
//some statements here
}
The variable number does not hold a Boolean value.

2. Using = instead of == for comparison. For example,


//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
This should be written as,
//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}

3. Writing elseif instead of else if.

switch statement

Another way to indicate a branch is through the switch keyword. The switch construct allows
branching on multiple outcomes.

PANGASINAN STATE UNIVERSITY 10


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

PANGASINAN STATE UNIVERSITY 11


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

The switch statement has the form,

switch( switch_expression ){
case case_selector1:
statement1; //
statement2; //block 1
. . . //
break;
case case_selector2:
statement1; //
statement2; //block 2
. . . //
break;
. . .
default:
statement1; //
statement2; //block n
. . . //
break;
}

where, switch_expression is an integer or character expression and, case_selector1,


case_selector2 and so on, are unique integer or character constants.

When a switch is encountered, Java first evaluates the switch_expression, and jumps to the case
whose selector matches the value of the expression. The program executes the statements in
order from that point on until a break statement is encountered, skipping then to the first
statement after the end of the switch structure.

If none of the cases are satisfied, the default block is executed. Take note however, that
the default part is optional. A switch statement can have no default block.

Let’s Remember

 Unlike with the if statement, the multiple statements are executed in the switch
statement without needing the curly braces.

 When a case in a switch statement has been matched, all the statements associated with
that case are executed. Not only that, the statements associated with the succeeding
cases are also executed.

To prevent the program from executing statements in the subsequent cases, we use a break
statement as our last statement.

PANGASINAN STATE UNIVERSITY 12


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Coding Guidelines:
1. Deciding whether to use an if statement or a switch statement is a judgment call. You can decide
which to use, based on readability and other factors.
2. An if statement can be used to make decisions based on ranges of values or conditions, whereas a
switch statement can make decisions based only on a single integer or character value. Also, the
value provided to each case statement must be unique.

Source code for switch statement

import java.io.*;

//Transforms a number input from 1-5 to words using the switch statement

public class NumWords {


public static void main(String[] args){

//declares the variable reader as the


BufferedReader reader = new BufferedReader( new
InputStreamReader( System.in));

int input = 0;
try{
System.out.print("Enter a number: ");
input= Integer.parseInt(reader.readLine());

switch (input ){
case 1:
System.out.print("One");
break;
case 2:
System.out.print("Two");
break;
case 3:
System.out.print("Three");
break;
case 4:
System.out.print("Four");
break;
case 5:
System.out.print("Five");
break;
default:
System.out.print("Invalid number");
break;
}
}
}
}

PANGASINAN STATE UNIVERSITY 13


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

LEARNING POINTS

 Making decision involves choosing between two alternative courses of action based on some
value within a program.
 The decision-control structures use Boolean expression. Selection structures can be one
alternative or if statement, two alternatives or the if-else statement, and three or more
alternatives or the if-else if …else statement.
 Decision control structure can be nested
 The decision control structure uses relational or logical operators.
 The switch statement test a single variable against a series of exact integer, character or string
values.
LEARNING ACTIVITIES

SKILLS WARM-UP
True or False. Write your answer in the space provided.

________1. Every if statement must be accompanied by an else statement.

________2. Including a semicolon before the action statement in a one-way selection causes a
syntax error.

________3. The output of the Java code

int num = 15;

if (num <= 15)


if (num >= 0)
System.out.println("Num is between 0 and 15");
else
System.out.println("Num is greater than 15");

is: Num is between 0 and 15

________4. The expression (x >= 0 && x <= 100) evaluates to false if either x < 0 or x >= 100.

________5. An else statement must be paired with an if statement.

________6. All switch structures include default cases.

________7. In Java, case and switch are reserved words, but break is not a reserved word.

________8. All switch cases include a break statement.

________9. The execution of a break statement in a switch statement terminates the switch
statement.

PANGASINAN STATE UNIVERSITY 14


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

________10. A program uses selection to implement a branch.

SKILLS WORKOUT
Multiple Choice: Encircle the letter that corresponds to the correct answer.

int x, y;
if (x < 4)
y = 2;
else if (x > 4)
{
if (x > 7)
y = 4;
else
y = 6;
}
else
y = 8;

1. Based on the code above, what is the value of y if x = 5?

a. 2 c. 6
b. 4 d. 8

2. Based on the code above, what is the value of y if x = 4?

a. 2 c. 6
b. 4 d. 8

3. Based on the code above, what is the value of y if x = 9?

a. 2 c. 6
b. 4 d. 8

4. Based on the code above, what is the value of y if x = 5?

a. 2 c. 6
b. 4 d. 8

5. Based on the code above, what is the value of y if x = 1?

a. 2 c. 6
b. 4 d. 8

6. Based on the code above, if the value of y is found to be 6, what is a possible value of x?

a. 4 c. 10
b. 6 d. 12

7. What is the output of the following Java code?

PANGASINAN STATE UNIVERSITY 15


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

int x = 57;
int y = 3;

switch (x % 9)
{
case 0:
case 1:
y++;
case 2:
y = y - 2;
break;
case 3:
y = y + 2;
case 4:
break;
case 5:
case 6:
y = y + 3;
}
System.out.println(y);

a. 2 c. 6
b. 5 d. None of these

8. Which of the following will cause a syntax error, if you are trying to compare x to 5?

a. if (x == 5) c. if (x <= 5)
b. if (x = 5) d. if (x >= 5)

9. Suppose that you have the following code:

int sum = 0;
int num = 8;

if (num < 0)
sum = sum + num;
else if (num > 5)
sum = num + 15;

After this code executes, what is the value of sum?


a. 0 c. 15
b. 8 d. 23

10. Assuming a variable f has been initialized to 5, which of the following statements sets g to 0?

a. if(f > 6 || f == 5) g = 0; c. if(f < 3 || f > 4) g = 0;


b. if(f >= 0 || f < 5) g = 0; d. All of the above statements set g to 0

PANGASINAN STATE UNIVERSITY 16


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Hands-on Activity
1. Write a program that would input the year and then indicate whether that year is a leap
year or not.

PANGASINAN STATE UNIVERSITY 17


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Hands-on Activity
2. Write an application that prompts an employee for an hourly pay rate and hours worked.
Compute gross pay (hours times rate), withholding tax, and net pay (gross pay minus
withholding tax). Withholding tax is computed as a percentage of gross pay based on the
following:

Gross Pay (Php) Withholding (%)


0 to 2000.00 10
2001 to 4000 12
4001 to 10000 15
10001 and over 20

PANGASINAN STATE UNIVERSITY 18


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Hands-on Activity
3. To avail of a college scholarship, an applicant must provide three figures: his NSAT score,
monthly salary of his parents, and entrance examination score. The college may either
decide to accept, reject, or further study his application based on the following conditions:
Rejected is any of the following exists:
a. Parents’ salary is above 10,000
b. NSAT score is below 90
c. Entrance exam score is below 85

Accepted if all of the following are met:


a) Parents’ salary is at most 3,500
b) Average of NSAT and entrance exam is at least 91

Any application which is neither accepted nor rejected will be subjected for further study.
Make a program that would input the NSAT score, parents’ salary and entrance exam score
and then output whether the applicant is accepted, rejected or for further study.

PANGASINAN STATE UNIVERSITY 19


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Hands-on Activity
4. An applicant will accepted to the Jedi Knight Military Academy is he is least 200 cm. tall;
age is between 21 and 25, inclusive; and a citizen of the Planet Endor. However, if the
applicant is a recommendee of Jedi Master Obi Wan, he is accepted automatically
regardless of his height, age and citizenship. Write a program that would input the
applicant’s height, age, citizenship code(“C” for citizen of Endor, “N” for non-citizen), and
recommendee code (“R” for recommendee, “N” for non-recommendee) and then output
whether the applicant is accepted or rejected.

PANGASINAN STATE UNIVERSITY 20


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

REFERENCES

1. Farrel, Joyce, “Java Programming 9ed”, Course Technology, Cengage Learning


2. Cervantes, Julio, “Module in Java Programming”, Pangasinan State University.

PANGASINAN STATE UNIVERSITY 21

You might also like