SlideShare a Scribd company logo
MODULE 1:
OBJECT-ORIENTED
PROGRAM LOGIC AND
DESIGN
CHAPTER 8:
CONTROL STRUCTURES
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).
• Types of Control Structures
- Sequence
- Selection (or Decision Control) Structure
- Iteration (or Repetition) Structure
CONTROL STRUCTURES
Control Structures
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
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 */
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
Control Structures - Selection
• Entry to the structure is through the condition
• Exit is through the execution of process A or process B
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
Control Structures - Selection
• Program code for dual alternative selection:
if (condition)
statement1;
else
statement2;
- where condition is a boolean expression or
boolean variable
Control Structures - Selection
• Example:
int grade = 60;
if (grade > 79)
System.out.println(“Congratulations! You
passed!”); else
System.out.println(“Try harder next time.”);
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.
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?
Control Structures - Selection
Exercise 8.1
• Problem Analysis using HIPO
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;
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
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
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
Control Structures - Selection
Exercise 8.2
• Problem analysis using HIPO:
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;
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;
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
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.
Control Structures - Selection
Exercise 8.2
• The HIPO using step-wise refinement
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;
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;
Control Structures - Selection
Exercise 8.2 – Program code cont’d
// compute netPay
if (noOfDaysAbsent > 0) {
deductionsDueToAbsences = dailyRate *
noOfDaysAbsent;
netPay = monthlySalary – deductionsDueToAbsences;
}
else {
netPay = monthlySalary;
}
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
Control Structures - Selection
Exercise 8.3
Using selection control structures
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”.
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.
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)
• 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
• 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
• 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
• 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
• 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
• The output of the program is:
0
10
false
Compound Conditions and
Conditional Operators
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
• The truth table for || (conditional-OR)
Compound Conditions and
Conditional Operators
• 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
• 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
• The output of the program is:
0
10
true
Compound Conditions and
Conditional Operators
• 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
• 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
• 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
• 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
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)
• 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
• 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
• 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
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
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
The switch statement
The switch statement
- An alternative to the if-else statement
- Allows branching on multiple outcomes
• switch statement format:
switch (switch-expression) {
case case-selector1:
statement1;
statement2;
break;
case case-selector2:
statement1;
statement2;
break;
default:
statement1;
statement2;
}
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
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.
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.
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.”);
}
}
}
Control Structures - Iteration
• Most useful and powerful structure
• Allows the repetition of instructions or statements
in the loop body
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
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
Control Structures - Iteration
• Example 1:
int x = 0;
while (x < 10) {
System.out.println(x);
x++;
}
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
Control Structures - Iteration
• Example 2:
// infinite loop
while (true) {
System.out.println(“hello”);
}
Control Structures - Iteration
• Example 3:
// no loops
// statement is not even executed
while (false) {
System.out.println(“hello”);
}
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
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!”);
}
}
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();
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
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
Control Structures - Iteration
• do-while loop has the form:
do {
statement-1
statement-1
. . .
} while (boolean expression);
Control Structures - Iteration
• Example:
int x = 0;
do {
System.out.println(x);
x++;
} while (x < 10);
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
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;
. . .
}
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
Control Structures - Iteration
• for loop
- step expression
• An expression that would alter the value of
the loop control variable
• Example: count = count + 1
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.
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++;
}
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.
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
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.
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
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

More Related Content

What's hot

What's hot (20)

Java method
Java methodJava method
Java method
 
Exception handling
Exception handlingException handling
Exception handling
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Java awt
Java awtJava awt
Java awt
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception handling
Exception handling Exception handling
Exception handling
 
Object and class
Object and classObject and class
Object and class
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Java basic
Java basicJava basic
Java basic
 
Exception handling
Exception handlingException handling
Exception handling
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 

Similar to CONTROL STRUCTURE

9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
ransayo
 
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
gilpinleeanna
 
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docxNew folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
henrymartin15260
 
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docxELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
jack60216
 
Onlineshopping 121105040955-phpapp02
Onlineshopping 121105040955-phpapp02Onlineshopping 121105040955-phpapp02
Onlineshopping 121105040955-phpapp02
Shuchi Singla
 

Similar to CONTROL STRUCTURE (20)

Building blocks of Algblocks of Alg.pptx
Building blocks of Algblocks of Alg.pptxBuilding blocks of Algblocks of Alg.pptx
Building blocks of Algblocks of Alg.pptx
 
Srs template ieee se-1
Srs template ieee se-1Srs template ieee se-1
Srs template ieee se-1
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
 
Cis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.comCis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.com
 
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docxMSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
MSCD650 Final Exam feedback FormMSCD650 Final Exam Grading For.docx
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
SE2018_Lec 19_ Software Testing
SE2018_Lec 19_ Software TestingSE2018_Lec 19_ Software Testing
SE2018_Lec 19_ Software Testing
 
Application of theorem proving for safety-critical vehicle software
Application of theorem proving for safety-critical vehicle softwareApplication of theorem proving for safety-critical vehicle software
Application of theorem proving for safety-critical vehicle software
 
Lect 3-4 Zaheer Abbas
Lect 3-4 Zaheer AbbasLect 3-4 Zaheer Abbas
Lect 3-4 Zaheer Abbas
 
Automation with bpt methodology
Automation with bpt methodologyAutomation with bpt methodology
Automation with bpt methodology
 
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docxNew folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
 
SE2_Lec 20_Software Testing
SE2_Lec 20_Software TestingSE2_Lec 20_Software Testing
SE2_Lec 20_Software Testing
 
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docxELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
 
