第10版教輔含答案testbank實(shí)驗(yàn)手冊(cè)等_第1頁(yè)
第10版教輔含答案testbank實(shí)驗(yàn)手冊(cè)等_第2頁(yè)
第10版教輔含答案testbank實(shí)驗(yàn)手冊(cè)等_第3頁(yè)
第10版教輔含答案testbank實(shí)驗(yàn)手冊(cè)等_第4頁(yè)
第10版教輔含答案testbank實(shí)驗(yàn)手冊(cè)等_第5頁(yè)
已閱讀5頁(yè),還剩113頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、Chapter 3More Flow of ControlOverview3.1 Using Boolean Expressions 3.2 Multiway Branches3.3 More about C+ Loop Statements3.4 Designing LoopsSlide 3- 3Flow Of ControlFlow of control refers to the order in which program statements are performedWe have seen the following ways to specify flow of control

2、if-else-statementswhile-statementsdo-while-statementsNew methods described in this chapter includeswitch-statementsfor-statementsSlide 3- 43.1Using Boolean ExpressionsUsing Boolean ExpressionsA Boolean Expression is an expression that is either true or falseBoolean expressions are evaluated using re

3、lational operations such as= = , = which produce a boolean valueand boolean operations such as&, | |, and ! which also produce a boolean valueType bool allows declaration of variables thatcarry the value true or falseSlide 3- 6Evaluating Boolean ExpressionsBoolean expressions are evaluated using val

4、uesfrom the Truth Tables inFor example, if y is 8, the expression !( ( y 7) ) is evaluated in the following sequenceSlide 3- 7Display 3.1! ( false | | true )! ( true )falseOrder of PrecedenceIf parenthesis are omitted from boolean expressions, the default precedence of operations is:Perform ! operat

5、ions firstPerform relational operations such as 2 | | (x + 1) 2) | | ( ( x + 1) and 2 | | x + 1 2 | | x + 1 and = 0) & ( y 1)can be determined by evaluating only (x = 0)C+ uses short-circuit evaluation If the value of the leftmost sub-expression determines the final value of the expression, the rest

6、 of the expression is not evaluatedSlide 3- 12Using Short-Circuit EvaluationShort-circuit evaluation can be used to preventrun time errorsConsider this if-statement if (kids != 0) & (pieces / kids = 2) ) cout = 2) Division by zero causes a run-time errorSlide 3- 13Type bool and Type intC+ can use in

7、tegers as if they were Boolean valuesAny non-zero number (typically 1) is true0 (zero) is falseSlide 3- 14Problems with !The expression ( ! time limit ), with limit = 60, is evaluated as (!time) limit If time is an int with value 36, what is !time?False! Or zero since it will be compared to an integ

8、erThe expression is further evaluated as 0 limit falseSlide 3- 15Correcting the ! ProblemThe intent of the previous expression was most likely the expression ( ! ( time limit) )which evaluates as ( ! ( false) ) trueSlide 3- 16Avoiding !Just as not in English can make things not undifficult to read,

9、the ! operator canmake C+ expressions difficult to understandBefore using the ! operator see if you can express the same idea more clearly withoutthe ! operatorSlide 3- 17Enumeration Types (Optional)An enumeration type is a type with values defined by a list of constants of type intExample:enum Mont

10、hLengthJAN_LENGTH = 31, FEB_LENGTH = 28, MAR_LENGTH = 31, DEC_LENGTH = 31;Slide 3- 18Default enum ValuesIf numeric values are not specified, identifiersare assigned consecutive values starting with 0enum Direction NORTH = 0, SOUTH = 1, EAST = 2, WEST = 3;is equivalent toenum Direction NORTH, SOUTH,

11、EAST, WEST;Slide 3- 19Enumeration ValuesUnless specified, the value assigned an enumeration constant is 1 more than the previousconstantenum MyEnumONE = 17, TWO, THREE, FOUR = -3, FIVE;results in these valuesONE = 17, TWO = 18, THREE = 19, FOUR = -3, FIVE = -2Slide 3- 20Strong EnumsC+11 introduced a

12、 new version of enumeration called strong enums or enum classes that avoids some problems of conventional enumsMay not want an enum to act like an intEnums are global so you cant have the same enum value twiceDefine a strong enum as follows:Slide 3- 21Using Strong EnumsTo use our strong enums:Days d

