Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes -----------------------------------------  Define the concept of repetition structure.  Specify.

Similar presentations


Presentation on theme: "CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes -----------------------------------------  Define the concept of repetition structure.  Specify."— Presentation transcript:

1 CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes -----------------------------------------  Define the concept of repetition structure.  Specify the repetition of a group of program statements using the while, for and do-while.  Apply counter-controlled repetition sentinel- controlled and flag – controlled in program.  Design loops using algorithm for solving problems. Reference... Hanly, Koffman, C Problem Solving and Program Design in C, Fifth Edition, Pearson International Edition. Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)

2 Continue.. Learning outcomes -----------------------------------------  Convert problem design into C code using repetition controls.  Trace an algorithm or program to verify that it does what user expected.  Write a program using the combination of repetition and selection statements that control the flow of program execution  Debug and test a program. Reference... Hanly, Koffman, C Program Design for Engineers, Second Edition, Addison Wesley, 2004. Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)

3 This chapter introduces to: Repetition in Programs Counting Loops and the while Statement Computing a Sum or a Product in a Loop The for Statement Conditional Loops Loop Design Nested Control Structures The do-while Statement and Flag controlled Loops

4 REPETITION IN PROGRAMS Loop body – the statements that are repeated in the loop Figure 6.1 Flow Diagram of Loop Choice Process Figure 6.1 Flow Diagram of Loop Choice Process source: This figure is taken from Pearson Addison-Wesley, 2004.

5

6 KindWhen usedC Implementation structures Counting loopCan determine before loop execution exactly how many loop repetitions will be needed to solve the problem while for Sentinel-controlled loopInput of a list of data of any length ended by a special value. While For Endfile-controlled loopInput of a single list of data of any length from a data file While For Input validation loopRepeated interactive input of data of any length from a data file. Do-while General validation loopRepeated processing of data until a desired condition is met While For Table 6.1 Comparison of Loop Kinds

7 Counter-controlled loop – a loop whose required number of iterations can be determined before loop execution begins. Syntax: initialization expression; while (loop repetition condition){ statement; update expression; } Example: int x = 0; while (x < 4) { printf(“The value of x is %d”, x); x = x + 1; } COUNTING LOOPS AND THE WHILE STATEMENT

8 Figure 6.2 Program Fragment with a Loop Figure 6.2 Program Fragment with a Loop source: This figure is taken from Pearson Addison-Wesley, 2004.

9 Figure 6.3 Flowchart for a while Loop Figure 6.3 Flowchart for a while Loop source: This figure is taken from Pearson Addison-Wesley, 2004.

10 The loop control variable must be –Initialized –Tested –Updated for the loop to execute properly Each step is summarized as: –Initialization : set to an initial value before the while statement is reached. –Testing: tested before the start of each loop repetition –Updating: updated during each iteration.

11 Loop often accumulate a sum or a product by repeating an addition or multiplication operation as demonstrated in example 1 and 2. Example 1 (program to compute company payroll): –See page 216 – 219 Example 2 (program to calculate product) –See page 219 - 220 COMPUTING A SUM OR A PRODUCT IN A LOOP

12 Figure 6.4 Program to Compute Company Payroll Figure 6.4 Program to Compute Company Payroll Source: This figure is taken from Pearson Addison-Wesley, 2004.

13 Figure 6.4 Program to Compute Company Payroll (cont’d) Figure 6.4 Program to Compute Company Payroll (cont’d) Source: This figure is taken from Pearson Addison-Wesley, 2004.

14 C provides the for statement as another form for implementing loops. Syntax: for(initialization expression; loop repetition condition; update expression){ statement; } Example: int x; for (x = 0; x < 4; x++) { printf(“The value of x is %d”, x); } THE FOR STATEMENT

15 Figure 6.5 Using a for Statement in a Counting loop Figure 6.5 Using a for Statement in a Counting loop Source: This figure is taken from Pearson Addison-Wesley, 2004.

16 Increment and Decrement Operators The counting loop that you have seen have all included assignment expression of the form Counter = Counter + 1; Counter = Counter - 1 or Counter += 1; Counter -= 1; The increment operator ++ means that the value of its operand in incremented by one. The decrement operator -- means that the value of its operand in decremented by one.

17 Figure 6.6 Comparison of Prefix and Postfix Increments Figure 6.6 Comparison of Prefix and Postfix Increments Source: This figure is taken from Pearson Addison-Wesley, 2004.

18 Increment and Decrement Other than 1 Example Counter = Counter + 5; Counter = Counter - 2 or Counter += 5; Counter -= 2; See example 5.4 at page 227: program to convert temperature from Celsius to Fahrenheit.