Model Driven Testing: requirements, models & test
Model Driven Testing: requirements, models & test Model Driven Testing: requirements, models & test
Model Driven Testing: requirements, models & test
 
Penyelesaian masalah
Penyelesaian masalahPenyelesaian masalah
Penyelesaian masalah
 
Software Verification, Validation and Testing
Software Verification, Validation and TestingSoftware Verification, Validation and Testing
Software Verification, Validation and Testing
 
Modeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDrawModeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDraw
 
Onlineshoppingonline shopping
Onlineshoppingonline shoppingOnlineshoppingonline shopping
Onlineshoppingonline shopping
 
Onlineshopping 121105040955-phpapp02
Onlineshopping 121105040955-phpapp02Onlineshopping 121105040955-phpapp02
Onlineshopping 121105040955-phpapp02
 

More from Dr. Rosemarie Sibbaluca-Guirre

More from Dr. Rosemarie Sibbaluca-Guirre (20)

Korean Language: Culture 한국어 개요
Korean Language: Culture 한국어 개요Korean Language: Culture 한국어 개요
Korean Language: Culture 한국어 개요
 
Korean Language Overview 한국어 개요
Korean Language Overview 한국어 개요Korean Language Overview 한국어 개요
Korean Language Overview 한국어 개요
 
Conjunction 접속사
Conjunction   접속사Conjunction   접속사
Conjunction 접속사
 
Pronoun 대명사
Pronoun  대명사Pronoun  대명사
Pronoun 대명사
 
Usage of Particles 입자의 사용
Usage of Particles 입자의 사용Usage of Particles 입자의 사용
Usage of Particles 입자의 사용
 
Usage of Particles 입자의 사용
Usage of Particles 입자의 사용Usage of Particles 입자의 사용
Usage of Particles 입자의 사용
 
Korean Word Order 한국어 단어 순서
Korean Word Order 한국어 단어 순서Korean Word Order 한국어 단어 순서
Korean Word Order 한국어 단어 순서
 
Korean Number 한국 번호
Korean Number 한국 번호Korean Number 한국 번호
Korean Number 한국 번호
 
ISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptx
ISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptxISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptx
ISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptx
 
ISAD 313-1_INTRODUCTION TO SYSTEMS.pptx
ISAD 313-1_INTRODUCTION TO SYSTEMS.pptxISAD 313-1_INTRODUCTION TO SYSTEMS.pptx
ISAD 313-1_INTRODUCTION TO SYSTEMS.pptx
 
ISAD 313-2_ SYSTEM ANALYSIS.pptx
ISAD 313-2_ SYSTEM ANALYSIS.pptxISAD 313-2_ SYSTEM ANALYSIS.pptx
ISAD 313-2_ SYSTEM ANALYSIS.pptx
 
ISAD 313-4_ RESEARCH PROJECT.pptx
ISAD 313-4_ RESEARCH PROJECT.pptxISAD 313-4_ RESEARCH PROJECT.pptx
ISAD 313-4_ RESEARCH PROJECT.pptx
 
ISAD 313-3_ SYSTEM FLOW.pptx
ISAD 313-3_ SYSTEM FLOW.pptxISAD 313-3_ SYSTEM FLOW.pptx
ISAD 313-3_ SYSTEM FLOW.pptx
 
ISAD 313-3_ MODELS.pptx
ISAD 313-3_ MODELS.pptxISAD 313-3_ MODELS.pptx
ISAD 313-3_ MODELS.pptx
 
ACCT11_9_Financial Position.pptx
ACCT11_9_Financial Position.pptxACCT11_9_Financial Position.pptx
ACCT11_9_Financial Position.pptx
 
ACCT11_8_Equity.pptx
ACCT11_8_Equity.pptxACCT11_8_Equity.pptx
ACCT11_8_Equity.pptx
 
ACCT11_7_Performance.pptx
ACCT11_7_Performance.pptxACCT11_7_Performance.pptx
ACCT11_7_Performance.pptx
 
ACCT11_6_Worksheet.pptx
ACCT11_6_Worksheet.pptxACCT11_6_Worksheet.pptx
ACCT11_6_Worksheet.pptx
 
ACCT11_5_Adjusting Entries.pptx
ACCT11_5_Adjusting Entries.pptxACCT11_5_Adjusting Entries.pptx
ACCT11_5_Adjusting Entries.pptx
 
ACCT11_4_Trial Balance.pptx
ACCT11_4_Trial Balance.pptxACCT11_4_Trial Balance.pptx
ACCT11_4_Trial Balance.pptx
 

Recently uploaded

Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 

Recently uploaded (20)

MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Forest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDFForest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDF
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 

CONTROL STRUCTURE

  • 1. MODULE 1: OBJECT-ORIENTED PROGRAM LOGIC AND DESIGN CHAPTER 8: CONTROL STRUCTURES
  • 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?
  • 14. Control Structures - Selection Exercise 8.1 • Problem Analysis using HIPO
  • 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
  • 19. Control Structures - Selection Exercise 8.2 • Problem analysis using HIPO:
  • 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;
  • 27. Control Structures - Selection Exercise 8.2 – Program code cont’d // compute netPay if (noOfDaysAbsent > 0) { deductionsDueToAbsences = dailyRate * noOfDaysAbsent; netPay = monthlySalary – deductionsDueToAbsences; } else { netPay = monthlySalary; }
  • 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
  • 29. Control Structures - Selection Exercise 8.3 Using selection control structures
  • 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
  • 55. • switch statement format: switch (switch-expression) { case case-selector1: statement1; statement2; break; case case-selector2: statement1; statement2; break; default: statement1; statement2; }
  • 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