Chapter 5 Computer Science I: Systems Engineering Focus .

2y ago
24 Views
3 Downloads
276.95 KB
9 Pages
Last View : 28d ago
Last Download : 3m ago
Upload by : Jenson Heredia
Transcription

Chapter 5Computer Science & Engineering 155EComputer Science I: Systems Engineering FocusLecture 05 - Loops5.1 Repetition in Programs5.2 Counting Loops and the While Statement5.3 Computing a Sum or a Product in a Loop5.4 The for Statement5.5 Conditional LoopsChristopher M. Bourkecbourke@cse.unl.edu5.6 Loop Design5.7 Nested Loops5.8 Do While Statement and Flag-Controlled Loops5.10 How to Debug and Test5.11 Common Programming ErrorsRepetition in ProgramsJust as the ability to make decisions (if-else selection statements) is animportant programming tool, so too is the ability to specify the repetition ofa group of operations.Counting LoopsA counter-controlled loop (or counting loop) is a loop whose repetition ismanaged by a loop control variable whose value represents a count. Alsocalled a while loop.When solving a general problem, it is sometimes helpful to write a solution toa specific case. Once this is done, ask yourself:2IWere there any steps that I repeated? If so, which ones?3IDo I know how many times I will have to repeat the steps?4IIf not, how did I know how long to keep repeating the steps?5The C While LoopThis while loop computes and displays the gross pay for seven employees.The loop body is a compound statement (between brackets) The looprepetition condition controls the while loop.12345678910111int count emp 0;// Set counter to 0while ( count emp 7) { // If count emp 7 , do stmtsprintf ( " Hours " );scanf ( " % d " ,& hours );printf ( " Rate " );scanf ( " % lf " ,& rate );pay hours * rate ;printf ( " Pay is %6.2 f \ n " , pay );count emp count emp 1; /* Increment count emp */}printf ( " \ nAll employees processed \ n " );Set counter to an initial value of 0 ;while counter someF inalV alue doBlock of program code ;Increase counter by 1 ;endAlgorithm 1: Counter-Controlled LoopWhile Loop SyntaxSyntax of the while Statement:IInitialize the loop control variableITest the loop control variable before the start of each loop repetitionUpdate the loop control variable during the iterationIIIWithout initialization, the loop control variable value is meaningless.Ensures that the program progresses to the final goal1 count 1;2 while ( count 10) {3printf ( " Count % d \ n " , count );4count count 1;5 }

Common Programming ErrorsGeneral While LoopsBest to generalize code whenever possible.ISkipping crucial steps could lead to an infinite loopICommon error: forgetting to increment your loop control variableISyntax error: misplaced semicolons1 count 1;2 while ( count 10); WRONG3 {4printf ( " Count % d \ n " , count );5count count 1;6 }While Loop Exercise1 int numEmployees 7 ,2 count emp 0;3 printf ( " How many employees " );4 scanf ( " % d " , & numEmployees );5 while ( count emp numEmployees ) {6. . .7count emp count emp 1;8 }Using numEmployees instead of the constant 7 allows our code to be moregeneral.While Loop ExerciseAnswerExerciseWrite a while loop to compute the sum of natural numbers 1 to 100:100Xi 1i 1 2 · · · 100Generalize the loop so that the sum from 1 to any n can be computed.Steps to design:IIdentify and define a loop control variable.IWrite the syntax for the loop control structureIFill in the code used within the loop to compute the sumWhile Loop ExerciseAnswer: Generalized12345678910int sum 0;int n 100; /* general variable , may be* changed or read from input */int i 1;/* our loop control variable */while ( i n ){sum sum i ;i i 1;}printf ( " Sum 1 to % d is % d \ n " , n , sum );12345678int sum 0;int i 1;/* our loop control variable */while ( i 100){sum sum i ;i i 1;}printf ( " Sum is % d \ n " , sum );While Loop Example IIInstead of the sum of integers 1 to n, compute the product:100Yi 1i 1 2 . . . 100What changes need to be made?IVariable names?IInitialized variable value?IOperators?Note: this is the factorial function,n! nYi 1i

