Download presentation
Presentation is loading. Please wait.
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. Hanly, Koffman, C Problem Solving and Program Design in C, Fifth Edition, Pearson International Edition. Reference... Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012) Prepared by: Pn. Nik Maria Nik Mahamood
2
Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012)
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. Hanly, Koffman, C Program Design for Engineers, Second Edition, Addison Wesley, 2004. Reference... Prepared By: Pn. Nik Maria Nik Mahamood (Coordinator DDC 1012) Prepared by: Pn. Nik Maria Nik Mahamood
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 source: This figure is taken from Pearson Addison-Wesley, 2004.
6
Table 6.1 Comparison of Loop Kinds
When used C Implementation structures Counting loop Can determine before loop execution exactly how many loop repetitions will be needed to solve the problem while for Sentinel-controlled loop Input of a list of data of any length ended by a special value. While For Endfile-controlled loop Input of a single list of data of any length from a data file Input validation loop Repeated interactive input of data of any length from a data file. Do-while General validation loop Repeated processing of data until a desired condition is met Table 6.1 Comparison of Loop Kinds
7
COUNTING LOOPS AND THE WHILE STATEMENT
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;
8
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 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
COMPUTING A SUM OR A PRODUCT IN A LOOP
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
12
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) Source: This figure is taken from Pearson Addison-Wesley, 2004.
14
THE FOR STATEMENT 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);
15
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 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 Source: This figure is taken from Pearson Addison-Wesley, 2004.
20
See example page 232 - 235: Program to monitor gasoline storage tank.
CONDITIONAL LOOPS 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 : Program to monitor gasoline storage tank.
21
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) Source: This figure is taken from Pearson Addison-Wesley, 2004.
23
Figure 6.8 Program to Monitor Gasoline Storage Tank (cont’d) Source: This figure is taken from Pearson Addison-Wesley, 2004.
24
LOOP DESIGN Problem solving questions for loop design as following table (based on program to monitor gasoline storage tanks . Questions Answer Implication 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
Questions Answer Implication 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 Get amount removed Convert the amount to barrels Subtract the amount removed from the current supply Checks to see whether the supply has fallen below the minimum. Program variable needed min_supply
26
Questions Answer Implication for the algorithm Do I know in advance how many times steps will be repeated? No Loop 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 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
NESTED LOOPS 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 : Program to process bald eagle sightings for a year.
31
Figure Program to Process Bald Eagle Sightings for a Year Source: This figure is taken from Pearson Addison-Wesley, 2004.
32
Figure Program to Process Bald Eagle Sightings for a Year (cont’d) Source: This figure is taken from Pearson Addison-Wesley, 2004.
33
Figure Nested Counting Loop Program Source: This figure is taken from Pearson Addison-Wesley, 2004.
34
THE DO-WHILE STATEMENT AND FLAG-CONTROLLED LOOPS
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; printf(“The value of x is %d”, x); x = x + 1; } while (x < 4);
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 : Program validating input using do-while statement
36
Figure Validating Input Using do-while Statement Source: This figure is taken from Pearson Addison-Wesley, 2004.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.