Anda di halaman 1dari 55



Explain the i p!"tan#e !$ %t"&#t&"e' p"!("a

in( te#hni)&e% in #"eatin( p"!("a %* !'elin( an' p"!("a in(*

Explain the i p!"tan#e i$ #!nt"!l% %t"&#t&"e% t! l!(i#

De$ine an' i ple ent %e)&en#e, 'e#i%i!n an' "epetiti!n %t"&#t&"e% +ith $l!+#ha"t% an' p%e&'! #!'e


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 one through 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

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 our models 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.

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.

+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.

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.


Sequence structures a"e the %i ple%t !$ #!nt"!l %t"&#t&"e% t! i ple ent an' the #l!%e%t in $!" at t! +hat +e ha,e 'i%#&%%e' in the e-!!. %! $a"* Se)&en#e %t"&#t&"e% ha,e !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(n ent1* The "e%&lt 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' %tate ent% 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% !$

t+! i'enti$ie"%, lite"al% !" !the" exp"e%%i!n% 4!ine' 2/ a l!(i#al !pe"at!"* It i% i p!"tant t! &n'e"%tan' that -!!lean exp"e%%i!n% #an !nl/ p"!'&#e a %!l&ti!n +ith t+! alte"nati,e%* -/ ne%tin( 0a''in( ne+ 'e#i%i!n %t"&#t&"e% +ithin the t"&e an' $al%e 2"an#he%1, e,en #! plex 'e#i%i!n% #an 2e i ple ente' in a p"!("a * De#i%i!n %t"&#t&"e% appea" a% 'ia !n' %hape' %/ 2!l% in $l!+#ha"t% an' a"e i ple ente' in p%e&'! #!'e a% an i$ %tate ent* The $l!+#ha"t 'ia !n' %/ 2!l 0+hi#h al%! i'enti$ie% the 2!!lean exp"e%%i!n1 +ill ha,e a t"&e line an' !pti!nall/ a $al%e line '"a+n $"! the p!int% !n the 'ia !n'* P%e&'! #!'e +ill in#l&'e %tate ent% in'ente' &n'e" the i$ %tate ent $!" t"&e -!!lean exp"e%%i!n% an' &n'e" the el%e %tate ent $!" a $al%e -!!lean exp"e%%i!n*

%seudo code for ..6 percent boo! discount with purchase of more than 7 boo!s1

if (books > then tot!ales = sales " #$% else tot!ales = sales +low Chart for ..6 percent boo! discount with purchase of more than 7 boo!s1

+igure 71 8ecision structure flowchart

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!#. !$ %tate ent% 2a%e' !n the e,al&ati!n !$ a -!!lean exp"e%%i!n* Thi% %t"&#t&"e all!+% &% t! ta.e a ("!&p !$ %e,e"al %tate ent% an' "epeat thei" exe#&ti!n 2a%e' !n %! e 'e#i%i!n !" #!n'iti!n* The "epetiti!n #!&l' 2e a% %i ple a% ite"ati!n that all!+% &% t! "epeat th"!&(h a 2l!#. !$ #!'e a #e"tain n& 2e" !$ ti e% !" #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 e,al&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/ i ple ente' +ith a +hile l!!p an' ha% the %tate ent% 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

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"


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 used primarily to test for a relationship. $ogical operators are the ; ,greater than- ;< ,greater than or equal- / ,less than- /< ,less than or equal- and finally the << ,equity operator-.

Key Point: Some languages use the < ,equals sign- both as the assignment operator ,when we want to ma!e a variable equal to some other variable or literaland the equity operator ,i.e. used to test if two variables two constants or a variable and constant etc. are the same-. =any of the newer languages ,i.e. >ava- have a double equals sign ,<<- for equality operator and a single equals ,<- for the assignment operator. ?ou will want to chec! the language reference to !now which one to use.

Equity operator

I$ t!tal 88 6777: PYTHON I$ t!tal 8 6777 then 9:i%&al ;-a%i#*NET< I$ 0t!tal 88 67771 =a,a

! " Greater T#an Operators I$ t!tal 58 6777: PYTHON I$ t!tal 5 6777 then 9:i%&al ;-a%i#*NET<

I$ 0t!tal 58 67771 =a,a $! $" Less T#an Operators I$ t!tal > 6777: PYTHON I$ t!tal >8 6777 then 9:i%&al ;-a%i#*NET< I$ 0t!tal >8 67771 =a,a

Logical Operators: $ogical operators are used when we need to ma!e comparisons in expressions. The result of a comparison with a logical operator is usually true or false. The logical operators are ; / ;< /< and <<. The logical operators allow us to compare some predicted relationship ,i.e. StateCode << @)AB- and if the conditional expression is valid then the program returns true. If it is not it returns a false. We used logical operators extensively in if statements ,covered in our next chapter-.

Programming Tip: =a!e sure you place the equals sign after the ; and / for greater than or equal ,<- and less than or equal to ,/<-. To reverse the characters will lead to a compiler or interpreter syntax error.


This final group of operators is associated with logical operators and is called compound operators. Compound operators are used to Coin multiple expressions typically made up of logical operators. $ogical operators consist of the and or and not !eywords. When +e &%e the an' #! p!&n' !pe"at!", +e a"e te%tin( that 2!th %i'e% !$ the exp"e%%i!n e,al&ate a% t"&e* When +e &%e the !" !pe"at!", +e a"e expe#tin( at lea%t !ne %i'e !$ the exp"e%%i!n% a% t"&e* The n!t !pe"at!" all!+% &% t! te%t $!" the !pp!%ite !$ t"&e* &ltiple

#elow is a decision table. 8ecision tables are a popular way of showing the outcome of the entire compound statement by evaluating the outcomes of the two #oolean expressions contained within the compound statement. If you loo! at the first compound and expression you will see the first expression is true and the second expression is also true. Since both expressions by themselves are true the entire expression is true. +or the other values at least one side of the entire expression is false so the entire statement is false.

#oolean expression Dne );9

#oolean expression Two #;5

3ntire Compound 3xpression Dutcome

) < E ,True- # < E ,True- True ) < 9 ,+alse- # < .6 ,True- False ) < F ,True- # < 7 ,+alse- False ) < 9 ,+alse- # < 7 ,+alse- False

Table G1 8ecision table for compound statement )48 compound operator

With the or compound operator only one side of the compound operator expression has to be true. +or the first three values at least one or both side is true. +or the last line neither side is true so the entire compound expression is false.

#oolean expression Dne );9

#oolean expression Two #;5

3ntire Compound 3xpression Dutcome ) < E ,True- # < E ,True- True ) < 9 ,+alse- # < .6 ,True- True ) < F ,True- # < 7 ,+alse- True ) < 9 ,+alse- # < 7 ,+alse- False