While Loop Example IIProgram FailedAnswer12345678910int product 1;int n 100; /* general variable , may be* changed or read from input */int i 1;/* our loop control variable */while ( i n ){product product * i ;i i 1;}printf ( " Product 1 to % d is % d \ n " , n , product );OverflowIRun the previous program: it gives an answer of 0—why?IDebug your code: use a printf statement in the loop to see whatintermediate values are computed:printf("i %3d product %d\n",i,product);ICheck the answers with a calculatorIFor what i does this program fail?Compound Assignment OperatorsWe got the wrong answer for i 13,13! 6, 227, 020, 800IWe used a 32-bit integer to store productIMaximum representable value is 231 2, 147, 483, 648IWhen a number is too large (or too small!) to be represented by itstype, overflow occurs (or underflow)IMore sophisticated solutions are available, but beyond this courseIExpressions such as variable variable op expression; (whereop is a C operator such as ,-,*,/,) occur frequentlyIC provides several syntax shortcutsIx x 1; and x 1; are “equivalent”ICan do this with other operators (see table)Expressionx x 1;x x - 1;x x * 5;x x / 2;Shortcutx 1;x - 1;x * 5;x / 2;Table: Compound Assignment OperatorsCompound Assignment OperatorsFor LoopsExample Revisited12345678910int product 1;int n 100; /* general variable , may be* changed or read from input */int i 1;/* our loop control variable */while ( i n ){product * i ;i 1;}printf ( " Product 1 to % d is % d \ n " , n , product );IProgram StyleIIncrement and Decrement OperatorsIIncrement and Decrement Other Than 1

For LoopsFor Loop ExampleComputing the sum using a for-loop:IAny repetition can be implemented using a while loopIAnother way to construct a counting loop is to use a for loopIC provides for statements as another form for implementing loops.IAs before we need to initialize, test, and update the loop control variable.IThe syntax for a for statement is more rigid: it designates a specificplace for the initialization, testing, and update componentsIncrement OperatorsINew syntax: i IKnown as a (postfix) incrementI“Equivalent” to i i 1IAlso available: (postfix) decrement: i-- (“equivalent” to i i - 1)Increment and Decrement OperatorsThe counting loops that we have seen have all included assignmentexpressions of the formIcounter counter 1Icounter Icounter 1This will add 1 to the variable counter.Using -- will subtract one from the counter.1234567int sum 0;int n 100;int i ;for ( i 0; i n ; i ){sum sum i ;}IAdvantages: more readable, more predictableIEasier to debugIPitfall: note the placement of semicolons!Program StyleFor clarity, the book usually places each expression of the for heading on aseparate line. If all three expressions are very short, however, they will beplaced on one line.The body of the for loop is indented just as the if statement.Increment and Decrement Other Than 1We can use the “shortcut” compound assignment operators with values otherthan 1IIncrement operations: sum sum x or sum x, will take thevalue of sum, add x to it, and then assign the new value to sumIDecrement operations: temp temp - x or temp - x, will take thevalue of temp, subtract x from it and then assign the new value to temp

Increment and Decrement Other Than 1Conditional LoopsExample12345678910/* increment by 10 */int x 10;int i ;for ( i 0; i 100; i x )printf ( " i % d \ n " ,i );/* decrement by 5 */int y 5;for ( i 25; i 0; i - y )printf ( " i % d \ n " ,i );ExerciseIThe exact number of loop repetitions we need to run for a loop will notalways be known before loop execution begins.Initialization step? Test? Update action?ExercisePseudocode1Exercise23Create a program that prompts the user for a value x and multiplies it by theprevious value of x storing the result in x until the user enters a 0.456ExerciseSet x to an initial value of 1 ;Prompt the user for a value input;while input is not zero doSet x to x multiplied by input;Prompt the user for a new input value ;endAlgorithm 2: Prompt Product LoopLoop DesignTranslated to C1234567891011int x 1;int value ;printf ( " Enter a value , (0 to quit ) " );scanf ( " % d " ,& value );while ( value ! 0){x x * value ;printf ( " Enter a value , (0 to quit ) " );scanf ( " % d " ,& value );}printf ( " The product is % d " , value );To this point, we have been analyzing the actions a loop performs.Now, we also want to design our own loops:ISentinel-Controlled LoopsIUsing a for Statement to Implement a Sentinel Loop