13、 = Days:Tue;Weather w = Weather:Sun;The variables d and w are not integers so we cant treat them as such.Slide 3- 22Section 3.1 ConclusionCan youWrite a function definition for a function named in_order that takes three arguments of type int?The function returns true if the arguments are inascending

14、 order; otherwise, it returns false.Determine the value of these Boolean expressions?Assume count = 0 and limit = 10(count = 0) & (limit 20)!(count = 12)(limit 7)Slide 3- 233.2Multiway BranchesMultiway BranchesA branching mechanism selects one out of a number of alternative actionsThe if-else-statem

15、ent is a branching mechanismBranching mechanisms can be a subpart of another branching mechanismAn if-else-statement can include anotherif-else-statement as a subpartSlide 3- 25Nested StatementsA statement that is a subpart of another statementis a nested statementWhen writing nested statements it i

16、s normal to indent each level of nestingExample: if (count 10) if ( x y) cout x is less than y; else cout y is less than ) then: output a statement saying dont stopSlide 3- 27First Try Nested ifsTranslating the previous pseudocode to C+ could yield (if we are not careful)if (fuelGaugeReading 0.75) i

17、f (fuelGaugeReading 0.25) cout Fuel very low. Caution!n;else cout number) cout Too high.;else if (guess number) cout Too low.); else if (guess = number) cout number) cout Too high.;else if (guess number) cout Too low.);else if (guess = number) cout number) cout Too high.;else if (guess number) cout

