2 Objectives In this chapter, you will:Learn about repetition (looping) control structuresExplore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structuresExamine break and continue statementsDiscover how to form and use nested control structuresC++ Programming: Program Design Including Data Structures, Fifth Edition

3 Objectives (cont'd.) Learn how to avoid bugs by avoiding patchesLearn how to debug loopsC++ Programming: Program Design Including Data Structures, Fifth Edition

4 Why Is Repetition Needed?Repetition allows you to efficiently use variablesCan input, add, and average multiple numbers using a limited number of variablesFor example, to add five numbers:Declare a variable for each number, input the numbers and add the variables togetherCreate a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbersC++ Programming: Program Design Including Data Structures, Fifth Edition

5 while Looping (Repetition) StructureThe general form of the while statement is:while is a reserved wordStatement can be simple or compoundExpression acts as a decision maker and is usually a logical expressionStatement is called the body of the loopThe parentheses are part of the syntaxC++ Programming: Program Design Including Data Structures, Fifth Edition

6 while Looping (Repetition) Structure (cont'd.)Infinite loop: continues to execute endlesslyAvoided by including statements in loop body that assure exit condition is eventually falseC++ Programming: Program Design Including Data Structures, Fifth Edition

9 Case 1: Counter-Controlled while LoopsIf you know exactly how many pieces of data need to be read,while loop becomes a counter-controlled loopC++ Programming: Program Design Including Data Structures, Fifth Edition

10 Case 2: Sentinel-Controlled while LoopsSentinel variable is tested in the conditionLoop ends when sentinel is encounteredC++ Programming: Program Design Including Data Structures, Fifth Edition

12 Case 3: Flag-Controlled while LoopsA flag-controlled while loop uses a bool variable to control the loopThe flag-controlled while loop takes the form:C++ Programming: Program Design Including Data Structures, Fifth Edition

13 Number Guessing GameExample 5-6 implements a number guessing game using a flag-controlled while loopThe program uses the function rand of the header file cstdlib to generate a random numberrand() returns an int value between 0 and 32767To convert it to an integer greater than or equal to 0 and less than 100:rand() % 100C++ Programming: Program Design Including Data Structures, Fifth Edition

14 Case 4: EOF-Controlled while LoopsUse an EOF (End Of File)-controlled while loopThe logical value returned by cin can determine if the program has ended inputC++ Programming: Program Design Including Data Structures, Fifth Edition

15 eof Function The function eof can determine the end of file statuseof is a member of data type istreamLike other I/O functionsThe syntax for the function eof is:where istreamVar is an input stream variable, such as cinC++ Programming: Program Design Including Data Structures, Fifth Edition

16 More on Expressions in while StatementsThe expression in a while statement can be complexFor example:while ((noOfGuesses < 5) && (!isGuessed)){…}C++ Programming: Program Design Including Data Structures, Fifth Edition

17 Programming Example: Fibonacci NumberConsider the following sequence of numbers:1, 1, 2, 3, 5, 8, 13, 21, 34, ....Given the first two numbers of the sequence (say, a1 and a2)nth number an, n >= 3, of this sequence is given by: an = an-1 + an-2C++ Programming: Program Design Including Data Structures, Fifth Edition

21 Programming Example: Problem Analysis and Algorithm DesignGet the first two Fibonacci numbersGet the desired Fibonacci numberGet the position, n, of the Fibonacci number in the sequenceCalculate the next Fibonacci numberBy adding the previous two elements of the Fibonacci sequenceC++ Programming: Program Design Including Data Structures, Fifth Edition

24 Programming Example: Main AlgorithmPrompt the user for the first two numbers—that is, previous1 and previous2Read (input) the first two numbers into previous1 and previous2Output the first two Fibonacci numbersPrompt the user for the position of the desired Fibonacci numberRead the position of the desired Fibonacci number into nthFibonacciC++ Programming: Program Design Including Data Structures, Fifth Edition

25 Programming Example: Main Algorithm (cont'd.)if (nthFibonacci == 1) The desired Fibonacci number is the first Fibonacci number. Copy the value of previous1 into currentelse if (nthFibonacci == 2) The desired Fibonacci number is the second Fibonacci number. Copy the value of previous2 into current.C++ Programming: Program Design Including Data Structures, Fifth Edition

26 Programming Example: Main Algorithm (cont'd.)else calculate the desired Fibonacci number as follows:Start by determining the third Fibonacci numberInitialize counter to 3 to keep track of the calculated Fibonacci numbers.Calculate the next Fibonacci number, as follows: current = previous2 + previous1;C++ Programming: Program Design Including Data Structures, Fifth Edition

27 Programming Example: Main Algorithm (cont'd.)Assign the value of previous2 to previous1Assign the value of current to previous2Increment counterRepeat until Fibonacci number is calculated:while (counter <= nthFibonacci){current = previous2 + previous1;previous1 = previous2;previous2 = current;counter++;}C++ Programming: Program Design Including Data Structures, Fifth Edition

28 Programming Example: Main Algorithm (cont'd.)Output the nthFibonacci number, which is currentC++ Programming: Program Design Including Data Structures, Fifth Edition

29 for Looping (Repetition) StructureThe general form of the for statement is:The initial statement, loop condition, and update statement are called for loop control statementsinitial statement usually initializes a variable (called the for loop control, or for indexed, variable)In C++, for is a reserved wordC++ Programming: Program Design Including Data Structures, Fifth Edition

32 for Looping (Repetition) Structure (cont'd.)C++ allows you to use fractional values for loop control variables of the double typeResults may differThe following is a semantic error:The following is a legal for loop:for (;;)cout << "Hello" << endl;C++ Programming: Program Design Including Data Structures, Fifth Edition

34 do…while Looping (Repetition) StructureGeneral form of a do...while:The statement executes first, and then the expression is evaluatedTo avoid an infinite loop, body must contain a statement that makes the expression falseThe statement can be simple or compoundLoop always iterates at least onceC++ Programming: Program Design Including Data Structures, Fifth Edition

39 Choosing the Right Looping StructureAll three loops have their place in C++If you know or can determine in advance the number of repetitions needed, the for loop is the correct choiceIf you do not know and cannot determine in advance the number of repetitions needed, and it could be zero, use a while loopIf you do not know and cannot determine in advance the number of repetitions needed, and it is at least one, use a do...while loopC++ Programming: Program Design Including Data Structures, Fifth Edition

40 break and continue Statementsbreak and continue alter the flow of controlbreak statement is used for two purposes:To exit early from a loopCan eliminate the use of certain (flag) variablesTo skip the remainder of the switch structureAfter the break statement executes, the program continues with the first statement after the structureC++ Programming: Program Design Including Data Structures, Fifth Edition

41 break and continue Statements (cont'd.)continue is used in while, for, and do…while structuresWhen executed in a loopIt skips remaining statements and proceeds with the next iteration of the loopC++ Programming: Program Design Including Data Structures, Fifth Edition

43 Nested Control Structures (cont'd.)What is the result if we replace the first for statement with the following?for (i = 5; i >= 1; i--)Answer:***************C++ Programming: Program Design Including Data Structures, Fifth Edition

44 Avoiding Bugs by Avoiding PatchesSoftware patchPiece of code written on top of an existing piece of codeIntended to fix a bug in the original codeSome programmers address the symptom of the problem by adding a software patchShould instead resolve underlying issueC++ Programming: Program Design Including Data Structures, Fifth Edition

45 Debugging LoopsLoops are harder to debug than sequence and selection structuresUse loop invariantSet of statements that remains true each time the loop body is executedMost common error associated with loops is off-by-oneC++ Programming: Program Design Including Data Structures, Fifth Edition

46 Summary C++ has three looping (repetition) structures:while, for, and do…whilewhile, for, and do are reserved wordswhile and for loops are called pretest loopsdo...while loop is called a posttest loopwhile and for may not execute at all, but do...while always executes at least onceC++ Programming: Program Design Including Data Structures, Fifth Edition

47 Summary (cont'd.)while: expression is the decision maker, and the statement is the body of the loopA while loop can be:Counter-controlledSentinel-controlledEOF-controlledIn the Windows console environment, the end-of-file marker is entered using Ctrl+zC++ Programming: Program Design Including Data Structures, Fifth Edition

48 Summary (cont'd.)for loop: simplifies the writing of a counter-controlled while loopPutting a semicolon at the end of the for loop is a semantic errorExecuting a break statement in the body of a loop immediately terminates the loopExecuting a continue statement in the body of a loop skips to the next iterationC++ Programming: Program Design Including Data Structures, Fifth Edition