View
224
Download
3
Embed Size (px)
Citation preview
Chapter 5Repetition and Loop Statements
Dr. J.-Y. Pan Dept. Comm. Eng.Nat. Chung Cheng Univ.http://[email protected]
3-2中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.1 Repetition in programs
Loop A control structure that repeats a group of steps in a
programLoop body
The statements that are repeated in the loopThree questions to determine whether loops will
be required in the general algorithm: (Figure5.1) 1. Were there any steps I repeated as I solved the
problem? If so, which ones? 2. If the answer to question 1 is yes, did I know in
advance how many times to repeat the steps? 3. If the answer to question 2 is no, how did I know how
long to keep repeating the steps?
3-3中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.1 Flow Diagram of Loop Choice Process
3-4中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
3-5中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
The while statement:
while (bool-expr) statement ;while (bool-expr) { stmts;}(1)First evaluates bool-expr;(2)If bool-expr’s value is TRUE, it executes
stmts,and back to step 1.(3)If bool-expr’s value is FALSE, it terminates.
3-6中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.2 Counting Loops and the while Statement
Counter-controlled loop (counting loop) A loop whose required number of iterations can
be determined before loop execution begins
Figure 5.2 shows a program fragment that computes and displays the gross pay for seven employees.
3-7中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.2 Program Fragment with a Loop
3-8中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.3 Flowchart for a while Loop
3-9中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.2 (cont) Counting Loops and the while Statement
Loop repetition condition The condition that controls loop repetition
Loop control variable The variable whose value controls loop
repetitionThe loop control variable must be
Initialization Testing Updating
3-10中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.3 Computing a Sum or a Product in a Loop
accumulator a variable used to store a value being computed
in increments during the execution of a loop
Fig.5.4 Program to Compute Company Payroll
3-11中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.4 Program to Compute Company Payroll
3-12中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.4 Program to Compute Company Payroll (cont’d)
跑個GDB?
3-13中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
3-14中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.3 (cont) Compound Assignment Operators
Assignment statements of the form variable = variable op expression variable op = expression
如 += -= /= %= /=
3-15中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.4 The for Statement
Three loop control components Initialization of the loop variable Test of the loop repetition condition Change (update) of the loop control variable
Using a for statement in a counting loop.
(Figure 5.5)
3-16中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.5 Using a for Statement in a Counting Loop
3-17中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
The for statementThe for (loop) statement
for (init expr; loop condition; step expr) {
stmts;
}
Initial expression
Loop condition
Step expression
statements
Yes
No
3-18中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
An Example
#include <stdio.h>
int main(void) {
int i, N;
printf(“How many = ?”);
scanf (“%d”,&N);
/* Display N asterisks */
for (i = 0; i < N; i += 1)
printf(“*”);
} // 跑個 GDB 吧…
3-19中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Increment and decrement operators
The counting loops that you have seen have all included assignment expressions of form
counter = counter +1
or
counter +=1
for (counter =0; counter<limit; ++counter)
…….. Side effecta change in the value of a variable as a result of carrying out an operation
3-20中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.6 Comparison of Prefix and Postfix Increments
3-21中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Conditional loops
In many programming situations, you will not be able to determine the exact number of loop repetitions before loop execution begins.
3-22中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.5 (cont) Example 5.5(Figure 5.9)
The program is designed to assist in monitoring the gasoline supply in a storage tank at the Super Oil Company refinery.
The program is to alert the supervisor when the supply of gasoline in the tank falls below 10% of the tank’s 80,000 barrel storage capacity.
The barrel used in the petroleum industry equals 42 U.S. gallons
3-23中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.9 Program to Monitor Gasoline Storage Tank
3-24中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)
3-25中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)
3-26中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.5 (cont) Example 5.5(Figure 5.9)
There are three critical steps in Fig.5.9 that involve the loop control variable current: current is initialized to the starting supply in the
for statement initialization expression current is tested before each execution of the
loop body current is updated (by subtraction of the amount
removed) during each iteration
3-27中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Loop design… An example on Ex 5.5 (Fig 5.9)
Fig5.1
3-28中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Loop design Sentinel-Controlled Loops
A loop that process data until the sentinel value is entered has the form get a line of data (initialization) while the sentinel value has not been
encountered (a loop repetition condition) process the data line. get another line of data (update)
Sentinel valueAn end marker that follows the last item in a list of data
3-29中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.6 (cont) Example 5.6(Figure 5.10)
A program that calculates the sum of a collection of exam scores is a candidate for using a sentinel value.
Sentinel loop1. Initialize sum to zero2. Get first score3. while score is not the sentinel
4. Add score to sum5. Get next score
有兩次 Get
會很怪嗎 ?
3-30中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.10 Sentinel-Controlled while Loop
3-31中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.6 (cont) Using a for Statement to Implement a Sentinel Loop
The for statement form of the while loop in Fig.5.10
/* 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(%d to quit)>”, SENTINEL);
}
3-32中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Endfile-controlled loops
Here is the pseudo code for an endfile-controlled loop: get the first data value and save input status while input status does not indicate that end of
file has been reached process data valueget next data value and save input status
3-33中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Result value of scanf and fscanf
input_status = scanf(“%d%d%lf”,&a, &b, &c);number of data items it actually obtainednumber of data before encountering errorEOF: when detecting the endfile before get
(End of File)
3-34中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.11 Batch Version of Sum of Exam Scores Program
3-35中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Nested loop
If a for loop is nested inside another for loop, the inner for loop is executed once for each iteration of the outer for loop
Each for loop must have its own (distinct) index variables so that the variables do not interfere with each other
You CANNOT use the same variable as the loop control variable of both an outerand an inner for loop in the same nest.
3-36中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
An Example
#include <stdio.h> main( ) { int I,j; for (i=1;i<=5 ;i++){ for(j=1;j<=5;j++){ printf (“(%d, %d)”, I, j); } printf( “\n”); } }
3-37中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
An Example
(1,1)(1,2)(1,3)(1,4)(1,5)
(2,1)(2,2)(2,3)(2,4)(2,5)
(3,1)(3,2)(3,3)(3,4)(3,5)
(4,1)(4,2)(4,3)(4,4)(4,5)
(5,1)(5,2)(5,3)(5,4)(5,5)
3-38中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.8 The do-while statement and flag-controlled loops
The do-while (loop) statement do statement; while ( bool-expr );
do { stmts; }while ( bool-expr );
statement
Bool-expr ?
NoYes
3-39中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
3-40中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.8 (cont) Flag-Controlled Loops for Input Validation
flag A type int variable used to represent whether or
not a certain event has occurred A flag has one of two values
1 (true) ( 或 非 0 值 )0 (false)
3-41中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.8 (cont) Example 5.10(Figure 5.14)
Function get_int returns an integer value that is in the range specified by its two arguments.
The outer do-while structure implements the stated purpose of the function.
The type int variable error acts as a program flag.
error is initialized to 0 and is changed to 1 when an error is detected.
3-42中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.14 Validating Input Using do-while Statement
3-43中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.9 Problem Solving IllustratedCase Study :
Collecting Area For Solar-Heated House
Problem An architect needs a program that can estimate
the appropriate size for the collecting area of a solar-heated house.
Considerate factorsAverage number of heating degree days for the
coldest month of a yearThe heating requirements per square foot of floor
spaceFloor spaceEfficiency of the collection method
3-44中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.9 (cont) Case Study :Collecting Area For Solar-Heated House
Problem The program will have to access two data files
File hdd.txtContains numbers representing the average
heating degree days in the construction location for each of 12 months
File solar.txtContains the average solar insolation for each
month
3-45中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Solar-heated house Heating degree * days
Heating requirementBTU / degree-day / ft^2
Floor space
Solar insolation 日射能量BTU / ft^2 / day
Efficiency
Area = heat loss / energy resource
3-46中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Problem solving illustrated BTU, 英制熱量單位
使 1磅 (b) 水升高華氏 1度所需能量
日射能量
3-47中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.9 (cont) Case Study :Collecting Area For Solar-Heated House
Design Refinement
1.1 Scan first value from heating degree days file into heat_deg_days, and initialize coldest_mon to 1.
1.2 Initialize ct to 21.3 Scan a value from the file into next_hdd, saving
status1.4 as long as no faulty data/end of file, repeat
1.5 if next_hdd is greater than heat_deg_days» 1.6 copy next_hdd into heat_deg_days» 1.7 copy ct into coldest_days
1.8 Increment ct1.9 Scan a value from the file into next_hdd, saving status
3-48中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.9 (cont) Case Study :Collecting Area For Solar-Heated House
Design Refinement
4.1 Calculate heat_loss as the product of heating_req, floor_space, and heat_deg_days
4.2 Calculate energy_resrc as the product of efficiency, solar_insol, and the number of days in the coldest month
4.3 Calculate collect_area as heat_loss divided by energy_resrc. Round result to nearest whole square foot
3-49中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.9 (cont) Case Study :Collecting Area For Solar-Heated House
Design Functions
nth_itemdays_in_month
Input file hdd.txt995 900 750 400 180 20 10 10 60 290 610 1051
Input file solar.txt500 750 1100 1490 1900 2100 2050 1550 1200 900
500 500
3-50中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.15 Structure Chart for Computing Solar Collecting Area Size
3-51中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.16 Program to Approximate Solar Collecting Area Size
好長哦…直接看程式
3-52中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)
3-53中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)
3-54中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)
3-55中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.10 How to Debug and Test Programs
Using debugger programs Execute programs one statement at a time
(single-step execution) Set breakpoints at selected statements when a
program is very long
Debugging without a debugger Insert extra diagnostic calls to printf that display
intermediate results at critical points
3-56中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
How to debug and test programs
Debugging without a debugger
Off-by-one loop errors
3-57中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.10 (cont) Off-by-One Loop Errors
A common logic error A loop executes one more time or one less time
Loop boundaries Initial and final values of the loop control
variable
3-58中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
補充資料
break 強制離開這層迴圈
continue 強制進行下次迴圈
3-59中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.11 Common Programming Errors
Do not confuse if and while statements if statement implement a decision step while/for statement implement a loop
Remember to end the initialization expression and the loop repetition condition with semicolons.
Remember to use braces around a loop body consisting of multiple statements (compound statements) 不要括錯了
Remember to provide a prompt for the users, when using a sentinel-controlled loop.
Make sure the sentinel value cannot be confused with a normal data item.
== and =
3-60中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.11 (cont) Common Programming Errors
Use do-while only when there is no possibility of zero loop iterations.
Replace the segment with a while or for statement when adding an if statement. if (condition1)
do {
…
} while(condition1);
3-61中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab
5.11 (cont) Common Programming Errors
Do not use increment, decrement, or compound assignment operators as subexpressions in complex expressions. (difficult to read)
Be sure that the operand of an increment or decrement operator is a variable.
Do not use a variable twice in an expression in which it is incremented/decremented