2. CONTROL STRUCTURES
• Statements in a program are executed
sequentially, from the first statement to the
last statement.
• Control structures provide a means for
some statements to be skipped or by-passed
during execution, depending on the result of a
condition(s).
3. • Types of Control Structures
- Sequence
- Selection (or Decision Control) Structure
- Iteration (or Repetition) Structure
CONTROL STRUCTURES
5. Control Structures - Sequence
Sequence Structure
• The simplest structure
• Control flows from one statement to the next
• Statements are executed sequentially in the order in
which they appear in the program
6. Control Structures - Sequence
Example: A program that computes and prints the net
pay of an employee contains the following code:
grossPay = 20000; // 1st statement to be
executed
netPay = grossPay – 4000; // 2nd statement to be
executed
System.out.println(“The net pay is: “ + netPay); /* 3rd
statement to be executed */
7. Selection (or Decision Control) Structure
• Provides a choice between two alternatives
• 3 components of the structure:
- A condition to be tested
- The statement to be performed if the condition is
satisfied (process A)
- The statement to be performed if the condition is
not satisfied (process B)
Control Structures - Sequence
8. Control Structures - Selection
• Entry to the structure is through the condition
• Exit is through the execution of process A or process B
9. Control Structures - Selection
• Program code for single alternative selection:
if (condition)
statement1;
or
if (condition) {
statement1;
statement2;
}
- where condition is a boolean expression or boolean
variable
10. Control Structures - Selection
• Program code for dual alternative selection:
if (condition)
statement1;
else
statement2;
- where condition is a boolean expression or
boolean variable
11. Control Structures - Selection
• Example:
int grade = 60;
if (grade > 79)
System.out.println(“Congratulations! You
passed!”); else
System.out.println(“Try harder next time.”);
12. Control Structures - Selection
Exercise 8.1
• Problem:
Write a program that would compute and
print out an employee’s net pay.
An employee’s net pay is computed as his/her
monthly salary less deductions due to
absences.
13. Control Structures - Selection
Exercise 8.1
• Solution:
- Use the tools learned in problem
definition and analysis (HIPO):
- Problem definition:
1. Is the problem clear?
2. Are there parts that are not
understood?
15. Control Structures - Selection
Exercise 8.1
• Program code:
class EmployeeNetPay {
public static void main (String [] args) {
// declare input variables and initialize
double monthlySalary = 0.0;
double deductionsDueToAbsences = 0.0;
// declare output variables and initialize
double netPay = 0.0;
16. Control Structures - Selection
Exercise 8.1 – Program code cont’d
// assign values to inputs
monthlySalary = 20000;
deductionsDueToAbsences = 4000;
// compute Net Pay
netPay = monthlySalary –
deductionsDueToAbsences;
// print Net Pay
System.out.println(“The net pay is: ” + netPay);
} // end of main method
} // end of class
17. Control Structures - Selection
Exercise 8.2
• Problem: Write a program that would compute
and print out an employee’s net pay given his
monthly salary and the number of days that he is
absent.
An employee’s net pay is computed as his/her
monthly salary less deductions due to absences.
Deductions are computed as:
daily rate * no. of days absent
18. Control Structures - Selection
Exercise 8.2
• Solution:
- Problem definition:
1. Is the problem clear?
2. Are there parts that are not understood?
- Unclear portion:
• If daily rate is a given value or not
• Assume that daily rate is given
20. Control Structures - Selection
Exercise 8.2
• Program code:
class EmployeeNetPay {
public static void main (String [] args) {
// declare input variables and initialize
double monthlySalary = 0.0;
int noOfDaysAbsent = 0;
double dailyRate = 0.0;
double deductionsDueToAbsences = 0.0;
// declare output variables and initialize
double netPay = 0.0;
21. Control Structures - Selection
Exercise 8.2 – Program code cont’d
// get inputs
monthlySalary = 20000;
noOfDaysAbsent = 2;
dailyRate = 1000;
// compute deductions
deductionsDueToAbsences = dailyRate *
noOfDaysAbsent;
// compute net pay
netPay = monthlySalary –
deductionsDueToAbsences;
22. Control Structures - Selection
Exercise 8.2 – Program code cont’d
// print Net Pay
System.out.println(“The net pay is: ” +
netPay);
} // end of main method
} // end of class
23. Control Structures - Selection
Exercise 8.2
• Test Run:
- Employee A’s monthly salary is P20,000.00 and her
daily rate is P1,000.00 a day. She has been absent for 2
days.
- Employee B’s monthly salary is P10,000.00 and his
daily rate is P500.00 a day. He has no absences.
• Will the program product correct results? - The
program will product correct results. - In terms of
efficiency, it can be improved further.
24. Control Structures - Selection
Exercise 8.2
• The HIPO using step-wise refinement
25. Control Structures - Selection
Exercise 8.2
• Program code revised:
class EmployeeNetPay {
public static void main (String [] args) {
// declare input variables and initialize
double monthlySalary = 0.0;
int noOfDaysAbsent = 0;
double dailyRate = 0.0;
double deductionsDueToAbsences = 0.0;
26. Control Structures - Selection
Exercise 8.2 – Program code cont’d
// declare output variables and initialize
double netPay = 0.0;
// get inputs
monthlySalary = 20000;
noOfDaysAbsent = 2;
dailyRate = 1000;
28. Control Structures - Selection
Exercise 8.2 – Program code cont’d
// print Net Pay
System.out.println(“The net pay is: ” +
netPay);
} // end of main method
} // end of class
30. Control Structures - Selection
Some Common Errors
• Using > instead of >=
Example:
“Write a program that would give customers over
age 60 a discount of 20%”
- The phrase “over age 60” is not clear. Does it
include the age 60 or not? Clarify what it means.
- Similar phrases that have unclear meaning are: “not
more than”, “at least”, “not under”.
31. Conditional Expressions in Selection
Conditional Expressions
- Are an important part of selection and iteration.
Faulty conditions lead to unwanted and erroneous
results. Simulating all possible scenarios in a condition
helps achieve clarity and accurate results.
- Conditional expressions using a selection control
structure will always result to ONLY ONE of two
values: true or false.
32. Compound Conditions and
Conditional Operators
Compound Conditions
- Have more than 1 conditional expression
- The result of the compound expression depends on
the individual result of each condition
- The expressions can be joined by any of java’s
conditional operators
- Format:
(condition-1) && (condition-2)
or
(condition-1) || (condition-2)
33. • Java’s conditional operators:
&& conditional-AND
|| conditional-OR
?: ternary operator (shorthand for if-then-else
statement)
• Unary logical operator
! logical complement operator (negates the a
Boolean value)
Compound Conditions and
Conditional Operators
34. • Compound conditions joined by conditional-AND
Example:
if ((performanceRating == “E”) && (noOfDaysAbsent < 5))
performanceBonus = 10000;
- The example can also be expressed using a nested if
structure:
if (performanceRating == ‘E’)
if (noOfDaysAbsent < 5)
performanceBonus = 10000;
Compound Conditions and
Conditional Operators
35. • The truth table for && (conditional-AND)
- A truth table summarizes the outcome of a
compound condition with 2 conditional expressions
Compound Conditions and
Conditional Operators
36. • The && (conditional-AND) operator
- Supports short-circuit evaluation (or partial evaluation)
- Given an expression:
condition-1 && condition-2
- && will evaluate condition-1 and immediately return a
false value if condition-1 is false
- condition-2 is never evaluated because the result will
be false regardless of the value of conditions
Compound Conditions and
Conditional Operators
37. • Conditional-AND Example:
public class TestAND {
public static void main (String [] args) {
int i = 0; int j = 10;
boolean test = false;
// demonstrate &&
test = (i > 10) && (j++ < 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}
Compound Conditions and
Conditional Operators
38. • The output of the program is:
0
10
false
Compound Conditions and
Conditional Operators
39. Compound Conditions and Conditional
Operators
• Compound conditions joined by conditional-OR
Example:
if ((performanceRating == “E”) || (performanceRating
==“VS”))
performanceBonus = 10000;
- If any of the conditions result to true, the compound
condition will be true
40. • The truth table for || (conditional-OR)
Compound Conditions and
Conditional Operators
41. • The || (conditional-OR) operator
- Supports short-circuit evaluation (or partial
evaluation)
- Given an expression:
condition-1 || condition-2
- || will evaluate condition-1 and immediately return a
true value if condition-1 is true
- condition-2 is never evaluated because the result
will be true regardless of the value of condition-2
Compound Conditions and
Conditional Operators
42. • Conditional-OR Example:
public class TestOR {
public static void main (String [] args) {
int i = 0; int j = 10;
boolean test = false;
// demonstrate ||
test = (i < 10) || (j++ < 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}
Compound Conditions and
Conditional Operators
43. • The output of the program is:
0
10
true
Compound Conditions and
Conditional Operators
44. • The ?: (ternary) operator
- Takes in three arguments that form a
conditional expression
- Format:
condition-1 ? exp1 : exp2
- condition-1 must result in a boolean value. If
condition-1 is true exp1 is the value returned. If
condition-1 is false, exp2 is the value returned.
Compound Conditions and
Conditional Operators
45. • Example for Ternary ?: operator:
public class TernaryOperator {
public static void main (String [] args) {
String status = “”;
int grade = 80;
// get status of student
status = (grade >= 80) ? “Passed” : “Failed”;
System.out.println(status);
}
}
• The output of the program will be: Passed
Compound Conditions and
Conditional Operators
46. • The ! (logical NOT) operator
- Takes in one argument, which could be an expression, a
variable or a constant
- Format: !exp1
- The truth table for ! (logical NOT)
Compound Conditions and
Conditional Operators
47. • Example for ! logical NOT operator
: public class TestNOT {
public static void main (String [] args) {
boolean val1 = true;
boolean val2 = false;
System.out.println(!val1);
System.out.println(!val2);
}
}
• The output of the program will be: false true
Compound Conditions and
Conditional Operators
48. Guidelines in Writing
Compound Conditions
Common errors in using Compound Conditions
• Conditional expressions in both sides of the && or ||
operator should follow syntax rules with no shortcuts.
A common mistake is forgetting to complete the
expression.
Example: if (age > 12 && < 18)
This should be written as: if (age > 12) && (age < 18)
49. • Using && instead of || Verbal instructions such
as this one can be misleading:
“Add a performance bonus for employees with
a performance rating of “E” and “VS”.
In this case, an employee cannot have both
ratings of “E” and “VS” at the same time, so a
conditional OR ( || ) is needed and not a
conditional-AND (&&)
Guidelines in Writing
Compound Conditions
50. • Mutually exclusive conditions
Another example of unclear instruction:
“Customers whose age is over 60 and minors under
the age of 13 should be given a discount”.
The condition
if (age > 60) && (age < 13)
is erroneous since age could not be both >60 and <13.
Using an || instead of && is more appropriate.
Guidelines in Writing
Compound Conditions
51. • Using || instead of &&
Another example of unclear instruction:
“Customers whose age is over 12 or less than 60 are
not given discounts”.
The condition
if (age > 12) || (age < 60)
is erroneous since the compound condition will never
be false. Seniors and minors will never be captured in
this condition.
Guidelines in Writing
Compound Conditions
52. Operator Precedence
• In compound conditions with mixed AND-OR
operators, conditional-AND && has greater precedence
over || conditional-OR
Example:
In the compound condition
if (age <= 12) || (age >= 60) && (member_status == “G”)
The highlighted code will be evaluated first.
• To avoid confusion, enclose conditions that have to
be evaluated first in parenthesis
Guidelines in Writing
Compound Conditions
53. Using Nested ifs instead of complex compound conditions
• Using nested ifs provide clearer and easier to
understand code instead of complex, compound
conditions
• Example:
If (member_status == “G”)
if (age <= 12)
System.out.println(“Discount applies”);
else if (age >= 60)
System.out.println(“Discount applies”);
Guidelines in Writing
Compound Conditions
54. The switch statement
The switch statement
- An alternative to the if-else statement
- Allows branching on multiple outcomes
56. The switch statement
• where,
- switch-expression
• is any of the primitive data types: byte,
short, char, int, or a String
- case-selector1, case-selector2 and so on
• are unique byte, short, char, int
constants, or a String literal
57. The switch statement
• 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.
58. The switch statement
• NOTE:
- Unlike the if statement, curly braces are not needed
for the block of code in each case.
- When a case is matched, statements in the matching
block are executed. A break statement is needed at
the end of each block to exit the switch statement.
Without a break statement, control will remain inside
the switch statement and succeeding blocks of code
will also be executed.
59. The switch statement
• Example:
public class Grade {
public static void main (String [] args) {
int grade = 92;
switch (grade) {
case 100:
System.out.println(“Excellent!”);
break;
case 90:
System.out.println(“Good Job!”);
break;
case 80:
System.out.println(“Study harder!”);
break;
default:
System.out.println(“Sorry, you failed.”);
}
}
}
60. Control Structures - Iteration
• Most useful and powerful structure
• Allows the repetition of instructions or statements
in the loop body
61. Control Structures - Iteration
• Parts of the iteration structure
- Loop body
- instruction(s) or statements which are repeated
- Loop-exit condition
the condition to be tested before each repetition
• Types
- while loop
- do-while loop
- for loop
62. Control Structures - Iteration
• Format: while loop
while ( condition ) {
statement-1
statement-2
. . .
}
- The statements inside the while loop are
executed as long as the condition remains true
63. Control Structures - Iteration
• Example 1:
int x = 0;
while (x < 10) {
System.out.println(x);
x++;
}
64. Control Structures - Iteration
• Loop control variable
– Used to control the loop’s execution
– The loop control variable is declared and initialized
outside the loop
– The loop control variable is tested and if the result is
true, the loop body is entered
– Inside the loop, the value of the loop control
variable must be changed
– The loop control variable must reach a value that
will render the loop-exit condition false
65. Control Structures - Iteration
• Example 2:
// infinite loop
while (true) {
System.out.println(“hello”);
}
66. Control Structures - Iteration
• Example 3:
// no loops
// statement is not even executed
while (false) {
System.out.println(“hello”);
}
67. Control Structures - Iteration
• Infinite loops
– An infinite loop results when the loop-exit
condition never becomes false.
– To control the execution of a loop, the
following can be used as loop control
variables:
• Counters
• Sentinel value or Indicators
A sentinel value signals a stop in the loop
68. Control Structures - Iteration
• Example 4:
Using a counter
class DisplayFourHellos {
public static void main (String [] args) {
int count = 0;
while (count < 4) {
System.out.println(“Hello”);
count++;
}
System.out.println(“Goodbye!”);
}
}
69. Control Structures - Iteration
• Example 5: Using a sentinel value
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class DisplaySomeHellos {
public static void main (String [] args) {
String shouldContinue = “”;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.print(“Do you want to continue?
Y or N>> ”);
shouldContinue = br.readLine();
70. Control Structures - Iteration
// loop body
while(shouldContinue.equals(“Y”)) {
System.out.println(“Hello”);
System.out.print(“Do you want to continue? Y or
N>> ”);
shouldContinue = br.readLine();
}
System.out.println(“Goodbye!”);
} // end of main method
} // end of class
71. Control Structures - Iteration
• Format: do-while loop
– Is similar to the while-loop
– Statements inside a do-while loop are executed
several times as long as the condition is
satisfied
– The main difference between a while and a do
while loop:
• The statements inside a do-while loop are
executed at least once
72. Control Structures - Iteration
• do-while loop has the form:
do {
statement-1
statement-1
. . .
} while (boolean expression);
73. Control Structures - Iteration
• Example:
int x = 0;
do {
System.out.println(x);
x++;
} while (x < 10);
74. Control Structures - Iteration
• Exercise 8.4
Using, while or do-while loops, print out a
multiplication table such as the one below. The value
of a cell is the product of the row and column that it
intersects.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
75. Control Structures - Iteration
• Format: for loop
- Allows execution of the same code a number of
times
- Format:
for (InitializationExpression;
LoopCondition;
StepExpression) {
statement-1;
statement-2;
. . .
}
76. Control Structures - Iteration
• for loop
- Initialization expression
• Declaration of loop variable and setting of
its initial value
• Example: count = 0
- Loop condition
• Condition to be tested before repetition
• Example: count <= 5
77. Control Structures - Iteration
• for loop
- step expression
• An expression that would alter the value of
the loop control variable
• Example: count = count + 1
78. Control Structures - Iteration
• for loop
- After the loop control variable is increased,
the loop condition is tested again
- If the loop condition results in false, the for
loop is exited.
79. Control Structures - Iteration
• Example: for loop
int i;
for (i = 0; i < 10; i++) {
System.out.println(i);
}
• The code above is equivalent to the following while
loop
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
80. Control Structures - Iteration
• When to use the while loop and the for loop
– The for loop is more compact than the while loop.
There is no need to write statements to alter the
loop control variable, thus reducing errors that
might result when these statements are missed out.
– When the number of times that the loop will be
executed is known, the for loop provides a
convenient shorthand.
81. Control Structures - Iteration
• When to use the while loop and the for
loop
– Loops that are dependent on a sentinel
value (or indicator) are better coded using
a while loop
– The for loop is generally used for
traversing and manipulating arrays
82. Control Structures - Iteration
• Common Loop Applications
- Using a loop to accumulate totals
• An accumulator is a variable that “sums up”
or accumulates values
• It is similar to a counter whose values
change each time the loop is entered.
Counters, however, add a fixed value while
accumulators accumulate undetermined
values.
83. Control Structures - Iteration
• Common Loop Applications
- Using a loop to validate user entry
• Data entered by a user usually needs
validation. It needs to be checked for
errors. Incorrect data can lead to unwanted
results and could end a program
abnormally
• Usual checks for data are: - If it is the
correct data type - For numeric data, if it is
within an acceptable range of values
84. Control Structures - Iteration
• Exercise 8.5 - Using a loop to validate user entry
• Write a program that would ask a user for his
or her birth month. The user enters a value
from 1 to 12, corresponding to the 12 months of
the year.
• Using a loop, validate the data entered. If the
data is incorrect, continue to prompt the user for
an entry until the data entered is valid. If the
data is valid, display the following:
- Birth month is value entered