chapter 4 control structure fundamentals
TRANSCRIPT
-
8/12/2019 Chapter 4 Control Structure Fundamentals
1/55
PART 2 INTRODUCTION TO STRUCTURED PROGRAMMING
CHAPTER 4 CONTROL STRUCTURE FUNDAMENTALS
IN THIS CHAPTER, YOU WILL LEARN HOW TO:
Explain the ip!"tan#e !$ %t"t&"e' p"!("ain( te#hni)&e% in #"eatin( p"!("a%*
Explain the ip!"tan#e i$ #!nt"!l% %t"t&"e% t! l!(i# !'elin( an' p"!("ain(*
De$ine an' ipleent %e)&en#e, 'e#i%i!n an' "epetiti!n %t"t&"e% +ith $l!+#ha"t% an'
p%e&'! #!'e
INTRODUCING CONTROL STRUCTURES?
It is now time to put a little magic in our logic and programs. So far our programs
have been very safe and very simple. We have yet to stretch your ability or creativity
with complex logic. That will all change with this chapter as we introduce control
structures. We can now bring together the techniques covered in chapters onethrough three with program control structures to solve problems we have
conveniently ignored up to this point. Control structures will allow us to add two
critical functions into logic. Specifically these two missing pieces are decision ma!ing
and repetition. These two control structures will give us the power to do far more
complex processing and provide flexibility with logic that I have only hinted at up to
this point.
The logic instructions used so far have been straightforward and were absent of
more sophisticated logic necessary for our program to solve complex problems. In
the previous chapters we have mentioned if statements and while loops but have
yet to explain why they are used and implemented. Why are they are so important to
programming" I might have been guilty of teasing you a little but there is a method
to this approach and also some madness. I wanted to focus your attention in the first
section of the e#oo! on the importance of creating complete logic models. $ogic
models are often overloo!ed in programming classes or there is an assumption that
the student already understands these concepts. The absence of a complete logic
-
8/12/2019 Chapter 4 Control Structure Fundamentals
2/55
model leads to unnecessary code rewor! or worst yet a solution that is different than
what was requested.
Key Concept: %rofessional computer trade publications are littered with stories of
computer programs gone bad. &sually a lot of time and money was spent on a
solution that was different than what the customer wanted. This is usually caused by
the programmer not listening carefully to the end user or short cutting on logic
design. %rogrammers are people and people have mis and'or pre(conceptions about
how things should wor!. It is very easy to get lost in the moment and assume rather
than going bac! and verifying the solution. ) good logic model that is validated with
the customer is a great insurance policy in protecting the program from coming out
different then what was requested.
When modeling logic for a typical business problem it does not ta!e long before ourmodels need to include some element of decision(ma!ing. )s we have already seen
in the Cactus #oo!s and Tapes case studies our ordering program processes data
differently if our customer purchases more than three boo!s. Whereas our previous
logic examples have ignored the requirement for our program to include a decision
we can now build logic to include decision structures that will allow our program to
branch down a thread of program code. In this chapter we will learn how to
implement techniques of structured programming. #y using structured programming
techniques we will not only improve the quality of our logic but ma!e programs
easier to write easier to debug easier to understand and easier to maintain.
In Practice:%rocedural %rogramming ( We will officially introduce procedural
programming next chapter when we cover the topic of modulari*ation but is
appropriate to mention it with structures since it is a critical part of structured
programming. When we develop programs using procedural programming techniques
we implement our logic as procedures. %rocedures li!e structures are bloc!s of code
that represent some logic component of the entire program. +or example we might
create a procedure to do calculate sales tax and another procedure to calculate
quantity discounts. #oth procedures might be necessary to create a customer invoice
but both operations stand on there own and can stand alone as logic inside a
program. Structures are typically written as bloc!s of statement and are similar to
procedures in that many times they stand alone and represent a piece of the entire
solution.
Structured Programming:Simply stated structured programming is the
implementation of three control structures. Structures can be thought of as bloc!s of
code that allows programs to implement sequence decisions and repetition.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
3/55
Sequence decision and repetition structures each have one entry point and one exit
point which provide an element of simplification and organi*ation that ma!es
programs easier to understand and maintain. )ll programming languages ma!e use
of these three structures in various ways. They are essential to performing the
complex logic necessary in computer programming.
With control structures ,sequence decision and repetition- we can also begin to
represent a tas! as a series of related instructions. We can begin to loo! at some
logic tas!s as a series of related steps. +or example when use an if statement to
implement a decision structure the if statement has two branches which describe
the logic outcomes of the #oolean expression. The #oolean expression consists of the
comparison of two values which results in a true or false value returned. +or example
the #oolean expression , / 0- is true but ,0/- would be false. The outcomes are
organi*ed and defined within the if code bloc! ,or we could say within the control
decision structure-.
)n I+ statement in pseudo code would loo! li!e this1
if (1 < 2) then
print This is my true outcome
else
print This is my false outcome
The T234 !eyword mar!s the start of the true branch and the else mar!s the start
of the false branch.
+or example if the customer purchased more than three boo!s a series of
calculations and statements will be executed to derive the correct discounted cost.
The cost calculation for the customer who purchased less than three boo!s is
different then the customer who purchased 5 boo!s. 3ach possible scenario required
a different set of calculations and statements. The control structure allows us to
group more than one logic step into a group which represented some particular tas!.In this example the tas! is the calculation of cost.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
4/55
+igure 1 ) decision control structure ( If #loc!
If youre a customer visiting that boo!store and you purchased five boo!s you would
certainly expect the calculations to reflect the quantity of boo!s purchased. If the
computer software can not support this level of logic flexibility the program is not
very useful. Control structures will help us meet this challenge.
Control Structures:%rogramming languages that support complex logic ,i.e. li!e
logic decisions- will implement sequence decision and repetition structures. These
structures will provide the programming flexibility necessary for computer programs
to solve complex problems. Control structures enable the grouping of processing
steps the implementation of decisions and the use of repetition in our logic and then
our programs.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
5/55
What will remain the same from previous chapters is the importance of proven
programming processes. We will still use the program development process to first
create a logic model then create our programming code next test our program and
finally implement the program. What will be different is that our logic solutions ,and
therefore our programs- will include sequence decision repetition structures.
CONTROL STRUCTURES DEFINED
Sequence structuresa"e the %iple%t !$ #!nt"!l %t"t&"e% t! ipleent an' the #l!%e%t
in $!"at t! +hat +e hae 'i%#&%%e' in the e-!!. %! $a"* Se)&en#e %t"t&"e% hae !ne
inp&t an' !ne !&tp&t +ithin the %e)&en#e %t"t&"e an' t/pi#all/ #!n%i%t !$ in%t"ti!n0%1
0i*e* a #al#&lati!n !" a/2e an a%%i(nent1* The "e%< i% pa%%e' !n t! the next %t"t&"e*
Se)&en#e %t"t&"e% appea" a% "e#tan(le% in $l!+#ha"t% an' %tateent% in p%e&'! #!'e*
%seudo code example1
total = sales times ~salesTax
+igure 01 Sequence structure flowchart
Decision structures, al%! .n!+n a% %ele#ti!n %t"t&"e%3 p"!i'e !&" p"!("a l!(i# +ith
the a2ilit/ t! te%t a -!!lean exp"e%%i!n that +ill "et&"n a -!!lean al&e !$ t"&e !" $al%e*
The te%t #!n%tit&te% a 'e#i%i!n in !&" l!(i#* The -!!lean exp"e%%i!n t/pi#all/ #!n%i%t% !$
-
8/12/2019 Chapter 4 Control Structure Fundamentals
6/55
-
8/12/2019 Chapter 4 Control Structure Fundamentals
7/55
Repetition structures, al%! .n!+n a% l!!pin( !" ite"ati!n %t"t&"e%, p"!i'e !&"
p"!("a l!(i# +ith a2ilit/ t! "epeat a 2l!#. !$ %tateent% 2a%e' !n the eal&ati!n !$ a
-!!lean exp"e%%i!n* Thi% %t"t&"e all!+% &% t! ta.e a ("!&p !$ %ee"al %tateent% an'
"epeat thei" exe#&ti!n 2a%e' !n %!e 'e#i%i!n !" #!n'iti!n* The "epetiti!n #!&l' 2e a%
%iple a% ite"ati!n that all!+% &% t! "epeat th"!&(h a 2l!#. !$ #!'e a #e"tain n&2e" !$
tie% !" #an 2e a% #!plex a% "epetiti!n 2a%e' !n a -!!lean #!pa"i%!n 0i*e* +hen
%ale% 5 67771* Li.e the 'e#i%i!n %t"t&"e, the "epetiti!n eal&ate% a -!!lean exp"e%%i!n
t! #!nt"!l "eent"/ int! the l!!p* Repetiti!n %t"t&"e% appea" a% a 'ia!n' +ith a line
"et&"nin( a2!e the 'ia!n' t! $a#ilitate "epetiti!n an' an!the" line %h!+in( the $l!+ !$
the l!(i# +hen the l!!p #!n#l&'e%* In p%e&'! #!'e an' p"!("a #!'e, the "epetiti!n
%t"t&"e i% &%&all/ ipleente' +ith a +hile l!!p an' ha% the %tateent% in#l&'e' in the
"epetiti!n in'ente' &n'e" the +hile l!!p*
%seudo code to repeat a sequence statement 6 times1
&hile cnt < 1%
total = cnt " 'ty
+low Chart for to repeat a sequence statement 6 times1
+igure 91 :epetition structure flowchart
-
8/12/2019 Chapter 4 Control Structure Fundamentals
8/55
Status Check
$ist and differentiate the three control structures covered in the text.
What is a boolean expression and how is it represented in a flowchart"
What is the symbol for a sequence structure"
LOGICAL OPERATORS
We will save our detailed discussion of logical operators until next chapter on
structured programming. In this chapter we will first introduce logical operators and
get started with structured programming techniques. $ogical operators are usedprimarily to test for a relationship. $ogical operators are the ; ,greater than- ;= then
+iscount e'uals #%-
tot.ost e'uals tot.ost less (tot.ost times +iscount)
print Tot.ost
Logic Tip: The TotCost calculation within the if bloc! may loo! a little mysterious.
2ere we have a statement that includes an assignment and an expression. The
TotCost variable is used no less than three times in this one statement. So how do
the values in TotCost change when this statement is evaluated by the operating
system" &sing operator precedence the TotCost times discount expression is
calculated first. 66 M .65 < 5 so this expression is equal to 5 which is now deducted
from the current value stored in TotCost of 66. The subtraction is performed and
the new value of H5 is stored in TotCost.
In this pseudo code the #oolean expression is boo!sNty ;
-
8/12/2019 Chapter 4 Control Structure Fundamentals
23/55
We have discussed logic errors frequently in the e#oo! so far. If we too! the
following pseudo code and changed the logical operator in the #oolean expression so
that it loo!ed li!e this1
if books,ty > then
The program would execute correctly for all values except for the current example
where boo!sNty is initiali*ed to have a starting value of 7. The way the #oolean
expression is written a value of 7 would not get the discount. This is not how the
program should wor! and the incorrect logical operator or ; would represent a logic
error. To test this logic you would want to test the program when boo!sNty equaled
a value less then 7 a value of three and a value greater than 7. This would test all
three scenarios possible with a logical operator.
Programming Tip:In some programming languages if statements have strict
formatting requirements ,spaces indented on branches- and in other programming
languages there no formatting requirements. 4o matter what the programming
languages requires it is considered good programming practice to line up the if the
word with the else !eyword and have the branch statements below all indented the
same number of spaces. This ma!es the logic much easier to understand and also
helps to prevent logic errors.
In this code snippet we have a variable called the boo!sNty which has been
initiali*ed with a value of three. The if statement has a #oolean expression that tests
to see if the boo!sNty is greater than or equal to the value of three. Since the
#oolean expression will evaluate as true the statement associated with a true
branch ,TotCost < TotCost M 8iscount- will execute. 4ote1 The If statement ends
with a colon and the true branch has each of the statements indented to the same
character position.
In Practice:#oolean String Comparisons ( $etter Case Counts1 When wor!ing with
strings ,a series of characters- in #oolean expressions the letter case of the values
stored in those string variables or string literals is important. +or example lets say I
have two string variables called carColor and modelColor. 3ach of these variables
holds information specifying a color. Color is spelled out as a string ,i.e. carColor
might contain the value @redB for a red car-.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
24/55
$oo! at the following pseudo code" Which branch would the if statement ta!e and
why"
car.olor e'uals re+
mo+el.olor e'uals /e+
if car.olor == mo+el.olor then
print .olor is i+entical
else
print .olor is +ifferent
If you said the false branch you would be correct. The reason for this is that thevalue stored in carColor ,lowercase @redB- is different than the value stored in
modelColor ,title case @:edB-. $etter case counts when comparing the contents of
string variables and literals. If the letter case is not the same then there will be no
match so the expression will evaluate to false. 8oes this ma!e sense" If you did not
account for the letter case of the color you could introduce a logic error into the
program.
Key Concept: When a language is said to be case sensitive is ma!es a distinctionbetween the letter case of identifiers and !eywords. totCost is a different variable
than TotCostbecause the case of the letters are different. >ava and %?T2D4 are case
sensitive but Lisual #asic is not.
TWO -RANCH IF THENELSE STATEMENTS
4ot only can a decision structure have a true branch but you can also define a
branch for a false outcome. In a flowchart this is done by drawing a line from one of
the other points on the diamond and labeling that line as false ,or 4o-. In pseudo
code and %?T2D4 creating a false branch is done by using the else !eyword. =any
of the same rules that were established on single branch decision structures are true
with two branch decision structures. We still need the #oolean expression that
contains at least one logical operator and we need a true and false outcome defined.
http://fundproglogic.pbwiki.com/FCKeditor/2_4/editor/TotCosthttp://fundproglogic.pbwiki.com/FCKeditor/2_4/editor/TotCost -
8/12/2019 Chapter 4 Control Structure Fundamentals
25/55
To Branch !ecision Structures: The decision structure allows the programmer
to add a false branch for the #oolean expression. The false branch implemented with
the else !eyword can contains other structures ust as the true branch did. The false
branch is optional.
FLOWCHARTS EAMPLE OF TWO -RANCH DECISION STRUCTURES
In this flowchart example will modify our single branch example to include a slightly
different calculation if the boo! quantity is less than three. If one or two boo!s are
purchased we want to award a half a percent discount. This calculation will need to
be made on the false branch and we will leave the true branch as it was earlier. ?ou
can place a true'false T'+ yes'no or ?'4 label on the line extending from thediamond to identify which branch is true and which is false. )lthough it is not a
standard the true branch is typically on the right and false on the left. Whatever
technique you use try to be consistent as to not to confuse the reader.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
26/55
+igure 61 I+ Statement with true and false branch
PSEUDO CODE EAMPLE OF TWO -RANCH DECISION STRUCTURES
)ll of the rules that applied with single branch pseudo code also apply to two branch
pseudo code with the exception that we now have a new !ey word else placed in
our if bloc!. We identify the false branch with the else !eyword. We will want to
format and tab the decision structure so that both true and false branches are
indented the same from the if statement and the else !eyword. #elow is an example
of our two branch decision structure using the if and else !eywords.
books,ty e'uals
if books,ty >= then
0iscount e'uals #%-
tot.ost e'uals ~tot.ost less (tot.ost times +iscount)
else
+iscount e'uals #%%-
tot.ost e'uals tot.ost less (tot.ost times +iscount)
print tot.ost
The else branch here represent the actions ta!en if the boolean expression is false.
)s we begin to implement structures and specifically decision structures you will
increase the li!elihood of logic errors. if statements are notorious for passing syntax
chec!s but failing with logic errors. It is very easy to construct complex decision
structures and thin! that the branching is correct only to test your application and
find that the branch you expected is not the one ta!en by the program. 8ebuggers
provide a picture of how your program wor!s by allowing you to follow code as
executes and inspect the values store within variables. Short of using a debugger
you can also do a des! chec! or visually inspect your code for errors but chances
are if you wrote the logic incorrectly you may be biased in reading it for errors and
miss the error. There is no substitute for using a debugger and watching the
program execute its instructions.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
27/55
NESTIN? DECISION STRUCTURES
Single and double branch decision structures are very similar. Typically if you
understand how to implement an if statement with a true branch then implementing
the false branch comes pretty naturally. The nesting of decisions structures describes
the situation where one or both of your branches contain a new decision structure.
We define nesting decision structures as a scenario where one or both of the
branches includes a new decision structure. In short this means one of your if
statement branches executes another if statement. There are no practical limitations
as to how far this nesting can occur. )s long as the syntax rules governing if
statements have not been violated the compiler or interpreter will let you nest
decisions structures as many ways and times as you would li!e. +rom a practical
standpoint as you move to two three or four levels of nesting the entire decision
structure becomes very complex and difficult to debug. >ust as we too! complex
calculations and bro!e them up into smaller calculations the same benefits wouldapply to brea!ing large complicated if bloc!s in to multiple smaller if bloc!s.
Key Concept: 4ow that we have discussed decision structures you see that a
decision implemented in a computer program can only have two outcomes. It can be
true or false or yes or no ,whatever you prefer to use-. This is pretty primitive. 2ard
to understand how this is very powerful but it is. What you can do with decisions is
nest them into a series of true'false decisions. Complex decisions are implemented
as a series of simple true'false decisions. Since the computer can execute decisionsvery quic!ly and can !eep all of the outcomes organi*ed it can become a very used
tool for automated decision ma!ing even with the limitation of only being able to
support two outcomes.
FLOWCHART EAMPLE OF NESTED DECISION STRUCTURES
The flowchart rules for nested decision structures are the same as the rules for single
and double branch decision structures. In our flowchart we would see the nested
decision structure appear as a second diamond hanging off the point of another
diamond. The first diamond would represent the primary decision structure and the
second decision structure and would represent the nested one. I have drawn an
example of this and figure .
-
8/12/2019 Chapter 4 Control Structure Fundamentals
28/55
+igure 1 I+ Statement with nested I+ statement
PSEUDO CODE EAMPLE OF NESTED DECISION STRUCTURES
)ll of the rules that applied with single and double branch pseudo code also apply to
the nesting of if statements. In the example below I have nested an if decision
statement off of the true and false branch of the primary if statement.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
29/55
books,ty e'uals
if books,ty >= then+iscount =#%-
if loyalty = true then
+iscount = +iscount plus #%%
else
+iscount e'uals #%%-
if loyalty = true then
+iscount = +iscount plus #%%1
tot.ost e'uals tot.ost less (tot.ost times +iscount)
print tot.ost
This is the first decision structure ,implemented as an if statement-.
2ere we have the second nested decision structure ,also implemented as an if
statement-.
In Practice:#usiness :ules ( ) common expression used to describe business logic
as business rules. ) business rule is computer logic that defines some set of program
structures used by an organi*ation in the day to day operation of their business. +or
us we could loo! at the loyalty purchase program used by Cactus #oo!s and Tapes
as a business rule. It qualifies as a business rule because its a set of logic which
defines the discount given to a customer who ma!es frequent purchases. We !now
from our previous wor! in chapters two and three that this business rule can be
converted into a logic model and implemented via a program. This is ust one
business rule of many at Cactus #oo!s and Tapes. #usiness rules are defined by the
end user during the requirements phase of S8$C and implemented as a logic model
first and then program code in the design phase.. The next time someone tal!s about
a business rule youll !now exactly what theyre referring to and how it is
implemented in a computer program.
Status Check
Why do not all if statements have a false branch"
-
8/12/2019 Chapter 4 Control Structure Fundamentals
30/55
Why must a sequence structure have a line draw into and from the sequence
structure symbol"
What does nesting of structures mean"
USING REPETITION STRUCTURES
Dur final control structure is the repetition structure. :epetition structures allow us
to repeat logic steps based on #oolean expression criterion. The #oolean expression
sets the criteria for how many times a bloc! of logic ,or code- will be repeated. We
may need to loop through a bloc! of code once or several times. We may !now the
number of exact repetitions in advance or it may only be !nown at run time when
the program is in use.
$ets discuss an example of how repetition structures simplify program logic. $ets
say that we have a program requirement to prompt the user for customer data. We
will need to collect the customers name address and customer number. This data
once collected will be stored in a data file for later use. #ased on conversations with
the customer service department we !now that the customer service rep using this
program may need to enter one customer or hundreds of customers during their
shift.
The first problem we have is how to efficiently code our solution so that it gathers
the three pieces of customer data for many customers. #ased on what we have
learned so far and excluding repetition structures we would have to repeat the
same three logic instructions for how ever many customers we had to collect data
from. If we collected information from 766 customers then our program would have
at the very least 766 customers times 7 lines of logic for a total of H66 lines of logic.
We !now from past experience that each of those logic instructions would probably
translate into a line of programming code. Without repetition structures we would
have a program with over H66 lines of logic. 4ot only would this be extremely
tedious to program but also very difficult to maintain.
Without the use of repetition structures we also have another problem. When we put
the logic together for the solution exactly how many customers should we plan on
processing" Is it 56 customers HF customers or 666 customers" Since our
program will need to be coded to accommodate however many customers we will be
-
8/12/2019 Chapter 4 Control Structure Fundamentals
31/55
collecting data for can we realistically determine what this program should loo! li!e
in advance" 8o we have to have several programs" Would we have one program
that collects data from 56 customers and one program that collects data from HF
customers and finally one program that collects 666 customers" I hope not. What if
we only one to collect data from three customers" Without repetition structures we
would have many versions of the same program that each could accommodate adifferent number of customers. Would it not be better to have one program that
would wor! for all" ?es it would.
4ow lets consider the same problem but this time we will have repetition structures
available for our solution. ) repetition structure has a #oolean expression which
determines if a bloc! of statements is repeated or is passed over. In the problem of
collecting customer information we could create logic which says that if the letters
@NNB are !eyed in for customer name than we have loop through the code enough
times to collect all of the data and now wish to move on to the next stage of the
program. With this design the program could be used for a *ero to an infinitenumber of customers. @NNNB would dictate when the program ends. There would be
no need for multiple programs and even with the extra lines of logic to accommodate
the repetition structure the executable code be small and the same for no matter
how many customers were being processed. The program logic could be written in
four lines and wor! ust as well for or 6666 customers.
&nli!e decision structures which are primarily implemented with if statement logic
we have more variability and options with repetition structures. +or starters the
#oolean expression which determines whether the repetition will occur can be doneat the top ,pre(test- of the logic bloc! or at the bottom of the logic bloc! ,post test-.
>ust li!e the if statement is typically used for decision structures in most
programming languages the while statement is the most common way of
programming repetition structures.
Logic Tip: $oops looping iteration and repetition ( ?ou will see all four of these
terms used identically when describing repetition structures. They all mean
essentially the same thing but iteration is more closely tied to counting through anumber of loops. Iteration is done best with another repetition structure called a for
loop.
PRETEST REPETITION STRUCTURES
-
8/12/2019 Chapter 4 Control Structure Fundamentals
32/55
%retest repetition structures are implemented in while loops. It is called a pretest
structure because the #oolean expression is evaluated before any of the code inside
the while bloc! is executed. The while bloc! consists of the statements repeated each
time while repeats. #ecause of this it is possible that if the pretest #oolean
expression does not evaluate to true then the code within the bloc! may never be
executed. %re(test repetitions structures have their own flowchart pattern along with
their own pseudo code and programming code format. #ecause of this we will
demonstrate both the pre(test and post(test repetition structures with their
representative flowchart and pseudo code examples.
Pre"Test #epetition Structures( %re(test repetition structures allow the program
to repeat through a bloc! of statements only if the #oolean expression evaluates astrue. The #oolean expression is evaluated before the loop is executed and it is
possible that if the #oolean expression evaluates as false on the first pass the loop
logic might never be executed.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
33/55
+igure 01%re(Test and %ost(Test $oop 8iagram
FLOWCHARTS EAMPLE
The pre(test flowchart consists of a diamond symbol that represents the #oolean
expression with two points of the diamond representing true and false. If the
expression evaluates as false the loop terminates and continues to the next logic
step. If the expression evaluates as true the logic steps included within the loop are
executed. )fter these statements are executed the loop test is executed again to
determine if future loops are required.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
34/55
+igure 71%re(Test While +lowchart 3xample
In this example a variable named cnt is initiali*ed to the value of *ero. The while
loop tests with its #oolean expression to see if the value of cnt is less than . Dn
the first loop the value of cnt is *ero so the #oolean expression is true. It will thenexecute the true branch of the diamond symbol and print the contents of the cnt
variable and then add one to the value of cnt. Dn the next pass of the loop the cnt
value is now so the true branch is executed again. It will continue until the value of
cnt is and at that point it fails the #oolean expression and continues to the final
print statement. The output of this logic should print the numbers one through ten
each on a separate line with a final print statement at the end displaying a message
that the program is complete.
COMMON REPETITION STRUCTURE FLOWCHARTIN? MISTABES
) common error made with repetition structure flowcharts is not returning the
branch line bac! to a point above the decision symbol. This may appear to loo! o!ay
at first glance. =any program languages may let you get away with one input
instruction inside the loop as opposed to a single input outside the loop and another
input within the loop but this violates the one input and output line on a control
structure. When you are using a while loop to capture and validate input you should
set up and initial read outside of the loop for the first read and another input inside
the loop for repeated inputs. $oo! at the following flowchart.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
35/55
-
8/12/2019 Chapter 4 Control Structure Fundamentals
36/55
+igure 91 3xample of a repetition structure that does not branch bac! to the
decision symbol.
PSEUDO CODE EAMPLE
+or our pseudo code example we could borrow from the symbol text placed in our
flowchart and simply reformat it for our pseudo code. The formatting or I should say
indenting of repetition structures holds the same importance as was previously
discussed with decision structures. The statements contained within the while bloc!
should be indented underneath the statement containing the while !ey word and the
#oolean expression.
cnt e'uals
&hile cnt < 11 then
print cnt
cnt e'uals cnt 1
print n+ of 3roram
cnt < 11 is the boolean expression# 4s lon as it remains true5 the
&hile &ill continue to loop#
Key Concept: Infinite $oops ( There is a situation that can exist within a repetition
structure called an infinite loop. This occurs if the #oolean expression never becomes
false. The program will continue to loop until the program is aborted or the %C is
turned off. &nder most circumstances an infinite loop is a logic error. This is one of
those errors that everyone ma!es -. 2aving an infinite loop occur in one of yourat
least once ,o!ay twice programs can more or less be considered @rights of passage.B
We all do it at least once. =a!ing mista!es is inevitable but not ma!ing them a
second time is what you should strive for.
POSTTEST REPETITION STRUCTURES
-
8/12/2019 Chapter 4 Control Structure Fundamentals
37/55
)s mentioned earlier while loops come in two varieties. Dne option tests entry into
the loop and the other option tests at the conclusion of the loop. In this post( test
repetition structure since the #oolean expression is at the end of the loop this loop
will always be executed at least once. 8epending on the evaluation of the #oolean
expression at the end of the bloc! the loop may be executed again.
Post"Test #epetition Structures:Similar to a pre(test structure except the
#oolean expression is evaluated at the end of the loop after all of the loop
statements have been executed. With post(test loops the loop is always executed at
least once. +uture looping is predicated on the #oolean expression value at the end
of the loop. If true the repetition structure statements will be executed again. If
false the program moves out of the loop and on to the next statement.
FLOWCHARTS EAMPLE
Contrast the post(test repetition flowcharts with a pre(test repetition flowchart. ?oull
see that in the post(test chart the logic steps included within the loop come before
the #oolean expression and controls any additional looping. Dn the pre(test loop the
logic steps occur after the #oolean expression. The outcome of both of these
flowcharts is the same. They will both print a number from one to nine on its own
line concluding with a message that the program is complete.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
38/55
-
8/12/2019 Chapter 4 Control Structure Fundamentals
39/55
The pseudo code used for post(test repetition structures is slightly different than the
pre(test. There are a number of ways to document the looping. Dne option is to
continue using the while !eyword except the while is now performed at the end of
the loop instead of at the top. This is seen in the following example.
cnt e'uals %
0o
print cnt
cnt e'uals cnt 1
&hile cnt < 11 then
print n+ of 3roram
( This is a post test repetition structure that determines if the loop continues based
on the decision made at the end of the loop.
The until !eyword can be used as a substitute for the while statement. In the
example below I used to do !eyword to mar! the start of the loop and the until
!eyword to mar! the end of loop. We find the #oolean expression at the end of the
loop. :emember pseudo code is non(standard so that !eywords and how you
describe your logic can vary. If you are using another programming language other
than %?T2D4 chec! you programming reference for how to implement repletion in
your programs.
cnt e'uals %
0o
print cnt
cnt e'uals cnt 1
until cnt < 11 then
print
( until is also a popular !eyword to implement post test repetition structures.
P$T%O& TIP: %ost(test looping has not been implemented in %?T2D4. :epetition
logic can be implemented as a pre(test while loop only.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
40/55
In Practice: )re ?ou a %re or %ost Test $ooper" ( 2opefully you have begun to see
from the previous examples that it ma!es little difference whether you use a pre(test
or post(test logic to perform repetition. Dne hint of this might have come from the
fact that %?T2D4 does not support post(test looping. 3ven when both alternatives
exist in a programming language which is usually case I find most programmers
gravitate towards one format or the other. I am a pre(test looper. In other wordswhen I construct my repetition logic I will lean towards using pre(tests loops. In
fact the only time I wor! with post(test loops is when theyve been coded by
another programmer and I am maintaining their program. It is however still
important to note the differences between both alternatives. With a pre(test loop it
is possible that if the #oolean expression is false the loops logic will never get
executed. With a post test loop it is important to remember that the code within the
loop will always be executed at least once.
REPETITION STRUCTURES WITH FOR LOOPS
There is also a second form of repetition structure implemented in many languages
called a for loop. The for loop is traditionally used when the logic needs to iterate
through some number of repetitions. Iteration is typically triggered by a count value
,also called iteration variable-. +or loops wor! exclusively with iteration whereas
while looping can use iteration or a #oolean expression that can ma!e entrance into
the loop based on a logical operator. The difference is subtle but while loops
traditionally are more flexible then for loops. That said for loops are a very powerful
tool to use with arrays ,a topic covered later in the e#oo!- and we will revisit for
loops again at that time. We will focus on While loops in this chapter.
Key Concept:Typically youll find that whatever can be done in a for loop can be
done in equally as well with a while bloc!. While bloc!s represent the most complete
solution for implementing code repetition. +or loops wor! best when the program
needs to increment or decrement ,iterate- some number of set repetitions. While
loops can support iteration of can also support looping controlled with a #oolean
expression that evaluates not only numbers but any valid #oolean expression. With awhile statement I can exit mile loop with a #oolean expression such as @City not
3qual to %hoenix.B This type of #oolean expression is not possible in a for loop where
the #oolean expression is simply evaluating a variable which is incrementing or
decrementing an iteration variable.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
41/55
In Practice' Repetiti!n St"t&"e% &%e' $!" 'e#i%i!n% Repetiti!n %t"t&"e% &%e a -!!lean
exp"e%%i!n t! #!nt"!l ent"/ int! the l!!p* -!!lean exp"e%%i!n% &%e l!(i#al !pe"at!"% t! #!pa"e
t+! al&e%* The !&t#!e i% eithe" t"&e !" $al%e* The +hile l!!p -!!lean exp"e%%i!n i% t/pi#all/ the
%ae a% the -!!lean exp"e%%i!n $!" an i$ %tateent* -e#a&%e !$ thi%, /!& #an &%e the -!!lean
exp"e%%i!n a% a 'e#i%i!n %t"t&"e (!e"nin( ent"/ int! the l!!p* It i% p!%%i2le t! pla#e the inp&t
in%i'e the l!!p an' hae it "epeat &ntil the inp&t i% #!""e#t* The p%e&'! #!'e 2el!+ 'e!n%t"ate%
thi%*
cost = 61
&hile cost > %
cost e'uals input(nter 3ro+uct cost)
if cost < % then
print 7n8ali+ .ost
print 3ro+uct .ost plus cost
( 2ere the #oolean expression does not use a counter but true logical expression.
( 4otice the nested decision structure inside the repetition structure.
Cost is initiali*ed to enter the loop the first time. If the input is greater then *ero the
loop is exited when the #oolean expression is tested again. If the input is less than*ero a message is displayed and the loop is executed again because cost is not
greater than *ero.
USES OF REPETITION STRUCTURES: ACCUMULATION AND COUNTERS
We have two common operations served by repetition structures. The first operation
is counting. Counting is a very important operation in programming. ?ou will count to
perform calculations ,i.e. averaging numbers- and count to determine if you need to!eep on looping in a while bloc!. Counting is accomplished in logic by defining a
variable and adding or subtracting a value from the variable during each repetition
loop. If you add to the counter on each loop the counter value increases
,incrementing-. If we subtract on each loop we count down ,decrementing- with the
counter. We can count by ones or by larger numbers. 2ere are some counting
examples illustrated in pseudo code1
-
8/12/2019 Chapter 4 Control Structure Fundamentals
42/55
count e'uals %
count0o&n e'uals %
count9y:i8e e'uals %
;ne = 1
*hile count
-
8/12/2019 Chapter 4 Control Structure Fundamentals
43/55
'ccumulating: )n accumulating operation is similar to counting except that instead
of adding or subtracting the same number on each pass accumulating adds or
subtracts an identifier or numeric literal value to a variable on each pass. The value
accumulated could be the same value on each pass or a different value.
Status C#ec(
2ow many time will code inside the while bloc! be executed with a post(test while
loop"
What is the difference between counting and accumulating"
Can a for loop structure be simulated with a while repetition structure"
NESTIN? REPETITION STRUCTURES
>ust as with decisions structures nesting repetition structures is also an important
option in designing program logic. $i!e with nested decision structures a while loop
may have many other while loops contained within it. I have included a simple
example of nested while loops but we will see others as we move through the e#oo!.
4ested while loops are especially effective and processing multi(dimensional arrays.
)rrays are a specific type of data structure that hold collections of identifiers. We will
cover the topic of arrays later the e#oo!.
+igure E1 4ested 8ecision and repetition structures
-
8/12/2019 Chapter 4 Control Structure Fundamentals
44/55
2ere is a pseudo code example of a nested while loop1
outer.ount e'uals 1inner.ount e'uals 1
&hile outer.ount < then
print ;uter oop .ount = plus outer.ount
outer.ount e'uals outer.ount plus 1
&hile inner.ount < then
print 7nner oop .ount plus inner.ount
inner.ount plus 1
print 666666666666
print n+ of 3roram
The results of the logic when processed in a program would loo! li!e the following1
Duter $oop Count
Inner $oop Count
Inner $oop Count 0
Inner $oop Count 7
Duter $oop Count 0
Inner $oop Count
Inner $oop Count 0
Inner $oop Count 7
Duter $oop Count 7
Inner $oop Count
Inner $oop Count 0
Inner $oop Count 7
-
8/12/2019 Chapter 4 Control Structure Fundamentals
45/55
( Duter repetition structure implemented as a while loop
( Inner repetition structure implemented as a nested loop
8o you understand how this display was generated" 8oes the nesting of the whileloops ma!e sense" 8o you see how the outside while loop iterates once and then the
inner loop iterates three times for each outside loop. We then hit the second iteration
of the outer loop with the inner loop executing three times again. This is how a
nested loop with two while bloc!s would execute. Can you visuali*e the effects of a
nested repetition structure with three while loops"
CASE STUDY CACTUS -OOBS AND TAPES
The Chave* sisters are happy with the progress made so far and are anxious to see
more of the on(line boo! reservation logic implemented. ?ou have two programs that
youll need to wor! on in this case study. The first program will be finishing up some
wor! started in chapter three and creation of a new program that will involve
collecting customer input for order processing. We will start with finishing up on the
case study first identified in chapter three in part ) and move to the new program in
part #.
PART A
$ets loo! over a transcript of the last session you had with the sisters concerning the
customer discount calculation.
They have been thin!ing about developing a loyalty plan for frequent customers loyal
to the store. The calculation needs to be modified to give a loyalty discount ,.5
percent- if they enter their customer number. In addition if they have purchased
more than three boo!s in the current month they are given another O6 dollars off
there order. The O6 dollars is applied after all other discounts.B
?oull need to modify the pseudo code from the chapter threes case study to
accommodate two new decision structures which need to be included in the logic.
The first decision structure uses an if statement to determine if the person is a
loyalty customer. If you remember from last chapter a loyalty customer is a person
who frequently shops at Cactus #oo!s and Tapes. The second decision structure is
-
8/12/2019 Chapter 4 Control Structure Fundamentals
46/55
also implemented as an if statement and implements quantity discount logic that the
customer is entitled to if they purchased three or more boo!s in this order.
PSEUDO CODE LO?IC SOLUTION
!tart
7nput *!.ost
markup e'uals 1#2-
han+lin e'uals -
loyalty9onus e'uals %
'uantity0iscount e'uals %
7nput custoyal!tatus
7f custoyal!tatus = true then
loyalty9onus e'uals 1#- per cent
7nput ,ty
if ,ty >= then
'uantity0iscount e'uals 1%
!ubTotal e'uals *!.ost times markup plus han+lin
cust0iscount e'uals subTotal times loyalty9onus less 1%
cust.ost = subTotal less cust0iscount
3rint cust.ost
n+
PART -
?ou are now ready to wor! on other logic necessary to process the boo! order. In
this second program youll want to create logic the as! the customer for their name
the number of boo!s purchased and then loop through that logic to gather
information on title price and quantity. The program will and by displaying the total
boo! quantity and the total order amount purchased in this customer order. ?ou
have been as!ed to implement a @flagB value to determine when the customer is
finished. The @flagB value will be used in the while statement #oolean expression to
finish up with collecting input and move on to the next section of the program.
7nput nter .ustomer ame name
7nput nter 9ook ame or ,, to 'uit bookame
-
8/12/2019 Chapter 4 Control Structure Fundamentals
47/55
&hile bookame ,, then
7nput nter 9ook 3rice price
count e'uals count 1
tot3rice e'uals tot3rice price
7nput nter 9ook ame or ,, to 'uit bookame
print Total 3rice plus tot3rice
print .ount plus count
( 2ere I have used NN as a sentinel value to trigger the end of the loop and also the
end of input. ) while loop provides this type of flexibility. Something that could not
be done with a for loop without changing the logic.
In this pseudo code you will see the while loop controls the number of times the
user is prompted for boo! name and price. )lso the while bloc! has both
accumulating in counting operations that will be used in the printed summary at theend of this
customers order.
STRUCTURES USIN? COMPOUND OPERATORS
3arlier in the chapter chapter we covered compound operators which are used to
oin logical expressions. Compound operators are important in both decision and
repetition structures. They add flexibility and power to our structures. 8ifferent
languages implement compound structures differently so you will want to refer to
your programming reference for compound operator syntax.
The two most commonly used compound operators are and and or. ?ou can easily
oin two #oolean expressions but as you oin three and four you have to be conscious
of operator precedence and its effects on evaluating the entire collection of
expressions. $ogic errors are common with this type of statement. Dperator
precedence will have you evaluating each individual expression first and then eachexpression with each other from left to right and so on. To illustrate how to properly
evaluate compound operators I have included the following pseudo code example1
a = 1
b = 2
c =
-
8/12/2019 Chapter 4 Control Structure Fundamentals
48/55
if (a = 2) or (b > 1) an+ (c = a)
The first expression ,a < 0- will evaluate as false. The second expression ,b ; -
will evaluate as true and the third expression ,c < a- will evaluate as false. Thecompound operator oins expression one and expression two first. Since expression
one is false and expression two is true and they are oined with an or only one side
has to be true for the whole expression to be true. This is the case so this first
compound expression evaluates as true. The third expression is false and it is oined
to with the first two expressions with an and. Since one side is true and one side is
false then the entire expression finally evaluates as false.
COMPOUND OPERATORS IN DECISION STRUCTURES
2ere is an example of how a compound operator will wor! with a decision structure.
qty ; 9 will be valuated first and then qty / 6 next. If both evaluate as true the
entire expression is true. In this case the qty must be between 5 and H to call the
true branch and anything else to call the false branch.
if ('ty > ) an+ ('ty < 1%)
subTotal e'uals ext.ost minus (ext.ost times 07!.%-)
else
subtotal e'uals ext.ost
COMPOUND OPERATORS IN REPETITION STRUCTURES
2ere we have a similar scenario where two #oolean expressions are used in a
repetition structure to determine if the looping will continue.
&hile ('ty > %) or (part.o+e = 4)
ext.ost e'uals cost times part.o+e4+?ust
-
8/12/2019 Chapter 4 Control Structure Fundamentals
49/55
+or this loop to continue into the quantity must be greater than 6 and the partCode
must be equal to the literal @)B.
PUTTING IT TO USE
The intent of this section is to introduce the new programmer to standards and
techniques frequently used by professional programmers. Topics in this section relate
to concepts introduced in the chapter but with a more vocational or occupational
focus for students considering a career in programming.
Best Practices:%rogram Source Code Comments ( In previous chapters I tal!ed
about documenting your logic within your program as a program comment. The
program comment is a non executable line which is visible to those editing the
program but invisible to the users who are executing it. )s a rule I have a
requirement in my programming classes that every line of code of the program is
commented. Those students who have had previous program experience will be the
first to remind me that this rule is a little extreme. There are no set rules on what or
how much program commenting should be done inside a program. When as!ed how
much is enough" I will quite often give the answer that you should comment any
logic in your program that might be confusing or difficult for another programmer tounderstand. I also say all structures and calculations should be commented.
I specifically identify programming structures as a good place to thin! about adding
program comments. :eflecting about what weve learned so far certainly decision
and repetition structures have been the most complicated mechanism used in our
logic and programming so far. It is highly li!ely that these structures will be included
in the more complex parts of your logic and therefore ma!e excellent candidates for
program comments. It has been my experience that it is better to error with two
many comments that not enough. In other words if you have any thoughts at allabout a part of your program being complicated then comment itK
It is also common practice to include a few lines of comments at the beginning of
your program that identify the name of the program the person who wrote the
program a description of the program. )ny updates made to the program after the
original coding should include the date and initials of the person who modified the
-
8/12/2019 Chapter 4 Control Structure Fundamentals
50/55
program along with a short description of what they changed. This acts as a history
of the program and creates a timeline and blueprint for how this program was
developed and updated.
SOURCE CODE FORMATTIN?
It has been mentioned already about the importance of properly indenting decision
and repetition structures. I would li!e to go one step further and suggest that even
though the compiler and interpreter may not care how you indent your source code
failure to use good standardi*ed source code formatting techniques will have a very
negative effect on your wor! when reviewed by other programmers. Thin! of it li!e
this. Suppose you are editing a five page term paper. ?ou can hand in the paper
neatly handwritten on ruled paper or you can print it out double spaced with a letter
quality printer. Which of these documents will be the easiest to read" Which of thesedocuments will loo! the most professional" Style points may not count in
programming but formatting of code is an indicator of the programmers
professionalism and discipline.
Some things to remember when youre formatting your source code1
All 2"an#he% !n 'e#i%i!n %t"t&"e% %h!&l' 2e in'ente' the %ae n&2e" !$ %pa#e%*
Ne%te' i$ %tateent% %h!&l' $i"%t line &p +ith !the" 2"an#h %tateent% +ith thei" 2"an#he%
in'ente' the %ae n&2e" !$ %pa#e%*
Sepa"ate %t"t&"e% +ith a 2lan. line in /!&" %!&"#e #!'e* C"ain( all the line% t!(ethe"
+ith n! i%&al 2"ea.% a.e% %e#ti!n% !$ the #!'e !"e 'i$$i#< t! $in'* A 2lan. line pla#e'
in $"!nt !$ the %t"t&"e i%!late% it $"! !the" p"!("a #!'e an' a.e% a l!(i# &%e" t! $in'*
A p"!("a #!ent pla#e' in $"!nt !$ the %t"t&"e %h!&l' (ie (ene"al in$!"ati!n !n
+hat the %t"t&"e i% t! a##!pli%h* -e/!n' that %pe#i$i# p"!("a line #!ent% #an 2e
pla#e' t! the "i(ht !$ the %tateent !" !n the p"ei!&% line*
#elow are two more sophisticated %?T2D4 programs with a number of structures.Dne with comments inserted and lines formatted and one without. Which one would
you rather wor! on"
&ncommented and unformatted
-
8/12/2019 Chapter 4 Control Structure Fundamentals
51/55
total.ost = 1
total!ale = %
ext.ost = %
subTotal = %
'ty = %
tot4ll!ales = %
07!.1% = #1%
07!.%- = #%-
!4!T4@ = #%A
&hile 'ty B= 61C
'ty = input(Dnter ,uantity or 61 to 'uit >> D)
if 'ty > % an+ 'ty < 1%%C
ext.ost = total.ost " 'ty
if 'ty > an+ 'ty < 1%C
subTotal = ext.ost 6 (ext.ost " 07!.%-)
elif 'ty > 1%C
subTotal = ext.ost 6 (ext.ost " 07!.%-)
elseC
subTotal = ext.ost
total!ale = subTotal 6 (subTotal " !4!T4@)
tot4ll!ales = tot4ll!ales total!ale
print DTotal !ale plus tax is CD5 total!ale
print DTotal 4ll !ales C D 5 tot4ll!ales
COMMENTED AND FORMATTED
Comments mar!ed with P ,pound- sign.
Eproram 8ariables
total.ost = 1
total!ale = %
ext.ost = %
subTotal = %
'ty = %
tot4ll!ales = %
07!.1% = #1%
07!.%- = #%-
!4!T4@ = #%A
Emain loic starts here
-
8/12/2019 Chapter 4 Control Structure Fundamentals
52/55
Eloop &hile 'ty is not e'ual to 61
&hile 'ty B= 61C
Eprompt for 'uantity
'ty = input(Dnter ,uantity or 61 to 'uit >> D)
Eif 'ty is reater than Fero an+ 'ty is less than 1%%
if 'ty > % an+ 'ty < 1%%C
Eext cost e'uals total cost time 'ty
ext.ost = total.ost " 'ty
Eif 'ty is reat then an+ 'ty is less than 1%
if 'ty > an+ 'ty < 1%C
Esub total e'uals ext.ost minus ext.ost times 0isc%-
subTotal = ext.ost 6 (ext.ost " 07!.%-)
Eelse if 'ty reat than 1%
elif 'ty > 1%C
Esubtotal e'uals ext.ost minux ext.ost times 0isc%-
subTotal = ext.ost 6 (ext.ost " 07!.%-)
Eelse 6 outer branch is false
elseC
EsubTotal e'uals ext.ost
subTotal = ext.ost
Efinish up processin
Etotal!ale e'uals subTotal minus subtotal times salestax constant
Etotal4ll!ales e'uals tot4ll!ales plus total!ale
total!ale = subTotal 6 (subTotal " !4!T4@)
tot4ll!ales = tot4ll!ales total!ale
Eprint total sale
print DTotal !ale plus tax is CD5 total!ale
print DTotal 4ll !ales C D 5 tot4ll!ales
)lthough they both produce the same results I dont thin! theres any question as to
which program is the easiest to maintain. Certainly the second example that has
blan! lines ,also called white space- is visually easier to follow. The comments ma!e
the program logic easier to understand as it moves through different logic twists and
turns. This ma!es future changes easier to understand.
C)APTER RE*IE+
Chapter summary highlights !ey terms short answer questions qui**es and case
studies to reinforce topics covered in this chapter.
-
8/12/2019 Chapter 4 Control Structure Fundamentals
53/55
CHAPTER SUMMARY
)fter finishing this chapter you should understand and in some cases demonstrate
the following topics1
Explain the ip!"tan#e !$ %t"t&"e' p"!("ain( te#hni)&e% in #"eatin( p"!("a%*
o C!nt"!l %t"t&"e% all!+ p"!("ae"% t! 2&il' #!plex appli#ati!n% 2/ p"!i'in(
'e#i%i!n an' "epetiti!n %&pp!"t*
o When &%in( $l!+#ha"t% t! #"eate %t"t&"e' p"!("ain( l!(i# 'e%i(n%, ea#h
%/2!l %h!&l' hae !ne inp&t an' !ne !&tp&t line, +ith ea#h %/2!l #!ntainin( a
%h!"t 'e%#"ipti!n !$ the p&"p!%e !$ the %/2!l an' a.in( %&"e n! line% in the
'ia("a #"!%%*
o P%e&'! #!'e ha% %t"i#t "e)&i"eent% "e(a"'in( the in'entin( !$ %tateent% that
$all &n'e" the t"&e an' $al%e 2"an#h !$ the -!!lean exp"e%%i!n*
o When a %t"t&"e #all% an!the" %t"t&"e 2e#a&%e !$ the eal&ati!n !$ the
-!!lean exp"e%%i!n, the #alle' %t"t&"e i% #alle' a ne%te' %t"t&"e* All !$ the
#!nt"!l %t"t&"e% #an 2e ne%t &n'e" an/ !$ the !the" #!nt"!l %t"t&"e%*
Explain the ip!"tan#e i$ #!nt"!l% %t"t&"e% t! l!(i# !'elin( an' p"!("ain(*
o P"!("a% a.e 'e#i%i!n% in l!(i# +ith 'e#i%i!n %t"t&"e%* De#i%i!n %t"t&"e%
li.e the i$ %tateent all!+ a -!!lean exp"e%%i!n t! &%e l!(i#al !pe"at!"% t! "et&"n
a t"&e !" $al%e !&t#!e* On#e the 'e#i%i!n !&t#!e i% 'ete"ine', the p"!("a
#an 2"an#h t! a %e"ie% !$ in%t"ti!n% #"eate' $!" that !&t#!e*
De$ine an' ipleent %e)&en#e, 'e#i%i!n an' "epetiti!n %t"t&"e% +ith $l!+#ha"t an'
p%e&'! #!'e
o Se)&en#e #!nt"!l %t"t&"e% a"e the %iple%t !$ #!nt"!l %t"t&"e% 2&t the !%t
#!!n* Se)&en#e %t"t&"e% h!l' %tateent% an' exp"e%%i!n% that #!n%tit&te
!%t !$ the in%t"ti!n% %ent t! the #!p&te"*
o De#i%i!n %t"t&"e% p"!i'e 'e#i%i!n %&pp!"t $!" !&" l!(i# an' p"!("a%* Th"!&(h
the ipleentati!n !$ i$ %tateent%, a l!(i# 'e#i%i!n ha% a t"&e !" $al%e !&t#!e*
The 'e#i%i!n %t"t&"e i% ipleente' +ith a 2!!lean exp"e%%i!n that eal&ate%
a% t"&e !" $al%e*
o De#i%i!n %t"t&"e% a/ 2e ne%te'* Thi% ean% a 2"an#h !$ a 'e#i%i!n %t"t&"e
#an #!ntain a ne+ 'e#i%i!n% %t"t&"e*
o A 'e#i%i!n %t"t&"e &%t a t"&e !&t#!e an' #an !pti!nall/ #!ntain a $al%e
!&t#!e*
o Repetiti!n %t"t&"e% a"e e"/ e"%atile an' #an 2e &%e' t! "epeat 2l!#.% !$ #!'e
!" a% a e#hani% $!" ali'atin( inp&t* Repetiti!n %t"t&"e% %ipli$/ l!(i# that
#!&l' !the"+i%e nee' t! #!ntain an/ !"e "epeate' l!(i# %tateent%*
-
8/12/2019 Chapter 4 Control Structure Fundamentals
54/55
o Repetiti!n %t"t&"e% #an 2e 'e%i(ne' +ith a -!!lean exp"e%%i!n at the %ta"t !$
the +hile 2l!#. !" the en' !$ the +hile 2l!#.* Ea#h +hile l!!p +ill +!". e)&all/ a%
+ell 2&t the p"ete%t l!!. a/ n!t exe#&te the l!!p l!(i# &nle%% the -!!lean
exp"e%%i!n eal&ate% a% t"&e an' the p!%tte%t l!!p +!&l' exe#&te the l!(i# at
lea%t !n#e an' a''iti!nal l!!p% i$ the 2!!lean exp"e%%i!n eal&ate% a% t"&e*
o The "epetiti!n %t"t&"e #an 2e &%e' $!" #!&ntin( an' a##&&latin( n&2e"% i$
the #!&ntin( an' a##&&latin( a"ia2le i% #!ntaine' +ithin the l!!p* C!&ntin( +ill
in#"eent !" 'e#"eent the %ae !n ea#h l!!p an' a##&&latin( +ill %& a
n&2e" int! a a"ia2le $!" ea#h l!!p*
CHAPTER BEY TERMS
)ccumulating
#ranch
Compound Dperators
Control Structures
Counting
8ecision Structures
4esting 8ecision Structures
4esting :epetition Structures
%ost Test :epetition Structure
%retest :epetition Structures
%rogram Comment
:epetition Structures
Sequence Structures
Single #ranch If Structures
Source Code +ormatting
Structured %rogramming
Two #ranch 8ecision Structures
-
8/12/2019 Chapter 4 Control Structure Fundamentals
55/55