Module 3
Module 3
0 03-June-2020
Module No. 3
MODULE TITLE
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
LEARNING CONTENTS
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.
if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
. . .
}
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;
. . .
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){
int firstGrade = 0;
int secondGrade = 0;
int thirdGrade = 0;
double average = 0;
try{
System.out.print("First grade: ");
firstGrade = Integer.parseInt(reader.readLine());
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
{
else
{
regularPay = hoursWorked * rate;
overtimePay = 0.0;
wages = regularPay + overtimePay;
}
}
}
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{ . . .
}
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.
if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else if( boolean_expression3 )
statement3;
else if( boolean_expression4 )
statement4;
.
.
.
else
statement_n;
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.
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
*/
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.
switch statement
Another way to indicate a branch is through the switch keyword. The switch construct allows
branching on multiple outcomes.
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;
}
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.
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.
import java.io.*;
//Transforms a number input from 1-5 to words using the switch statement
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;
}
}
}
}
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.
________2. Including a semicolon before the action statement in a one-way selection causes a
syntax error.
________4. The expression (x >= 0 && x <= 100) evaluates to false if either x < 0 or x >= 100.
________7. In Java, case and switch are reserved words, but break is not a reserved word.
________9. The execution of a break statement in a switch statement terminates the switch
statement.
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;
a. 2 c. 6
b. 4 d. 8
a. 2 c. 6
b. 4 d. 8
a. 2 c. 6
b. 4 d. 8
a. 2 c. 6
b. 4 d. 8
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
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)
int sum = 0;
int num = 8;
if (num < 0)
sum = sum + num;
else if (num > 5)
sum = num + 15;
10. Assuming a variable f has been initialized to 5, which of the following statements sets g to 0?
Hands-on Activity
1. Write a program that would input the year and then indicate whether that year is a leap
year or not.
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:
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
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.
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.
REFERENCES