18、Too low.);else / (guess = number) cout 15000 & e = 25000)can be replaced with else if ( e 15000Slide 3- 36The switch-statementThe switch-statement is an alternative for constructing multi-way branchesThe example in Display 3.6 determines output based on a letter gradeGrades A, B, and C each have a b

19、ranchGrades D and F use the same branchIf an invalid grade is entered, a default branch is usedSlide 3- 37Display 3.6 (1)Display 3.6 (2)switch-statement Syntaxswitch (controlling expression) case Constant_1: statement_Sequence_1break; case Constant_2: Statement_Sequence_2 break; . . . case Constant_

20、n: Statement_Sequence_n break; default: Default_Statement_SequenceSlide 3- 38The Controlling StatementA switch statements controlling statement must return one of these typesA bool value An enum constantAn integer typeA characterThe value returned is compared to the constant values after each caseWh

21、en a match is found, the code for that case is usedSlide 3- 39The break StatementThe break statement ends the switch-statementOmitting the break statement will cause the code for the next case to be executed!Omitting a break statement allows the use of multiple case labels for a section of codecase

22、A:case a: cout Excellent.; break;Runs the same code for either A or aSlide 3- 40The default StatementIf no case label has a constant that matches the controlling expression, the statements followingthe default label are executedIf there is no default label, nothing happens when the switch statement

23、is executedIt is a good idea to include a default sectionSlide 3- 41Switch-statements and MenusNested if-else statements are more versatile thana switch statementSwitch-statements can make some code more clearA menu is a natural application for a switch-statementSlide 3- 42Display 3.7 (1)Display 3.7

24、 (2)Function Calls in BranchesSwitch and if-else-statements allow the use of multiple statements in a branchMultiple statements in a branch can make the switch or if-else-statement difficult to readUsing function calls (as shown in Display 3.7)instead of multiple statements can make the switch or if

25、-else-statement much easier to readSlide 3- 43BlocksEach branch of a switch or if-else statement isa separate sub-taskIf the action of a branch is too simple to warrant a function call, use multiple statements between bracesA block is a section of code enclosed by bracesVariables declared within a b

26、lock, are local to the block or have the block as their scope.Variable names declared in the block can be reused outsidethe blockSlide 3- 44Display 3.8 (1)Display 3.8 (2)Statement BlocksA statement block is a block that is not a functionbody or the body of the main part of a programStatement blocks

27、can be nested in otherstatement blocksNesting statement blocks can make code difficult toreadIt is generally better to create function calls than to nest statement blocksSlide 3- 45Scope Rule for Nested BlocksIf a single identifier is declared as a variable ineach of two blocks, one within the other

28、, then these are two different variables with the same nameOne of the variables exists only within the inner block and cannot be accessed outside the innerblockThe other variable exists only in the outer block andcannot be accessed in the inner blockSlide 3- 46Section 3.2 ConclusionCan youGive the o

29、utput of this code fragment? int x = 1; cout x endl; cout x endl; int x = 2; cout x endl; cout x endl;Slide 3- 473.3More About C+ LoopStatementsMore About C+ Loop StatementsA loop is a program construction that repeats a statement or sequence of statements a number of timesThe body of the loop is th

30、e statement(s) repeatedEach repetition of the loop is an iterationLoop design questions:What should the loop body be?How many times should the body be iterated?Slide 3- 49while and do-whileAn important difference between while anddo-while loops:A while loop checks the Boolean expression at the begin

31、ning of the loopA while loop might never be executed!A do-while loop checks the Boolean expression at the end of the loopA do-while loop is always executed at least onceReview while and do-while syntax in Slide 3- 50Display 3.9The Increment OperatorWe have used the increment operator instatements su

32、ch as number+;to increase the value of number by oneThe increment operator can also be used in expressions: int number = 2; int valueProduced = 2 * (number+);(number+) first returns the value of number (2) to be multiplied by 2, then increments number to threeSlide 3- 51number+ vs +number(number+) r

33、eturns the current value of number,then increments numberAn expression using (number+) will usethe value of number BEFORE it is incremented(+number) increments number first and returns the new value of numberAn expression using (+number) will use the value of number AFTER it is incrementedNumber has

34、 the same value after either version!Slide 3- 52+ Comparisonsint number = 2;int valueProduced = 2 * (number+);cout valueProduced number;displays 4 3int number = 2;int valueProduced = 2* (+number);cout valueProduced number;displays 6 3Slide 3- 53Display 3.10The Decrement OperatorThe decrement operato

35、r (-) decreases the value of the variable by oneint number = 8; int valueProduced = number-;cout valueProduced number; displays 8 7Replacing number- with -number displays 7 7Slide 3- 54The for-StatementA for-Statement (for-loop) is another loopmechanism in C+Designed for common tasks such as adding

36、numbers in a given rangeIs sometimes more convenient to use than a while loopDoes not do anything a while loop cannot doSlide 3- 55for/while Loop Comparisonsum = 0;n = 1;while(n = 10) / add the numbers 1 - 10 sum = sum + n; n+; sum = 0;for (n = 1; n = 10; n+) /add the numbers 1 - 10 sum = sum + n;Sl

37、ide 3- 56For Loop DissectionThe for loop uses the same components as the while loop in a more compact formfor (n = 1; n = 10; n+)Slide 3- 57Initialization ActionBoolean ExpressionUpdate Actionfor Loop AlternativeA for loop can also include a variable declarationin the initialization actionfor (int n

38、 = 1; n = 10; n+)This line meansCreate a variable, n, of type int and initialize it with 1Continue to iterate the body as long as n = 10Increment n by one after each iterationFor-loop syntax and while loop comparison are found inSlide 3- 58Display 3.11for-loop DetailsInitialization and update action

39、s of for-loops often contain more complex expressionsHere are some samplesfor (n = 1; n -100 ; n = n -7) for(double x = pow(y,3.0); x 2.0; x = sqrt(x) )Slide 3- 59The for-loop BodyThe body of a for-loop can beA single statementA compound statement enclosed in bracesExample: for(int number = 1; numbe

40、r = 0; number-) / loop body statements shows the syntax for a for-loop with a multi-statement bodySlide 3- 60Display 3.13The Empty StatementA semicolon creates a C+ statementPlacing a semicolon after x+ creates the statementx+;Placing a semicolon after nothing creates an empty statement that compile

41、s but does nothing cout Hello endl; ; cout Good Bye endl;Slide 3- 61Extra SemicolonPlacing a semicolon after the parentheses of a for loop creates an empty statement as the body of the loopExample:for(int count = 1; count = 10; count+); cout Hellon;prints one Hello, but not as part of the loop!The e

42、mpty statement is the body of the loopcout Hellon; is not part of the loop body!Slide 3- 62Local Variable StandardANSI C+ standard requires that a variable declared in the for-loop initialization section be local to the block of the for-loopFind out how your compiler treats thesevariables!If you wan

43、t your code to be portable, do notdepend on all compilers to treat these variablesas local to the for-loop!Slide 3- 63Which Loop To Use?Choose the type of loop late in the design processFirst design the loop using pseudocodeTranslate the pseudocode into C+The translation generally makes the choice o

44、f anappropriate loop clearWhile-loops are used for all other loops when there might be occassions when the loop should not runDo-while loops are used for all other loops when the loop must always run at least onceSlide 3- 64Choosing a for-loopfor-loops are typically selected when doing numeric calcu

45、lations, especially when usinga variable changed by equal amounts each time the loop iteratesSlide 3- 65Choosing a while-loopA while-loop is typically used When a for-loop is not appropriateWhen there are circumstances for which the loop body should not be executed at allSlide 3- 66Choosing a do-whi

46、le LoopA do-while-loop is typically usedWhen a for-loop is not appropriateWhen the loop body must be executed at least onceSlide 3- 67The break-StatementThere are times to exit a loop before it ends If the loop checks for invalid input that would ruin a calculation, it is often best to end the loop

47、The break-statement can be used to exit a loop before normal terminationBe careful with nested loops! Using break only exits the loop in which the break-statement occursSlide 3- 68Display 3.14Section 3.3 ConclusionCan youDetermine the output of the following? for(int count = 1; count 5; count+) cout

48、 (2 * count) next; sum = sum + next; end of loopThis pseudocode can be implemented with a for-loopas shown on the next slideSlide 3- 72for-loop for a sumThe pseudocode from the previous slide is implemented as int sum = 0;for(int count=1; count next; sum = sum + next; sum must be initialized prior t

49、o the loop body!Slide 3- 73Repeat this many timesPseudocode containing the line repeat the following this many timesis often implemented with a for-loopA for-loop is generally the choice when there is a predetermined number of iterations Example: for(int count = 1; count = this_many; count+) Loop_bo

50、dySlide 3- 74for-loop For a ProductForming a product is very similar to the sumexample seen earlierint product = 1;for(int count=1; count next; product = product * next; product must be initialized prior to the loop bodyNotice that product is initialized to 1, not 0!Slide 3- 75Ending a LoopThe are f

51、our common methods to terminatean input loopList headed by size When we can determine the size of the list beforehandAsk before iteratingAsk if the user wants to continue before each iterationList ended with a sentinel value Using a particular value to signal the end of the listRunning out of inputU

52、sing the eof function to indicate the end of a fileSlide 3- 76List Headed By SizeThe for-loops we have seen provide a naturalimplementation of the list headed by size method of ending a loopExample: int items; cout items; for(int count = 1; count = items; count+) int number; cout Enter number number

53、; cout endl;/ statements to process the number Slide 3- 77Ask Before IteratingA while loop is used here to implement the askbefore iterating method to end a loopsum = 0;cout ans;while ( ans = Y) | (ans = y) /statements to read and process the number cout ans; Slide 3- 78List Ended With a Sentinel Va

54、lueA while loop is typically used to end a loop usingthe list ended with a sentinel value methodcout Enter a list of nonnegative integers.n number;while (number 0) /statements to process the number cin number; Notice that the sentinel value is read, but not processedSlide 3- 79Running Out of InputTh

55、e while loop is typically used to implement therunning out of input method of ending a loopifstream infile;infile.open(data.dat);while (! infile.eof( ) ) / read and process items from the file/ File I/O covered in Chapter 6 infile.close( );Slide 3- 80General Methods To Control LoopsThree general met

56、hods to control any loopCount controlled loopsAsk before iteratingExit on flag conditionSlide 3- 81Count Controlled LoopsCount controlled loops are loops that determinethe number of iterations before the loop beginsThe list headed by size is an example of a count controlled loop for inputSlide 3- 82

57、Exit on Flag ConditionLoops can be ended when a particular flag condition exists A variable that changes value to indicate that some event has taken place is a flagExamples of exit on a flag condition for inputList ended with a sentinel value Running out of inputSlide 3- 83Exit on Flag CautionConsid

58、er this loop to identify a student with a grade of 90 or betterint n = 1;grade = computeGrade(n); while (grade 90) n+; grade = computeGrade(n); cout Student number n has a score of grade endl;Slide 3- 84The ProblemThe loop on the previous slide might not stop atthe end of the list of students if no

59、student has agrade of 90 or higherIt is a good idea to use a second flag to ensure that there are still students to considerThe code on the following slide shows a better solutionSlide 3- 85The Exit On Flag SolutionThis code solves the problem of having no student grade at 90 or higher int n=1;grade

60、 = computeGrade(n);while ( grade 90) & ( n 90) / same output as before else cout No student has a high score.;Slide 3- 86Nested LoopsThe body of a loop may contain any kind of statement, including another loopWhen loops are nested, all iterations of the inner loop are executed for each iteration of

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論