Table H1 8ecision table for compound statement I+ compound operator

Programming Tip: =any languages use different terminology for logical operators. ?ou might also see relational operators and compound operators referred to as conditional operators. Compound operators frequently show up as !eywords ,i.e. and or and not- but most commonly as I ,ampersand- for the and J ,single bar- for the or operator and 4ot is frequently shown as an K ,3xclamation- symbol.

Key Concept: ) bloc! of code refers to a series of logic or programming instructions that are executed together as a group. This e#oo! will also refer to if bloc!s as if statements and if structures. 8ecision and repetition structures both use bloc!s to execute statements related to the outcome of a #oolean expression.

Co%poun& Operators' C! p!&n' !pe"at!"% all!+ &% t! 4!in &ltiple l!(i#al exp"e%%i!n% 0exp"e%%i!n% that #!ntain l!(i#al #! pa"i%!n%1* The%e !pe"at!"% #! e in ,e"/ han'/ $!" #! plex 'e#i%i!n% that ha,e %e,e"al #! p!nent% in#l&'e' in the 'e#i%i!n l!(i#*

Status Check Why are relational operators used in #oolean expressions" What is the difference between or and and when used in a boolean expression"


Df all of the control structures we are most familiar with sequenced structures. We have been using sequence in the examples covered in earlier chapters. ) sequence structure represents a process step. )n important part of system theory is that there is one input to the process and one output. )ll control structures including sequence represent the processing step in systems theory. The systems theory rule of one input moving into a process and finally to one output returned is central to the correct use of control structures.


The sequence structure is drawn on a flowchart with two arrows and a rectangle. Dne arrow points to the top of the rectangle and represents the entry point ,input-. The rectangle represents the process and within it a short text message should explain what that step will do. ) final line will drop from the bottom of the rectangle and represent the exit point ,output-. In ,+igure 5- a single sequence structure. %lease note that the example structure is a template and is unlabeled whereas typically it would contain information on what this sequence structure would perform.