Sentinel-Controlled LoopsIOften we don’t know how many data items the loop should processwhen it begins execution.ISentinel-Controlled Loops continue to read data until a unique datavalue is read, called the sentinel value.IThe sentinel value should be a value that could not normally occur asdata.IReading the sentinel value signals the program to stop reading andprocessing new data and exit the loop.IExample: Product of a list of numbers, with 1 stopping the loop.Implementing a Sentinel LoopSentinel-Controlled Loops1234Get a line of data ;while Sentinel value is not encountered doProcess the data ;Get another line of data ;5 endAlgorithm 3: Product Loop using a SentinelImplementing a Sentinel LoopBecause the for statement combines the initialization, test, and update inonce place, some programmers prefer to use it to implementsentinel-controlled loops.123456789Iint sentinelValue -1;int score 0printf ( " Enter first score (% d to quit ) " , sentinelValue );for ( scanf ( " % d " ,& score );score ! sentinelValue ;scanf ( " % d " ,& score )) {sum score ;printf ( " Enter next score (% d to quit ) " , sentinelValue );}Nested LoopsLike if statements, loops can also be nested.INested loops consist of an outer loop with or more inner loops.IEach time the outer loop is repeated, the inner loops are reentered.IThe inner loop control expressions are reevaluated, and all requirediterations are performed.IIscanf("%d",&score); Initialization: read the first scorescore ! sentinelValue; Terminating condition (test)scanf("%d",&score)) {. Update: read another scoreExample123456789101112int i , j ;for ( i 1; i 10; i ){for ( j 1; j 10; j ){if (j i )printf ( " " );elseprintf ( " * " );}printf ( " \ n " );}

Example - Output12345678910The do-while Statement and Flag-Controlled Loops********** ********* ******** ******* ****** ***** **** *** ** *Do-While StatementIdo-while statementIflag-controlled loopsDo WhileExampleIIThe for statement and the while statement evaluate conditions beforethe first execution of the loop body.In most cases, this pretest is desirable;IIIPrevents the loop from executing when there are no data items to processPrevents execution when the intimal value of the loop control variable isoutside the expected range.char letter choice ;do {printf ( " Enter a letter from A through E " );scanf ( " % c " , & letter choice );} while ( letter choice ’A ’ letter choice ’E ’ );Situations involving interactive input, when we know that a loop mustexecute at least one time, often use a do-while loop.Do WhileI12345Loop begins with doIEnds with whileICareful: Conditional expression does end with a semicolon!IConditional is checked at the end of each loop (versus the beginning)Flag-Controlled LoopsIISometimes a loop repetition condition becomes so complex that placingthe full expression in its usual spot is awkward.In many cases, the condition may be simplified by using a flag.IIA flag is a type int variable used to represent whether or not a certainevent has occurred.A flag has one of two values: 1 (true) and 0 (false).

FlagHow to Debug and Test ProgramsExample12345678char letter choice ;int isDone 0;while (! isDone ){printf ( " Enter a letter from A through E " );scanf ( " % c " , & letter choice );isDone ( letter choice ’A ’ && letter choice ’E ’ );}Debugging using printfIDebugging using printfIOff-by-One Loop ErrorsITestingOff-by-One Loop ErrorsLoop boundaries - the initial and final values of the loop control variable.IIUse several printf statements to output the values of your variables tomake sure they have the correct value in them as your program executes.IIt is often helpful to print out the value of your loop control variable tomake sure you are incrementing it and will not enter an infinite loop.A fairly common logic error in programs with loops is a loop thatexecutes one more time or one less time than required.IIIf a loop performs a counting operation, make sure that the initial andfinal values of the loop control variable are correct and that the looprepetition condition is right.IITestingAfter all errors have been corrected and the program appears to execute asexpected, the program should be tested thoroughly to make sure it works.For a simple program, make enough test runs to verify that the programworks properly for representative samples of all possible data combinations.If a sentinel-controlled loop performs an extra repetition, it mayerroneously process the sentinel value along with the regular data.The sum of 1 . . . 100, is not for(i 1; i 100; i ) sum i;Instead, i 100 should be used.Common Programming Errors IIif and while statement can be confused, since they have similarappearance.IRemember to initialize loop control variable as to prevent infinite loops.IInfinite loops are bad: kill your program using control-CIRemember to use brackets { . } around the code of the loopstatements.

Common Programming Errors IIIBe careful about the loop conditions, if we only want positive resultsthen if(result ! 0) would not work since result might becomenegative without ever being 0.Ido-while loops always executes once and then tests the condition.IWith the compound assignment operators, the parentheses are assumedto be around any expression that is the second operand.Real World ExampleReal World ExampleIZune Bug: December 31st, 2008I2008 was a leap year: 366 daysIThousands of Zunes froze for 24 hoursIAn embedded module in the Zune contained the following (actual) codeOther ExamplesWhat happened?12345678910111213141516while ( days 365){if ( IsLeapYear ( year )){if ( days 366){days - 366;year 1;}}else{days - 365;year 1;}}QuestionsQuestions?ISeptember 30, 1999: 125 million Mars orbiter crashesISeptember 26, 1983: Stanislav Petrov averts nuclear warIWired Article: History’s Worst Software Bugs 11/69355)