19 Figure 6.7 Display a Celsius to Fahrenheit Conversion Figure 6.7 Display a Celsius to Fahrenheit Conversion Source: This figure is taken from Pearson Addison-Wesley, 2004.

20 In many programming situations, we will not be able to determine the exact number of loop repetitions before loop execution begin. In this case, we still able to write a condition to control the loop by prompting the user to input a data value. See example page 232 - 235: Program to monitor gasoline storage tank. CONDITIONAL LOOPS

21 Figure 6.8 Program to Monitor Gasoline Storage Tank Figure 6.8 Program to Monitor Gasoline Storage Tank Source: This figure is taken from Pearson Addison-Wesley, 2004.

22 Figure 6.8 Program to Monitor Gasoline Storage Tank (cont’d) Figure 6.8 Program to Monitor Gasoline Storage Tank (cont’d) Source: This figure is taken from Pearson Addison-Wesley, 2004.

23

24 Problem solving questions for loop design as following table (based on program to monitor gasoline storage tanks. LOOP DESIGN QuestionsAnswerImplication for the algorithm What are the inputs? Initial supply of gasoline (barrels) Amount removed (Gallons) Input variable needed start_supply remov_gal Value of start_supply must be input once, but amounts removed are entered many times.

25 QuestionsAnswerImplication for the algorithm What are the output? Amount removed in gallons and barrels, and the current supply of gasoline. Values of current and remov_gals are echoed in the output. Output variable needed: remov_brls Is there any repetition? Yes. One repeatedly 1. Get amount removed 2. Convert the amount to barrels 3. Subtract the amount removed from the current supply 4. Checks to see whether the supply has fallen below the minimum. Program variable needed min_supply

26 QuestionsAnswerImplication for the algorithm Do I know in advance how many times steps will be repeated? NoLoop will not be controlled by a counter How do I know how long to keep repeating the steps? As long as the current supply is not below the minimum. The loop condition is Current >= min min_supply

27 Sentinel-Controlled Loops The sentinel value – to signal the program to stop reading and processing new data. Sentinel value is an end marker that follows the last item in a list of data. See example 5.6 at page 241: A program that calculates the sum of collection of exam is a candidate for using a sentinel value.

28 Figure 6.9 Sentinel-Controlled while Loop Figure 6.9 Sentinel-Controlled while Loop Source: This figure is taken from Pearson Addison-Wesley, 2004.

29 Using a for statement to implement a Sentinel Loops The for statement form pf the while loop in figure 6.9 as follows: /* Accumulate sum of all scores printf(“Enter first score (or %d to quit)>”, SENTINEL); for(scanf(“%d”, &score); score != SENTINEL; scanf(“%d”, &score)) { sum += score; printf(“Enter next score (or %d to quit)>”, SENTINEL); }

30 Loops may be nested just like other control structures. Nested loops consist of an outer loop with one or more inner loops. See example 5.7 at page 246 - 247: Program to process bald eagle sightings for a year. NESTED LOOPS

31 Figure 6.10 Program to Process Bald Eagle Sightings for a Year Figure 6.10 Program to Process Bald Eagle Sightings for a Year Source: This figure is taken from Pearson Addison-Wesley, 2004.

32 Figure 6.10 Program to Process Bald Eagle Sightings for a Year (cont’d) Figure 6.10 Program to Process Bald Eagle Sightings for a Year (cont’d) Source: This figure is taken from Pearson Addison-Wesley, 2004.

33 Figure 6.11 Nested Counting Loop Program Figure 6.11 Nested Counting Loop Program Source: This figure is taken from Pearson Addison-Wesley, 2004.

34 Do-while statement evaluate a loop repetition condition at the end of the loop body. Syntax: initialization expression; do { statement; update expression; } while (loop repetition condition); Example: int x = 0; do { printf(“The value of x is %d”, x); x = x + 1; } while (x < 4); THE DO-WHILE STATEMENT AND FLAG- CONTROLLED LOOPS

35 Flag-Controlled Loops for input validation The loop repetition condition may be simplified by using a flag A flag is a type int variable to represent whether or not a certain events has occurred. A flag has one of two values: 1 (true) and 0 (false). See example 5.10 at page 251-252: Program validating input using do-while statement

36 Figure 6.12 Validating Input Using do-while Statement Figure 6.12 Validating Input Using do-while Statement Source: This figure is taken from Pearson Addison-Wesley, 2004.


Download ppt "CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes -----------------------------------------  Define the concept of repetition structure.  Specify."

Similar presentations


Ads by Google