+igure 51 ) Sequence Structure demonstrated in an actual application. The sequence structure includes an assignment where the msg variable will hold the literal @2ello World.B


Sequence structures are the easiest of the control structures to flowchart. =ista!es made on sequence structures usually have to do with forgetting to add both an input and output line to the top and bottom of the sequence structure rectangle symbol. ) sequence symbol that only outputs or only inputs data is incorrect.

+igure E1 3xample of valid and invalid sequence flow chart


+lowcharts are designed to provide a flexible graphical alternative to pseudo code for representing computer logic. With pseudo code we have rules regarding the construction of pseudo code statements and recommendations concerning the formatting of pseudo code ,i.e. certain statements should be indented to add clarity to the logic-. +lowcharts also have rules that should be observed when using drawing structures. +lowcharting rules are a combination of requirements necessary to implement structures correctly and also to ma!e the chart easier to read.

#elow I have listed some of the important rules you will want to ta!e in consideration when designing flowcharts. )s with so many topics covered in this e#oo! we cover only the fundamentals of flow charting. To complete your understanding of flowcharts would require some additional study and more practice that is as!ed for than with this e#oo!. Dne of the more popular software tools used to create flowcharts is =icrosofts Lisio software.

Ne,e" #"!%% line% in /!&" $l!+#ha"t e,en i$ the p!%iti!nin( !$ the %/ 2!l% lea,e% /!& little alte"nati,e* It a/ ta.e hi(h le,el !$ a"ti%ti# e$$!"t t! %pa#e /!&" %/ 2!l% t! a,!i' ha,in( the line% #"!%% 2&t i$ /!&C"e %t"&#t&"e i% t! 2e '"a+n t! the "&le% !$ %t"&#t&"e' p"!("a in(, line% #ann!t t!&#h* T!&#hin( #!n$&%e% the "e)&i"e ent !$ !ne inp&t an' !ne !&tp&t*

Ea#h %/ 2!l %h!&l' 2e la2ele' +ith in$!" ati!n 'e%#"i2in( the a#ti,it/ !$ that %/ 2!l* F!" 'e#i%i!n %t"&#t&"e%, +hi#h +e +ill #!,e" %h!"tl/, a.e %&"e ea#h 2"an#h i% la2ele' a% t! +hethe" it "ep"e%ent% the t"&e !" $al%e !&t#! e an' the 'ia !n' %/ 2!l %h!&l' in#l&'e the -!!lean exp"e%%i!n* Se)&en#e %t"&#t&"e% %h!&l' ha,e a text 'e%#"ipti!n !$ +hat i% pe"$!" e' !n that %tep*

C! plete $l!+#ha"t% %h!&l' al+a/% %ta"t +ith a te" inat!" %/ 2!l la2ele' %ta"t an' #!n#l&'e +ith a te" inat!" %/ 2!l la2ele' en'

I$ a $l!+#ha"t nee'% t! 2e '"a+n a#"!%% &ltiple pa(e%, a% i% )&ite $"e)&entl/ the #a%e, the line '"a+n $"! the la%t %/ 2!l !n the pa(e %h!&l' #!ntain a !$$Dpa(e #!nne#t!" %/ 2!l 0"ep"e%ente' in $l!+#ha"t% a% a $i(&"e that i% %)&a"e !n !ne %i'e an' p!inte' !n the !the" D%i ila" t! the h! e plate !n a 2a%e2all 'ia !n'1 +ith a n& 2e" #!ntaine' +ithin it* Y!& %h!&l' %ta"t the next pa(e +ith the #!nne#t!" %/ 2!l an' the #!""e%p!n'in( #!nne#t!" n& 2e" t! in'i#ate +he"e the line #!ntin&e% $"! the p"e,i!&% pa(e*


) sequence structure is represented in pseudo code as a line of instruction. We have discussed in earlier chapters the relationship between pseudo code and flowcharts. ) pseudo code statement representing sequence would typically contain text very similar to what is found within the rectangle of the flowchart. #elow I have included two examples of sequence pseudo code.