A counter-controlled loop (or counting loop ) is a loop whose repetition is managed by a loop control variable whose value represents a count. Also called a while loop. 1 Set counter to an initial value of 0 ; 2 while counter someFinalValue do 3 Block of program code ; 4 Increase counter by 1 ; 5 end Algorithm 1: Counter-Controlled Loop The C .

Related Documents:

Part One: Heir of Ash Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 Chapter 24 Chapter 25 Chapter 26 Chapter 27 Chapter 28 Chapter 29 Chapter 30 .

Texts of Wow Rosh Hashana II 5780 - Congregation Shearith Israel, Atlanta Georgia Wow ׳ג ׳א:׳א תישארב (א) ׃ץרֶָֽאָּהָּ תאֵֵ֥וְּ םִימִַׁ֖שַָּה תאֵֵ֥ םיקִִ֑לֹאֱ ארָָּ֣ Îָּ תישִִׁ֖ארֵ Îְּ(ב) חַורְָּ֣ו ם

TO KILL A MOCKINGBIRD. Contents Dedication Epigraph Part One Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Part Two Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18. Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 Chapter 24 Chapter 25 Chapter 26

DEDICATION PART ONE Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 PART TWO Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 .

About the husband’s secret. Dedication Epigraph Pandora Monday Chapter One Chapter Two Chapter Three Chapter Four Chapter Five Tuesday Chapter Six Chapter Seven. Chapter Eight Chapter Nine Chapter Ten Chapter Eleven Chapter Twelve Chapter Thirteen Chapter Fourteen Chapter Fifteen Chapter Sixteen Chapter Seventeen Chapter Eighteen

18.4 35 18.5 35 I Solutions to Applying the Concepts Questions II Answers to End-of-chapter Conceptual Questions Chapter 1 37 Chapter 2 38 Chapter 3 39 Chapter 4 40 Chapter 5 43 Chapter 6 45 Chapter 7 46 Chapter 8 47 Chapter 9 50 Chapter 10 52 Chapter 11 55 Chapter 12 56 Chapter 13 57 Chapter 14 61 Chapter 15 62 Chapter 16 63 Chapter 17 65 .

HUNTER. Special thanks to Kate Cary. Contents Cover Title Page Prologue Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter

Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 . Within was a room as familiar to her as her home back in Oparium. A large desk was situated i