messa(e e'uals )ello *orl+ profit e'uals sales less cost

Background Information: Where %rogram Structures +it 2istorically and Today ( Structured programming became popular in the nineteen seventies as a reaction to poorly constructed programs. %oorly constructed programs were difficult and time consuming to maintain. Time is money and programs that are poorly written ta!e longer to develop and maintain. Structured programming methodologies used structures to organi*e logic and ma!e it easier to maintain. %rogrammers using these techniques were more effective and could do more in less time. This was a considered a great benefit to the organi*ation. The development of structured programming techniques was one of the first developments that encouraged the training of disciplined programmers who developed programs using standardi*ed proven professional techniques.


Sequence structures are certainly an important part of program logic but decision structures bring a flexibility and power to our programs that really ma!e programming worth while. It is seldom the case that the stepwise format of

sequence structures alone can handle the complexity necessary for a program to solve even a very simple problem.

8ecision structures are typically implemented with if statements. If statements will always contain a #oolean expression that will consist of logical and compound operators combined with identifiers and expressions. When evaluated the boolean expression will return a value of true or false. If statements support decisions by providing a branching of code via the evaluation of a #oolean expression. If the #oolean expression is true the true branch is followed and a set of instructions associated with the true branch is executed. )n if statement can optionally execute a separate set of instructions ,identified with the else !eyword- if the #oolean expression value is false.

#ottom line a single decision structure implemented with an if statement can only have two outcomes. Dne if branch is executed when the #oolean expression is true and one if branch is when the expression is false. #y combining decisions structures with other control structures ,this process is referred to as nesting- or sequence and repetition structures we can create complex logic within our program to handle a variety of decision scenarios. We will show the power and flexibility of nesting control structures later in the chapter.

If statements can be used in a variety of formats and based on the decision that needs to be implemented. )long with if statements many languages support the case !ey word which is another alternative when implementing a decision that has multiple outcomes. We will spend time on both of these topics with flowchart and pseudo code examples of each.

+igure F1 Single #ranch )nd Two #ranch If Statements.


If statements can be implemented two different ways. )n if statement can be implemented with a single true branch ,true- and if statement can be implemented with two branches ,true and false-. We will tal! about single branch if structures first since they are typically the easiest and least complicated to use. Single #ranch I+ Structures1 8ecision structures are usually implemented as if statements and a single branch if statement provides for a bloc! of instructions to be executed if the associated #oolean expression evaluates as true. It is a requirement of an if bloc! to contain at least a true branch. This if statement does not respond to a false decision.


3arly in the chapter we showed a flowchart of Cust a decision structure. This first flowchart included both true and false branches. In this section we will diagram a real life implementation of a single branch decisions structure. We will save the two branch if statement for later.

=any decisions in program logic need to only test the existence of a true condition. +or example I may need to apply a quantity discounts percent ,.65- when the boo!s purchased exceed a quantity of three. I can implement this decision with an if statement by testing the quantity variable and if that variable is greater than three include in the true branch sequence structures necessary to ma!e the appropriate calculation. If the quantity is less than three the true branch will not be executed in the discounts not applied. In this scenario a false branch is not necessary. There is no logic requirement to create a different calculation if the quantity of boo!s is less than three. This is illustrated in +igure G. 4ote1 This diagram is of Cust the decision structure and not the entire program.

+igure G1 I+ statement example with single true branch


) common error made with decision structure flowcharts is combining multiple logic paths together below decision structures. )lthough it may seem perfectly logical to connect branches from separate if bloc!s into one line to continue to the next structure it is not legal structured programming. 8rawing a flowchart in this manner would is invalid because each if bloc! should have its own output and not a shared output with other if structures.

+igure H1 3xample of an decision structure in sequence structure that share the same output line instead of having their own output line


When implementing decision structures with pseudo code the formatting of the information is important in ensuring that the true and false branches are clearly defined. With most decisions structures each branch will typically contain a series of other structures. To highlight the structures that fall under each branch the pseudo code the statements belonging to each branch are indented to show the relationship to the branch. 3xamine the following pseudo code example1

books,ty e'uals if book,ty >= 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 ;<7. Dnce this #oolean expression is evaluated an outcome of true or false will be returned. If the outcome is true the sequence structures of discount equals .65 and TotCost equals TotCost less ,TotCost times discount- are executed. If the boo!sNty variable had a value of 0 then the #oolean expression would have evaluated as false in the discount calculation would have not been performed. This would be the correct logic solution to process a quantity discount when the customer purchased three are more boo!s.

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 >


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-.

$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 the value 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 distinction between the letter case of identifiers and !eywords. totCost is a different variable than TotCost because the case of the letters are different. >ava and %?T2D4 are case sensitive but Lisual #asic is not.


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.

T o 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 Cust as the true branch did. The false branch is optional.


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 the diamond 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.

+igure .61 I+ Statement with true and false branch


)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.


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 would apply 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 decisions very 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.


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 ...

+igure ..1 I+ Statement with nested I+ statement


)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.

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 Cust 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"

Why must a sequence structure have a line draw into and from the sequence structure symbol" What does nesting of structures mean"


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

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 a different 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 infinite number 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! Cust 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 done at 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 a number of loops. Iteration is done best with another repetition structure called a for loop.


%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 as true. 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.

+igure .01%re(Test and %ost(Test $oop 8iagram


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.

+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 then execute 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 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.

+igure .91 3xample of a repetition structure that does not branch bac! to the decision symbol.


+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 1 print 2n+ of 3ro(ram cnt < 11 is the boolean expression# &hile &ill continue to loop#

4s lon( as it remains true5 the

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.


)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.


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.

+igure .51 ) post(test repetition structure flow chart


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 1 &hile cnt < 11 then print 2n+ of 3ro(ram

( 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 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.

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 words when 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.


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 a while 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.

In Practice' Repetiti!n St"&#t&"e% &%e' $!" 'e#i%i!n%E D 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 %a e a% the -!!lean exp"e%%i!n $!" an i$ %tate ent* -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' ha,e 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(2nter 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.


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

count e'uals % count0o&n e'uals % count9y:i8e e'uals % ;ne = 1 *hile count <= 1% count e'uals count 1 1 count0o&n e'uals count0o&n 6 ;ne count9y:i8e e'uals count9y:i8e 1 3rint count5 count0o&n5 count9y:i8e D He"e +e ha,e a #!&nte" in%i'e the +hile l!!p D An!the" #!&ntin( exa ple* Thi% ti e in#"e entin( 2/ $i,e !n ea#h l!!p* Counting: The counting activity in a program is accomplished by defining and initiali*ing a variable and placing that variable inside a loop. With each iteration of the loop a value is added to the counter to increment or a value is subtracted from the counter to decrement.

)ccumulating is also a popular operation used in program logic. With accumulation and accumulator variable is designated to accumulate a number in an variable. The statements necessary to perform accumulation loo! very similar to the statements that count. Instead of incrementing a counter variable by a set number we will be ta!ing some value or identifier and add this to the accumulator variable on each repetition. The effect is that the accumulator variable grows ,summari*es- on each pass of the loop. In the following pseudo code example we use a counter and accumulator variables to calculate a test average of five test scores.

count e'uals % tot!core e'uals % score e'uals % &hile count < - then 7nput score tot!core e'uals tot!core plus score count e'uals count plus 1 print Tot!core +i8i+e+ by .ount

( totScore is accumulating by ta!ing its previous value and adding score to it on each loop.

'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"


>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

2ere is a pseudo code example of a nested while loop1

outer.ount e'uals 1 inner.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 2n+ of 3ro(ram

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

( 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 while loops 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"


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 #.

$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 O.6 dollars off there order. The O.6 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

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.


!tart 7nput *!.ost markup e'uals 1#2han+lin( e'uals loyalty9onus e'uals % 'uantity0iscount e'uals % 7nput cust=oyal!tatus 7f cust=oyal!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 2n+


?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 2nter .ustomer >ame name 7nput 2nter 9ook >ame or ,, to 'uit book>ame

&hile book>ame <> ,, then 7nput 2nter 9ook 3rice price count e'uals count 1 1 tot3rice e'uals tot3rice 1 price 7nput 2nter 9ook >ame or ,, to 'uit book>ame 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 the end of this customers order.


3arlier in the chapter chapter we covered compound operators which are used to Coin 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 Coin two #oolean expressions but as you Coin 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 each expression 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 =

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. The compound operator Coins expression one and expression two first. Since expression one is false and expression two is true and they are Coined 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 Coined 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.


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


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

+or this loop to continue into the quantity must be greater than 6 and the partCode must be equal to the literal @)B.


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 to understand. 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 all about 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

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.


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 these documents 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 %a e n& 2e" !$ %pa#e%* Ne%te' i$ %tate ent% %h!&l' $i"%t line &p +ith !the" 2"an#h %tate ent% +ith thei" 2"an#he% in'ente' the %a e n& 2e" !$ %pa#e%* Sepa"ate %t"&#t&"e% +ith a 2lan. line in /!&" %!&"#e #!'e* C"a in( all the line% t!(ethe" +ith n! ,i%&al 2"ea.% a.e% %e#ti!n% !$ the #!'e !"e 'i$$i#&lt 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' (i,e (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 %tate ent !" !n the p"e,i!&% 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

total.ost = 1 total!ale = % ext.ost = % subTotal = % 'ty = % tot4ll!ales = % 07!.1% = #1% 07!.%- = #%!4=2!T4@ = #%A &hile 'ty B= 61C 'ty = input(D2nter ,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=2!T4@) tot4ll!ales = tot4ll!ales 1 total!ale print DTotal !ale plus tax is CD5 total!ale print DTotal 4ll !ales C D 5 tot4ll!ales


Comments mar!ed with P ,pound- sign.

Epro(ram 8ariables total.ost = 1 total!ale = % ext.ost = % subTotal = % 'ty = % tot4ll!ales = % 07!.1% = #1% 07!.%- = #%!4=2!T4@ = #%A Emain lo(ic starts here

Eloop &hile 'ty is not e'ual to 61 &hile 'ty B= 61C Eprompt for 'uantity 'ty = input(D2nter ,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=2!T4@) tot4ll!ales = tot4ll!ales 1 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.


Chapter summary highlights !ey terms short answer questions qui**es and case studies to reinforce topics covered in this chapter.

)fter finishing this chapter you should understand and in some cases demonstrate the following topics1 Explain the i p!"tan#e !$ %t"&#t&"e' p"!("a o C!nt"!l %t"&#t&"e% all!+ p"!("a 'e#i%i!n an' "epetiti!n %&pp!"t* in( te#hni)&e% in #"eatin( p"!("a %*

e"% t! 2&il' #! plex appli#ati!n% 2/ p"!,i'in(

When &%in( $l!+#ha"t% t! #"eate %t"&#t&"e' p"!("a in( l!(i# 'e%i(n%, ea#h %/ 2!l %h!&l' ha,e !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' %&"e n! line% in the 'ia("a #"!%%* P%e&'! #!'e ha% %t"i#t "e)&i"e ent% "e(a"'in( the in'entin( !$ %tate ent% that $all &n'e" the t"&e an' $al%e 2"an#h !$ the -!!lean exp"e%%i!n* When a %t"&#t&"e #all% an!the" %t"&#t&"e 2e#a&%e !$ the e,al&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%* !'elin( an' p"!("a in(*

Explain the i p!"tan#e i$ #!nt"!l% %t"&#t&"e% t! l!(i# 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$ %tate ent 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' i ple ent %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 %i ple%t !$ #!nt"!l %t"&#t&"e% 2&t the !%t #! !n* Se)&en#e %t"&#t&"e% h!l' %tate ent% an' exp"e%%i!n% that #!n%tit&te !%t !$ the in%t"&#ti!n% %ent t! the #! p&te"* De#i%i!n %t"&#t&"e% p"!,i'e 'e#i%i!n %&pp!"t $!" !&" l!(i# an' p"!("a %* Th"!&(h the i ple entati!n !$ i$ %tate ent%, a l!(i# 'e#i%i!n ha% a t"&e !" $al%e !&t#! e* The 'e#i%i!n %t"&#t&"e i% i ple ente' +ith a 2!!lean exp"e%%i!n that e,al&ate% a% t"&e !" $al%e* De#i%i!n %t"&#t&"e% a/ 2e ne%te'* Thi% #an #!ntain a ne+ 'e#i%i!n% %t"&#t&"e* A 'e#i%i!n %t"&#t&"e !&t#! e* ean% a 2"an#h !$ a 'e#i%i!n %t"&#t&"e

&%t a t"&e !&t#! e an' #an !pti!nall/ #!ntain a $al%e

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% %i pli$/ l!(i# that #!&l' !the"+i%e nee' t! #!ntain an/ !"e "epeate' l!(i# %tate ent%*

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"eDte%t l!!. a/ n!t exe#&te the l!!p l!(i# &nle%% the -!!lean exp"e%%i!n e,al&ate% a% t"&e an' the p!%tDte%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 e,al&ate% a% t"&e* 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#"e ent !" 'e#"e ent the %a e !n ea#h l!!p an' a##& &latin( +ill %& a n& 2e" int! a ,a"ia2le $!" ea#h l!!p*


)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