Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
1Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Repetition and Loop Statements
Chuan-Ming LiuComputer Science & Information Engineering
National Taipei University of TechnologyTaiwan
2Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
3Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Repetition in Programs
• Three types of program control structure:– sequence, selection, repetition
• loop– a control structure that repeats a group of steps in a
program• C loop control statements
– while, for, and do-while• loop body
– the statements that are repeated in the loop
4Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Determining the Need for Loops
• After you solve the sample case, ask yourself some of the following questions to determine whether loops will be required in the general algorithm:– Were there any steps I repeated as I solved the
problem? If so, which ones?– If the answer to question 1 is yes, did I know in
advance how many times to repeat the steps?– If the answer to question 2 is no, how did I know
how long to keep repeating the steps?
5Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Loop Choice Process
6Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Loop Kinds
7Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
8Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Counting Loops
• counter-controlled loop (counting loop) – a loop whose required number of iterations can be
determined before loop execution begins
Set loop control variable to an initial value of 0.while loop control variable < final value. . .
Increase loop control variable by 1.
9Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
The while Statement – Example
10Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
The while Statement
• After executing the last step in the loop body, control returns to the line beginning with while and the condition is reevaluated.
• loop repetition condition– the condition that controls loop repetition
11Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Flowchart for a while Loop
12Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Loop Control Variable • The loop control variable count_emp must be
(1) initialized, (2) tested, and (3) updated for the loop to execute properly. – Initialization. count_emp is set to an initial value of 0
(initialized to 0) before the while statement is reached.– Testing. count_emp is tested before the start of each loop
repetition (called an iteration or a pass).– Updating. count_emp is updated (its value increased by 1)
during each iteration.
• infinite loop– a loop that executes forever
13Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Syntax of while Statement
14Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
15Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
A Sum or Product Using a Loop
• accumulator – a variable used to store a value being computed in
increments during the execution of a loop
16Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Computing Company Payroll
17Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Multiplying a List of Numbers
18Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Compound Assignment Operators
• variable = variable op (expression);• variable op= expression;
19Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
20Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
The for Statement
• Review of the three loop control components– initialization of the loop control variable,– test of the loop repetition condition, and– change (update) of the loop control variable.
• Example– /* Display nonnegative numbers < max */
for (i = 0; i < max; i += 1)printf("%d\n", i);
21Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Loop Using for Statement
22Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Syntax – for Statement
23Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Increment and Decrement Operators
• The increment operator ++ takes a single variable as its operand.
• for (counter = 0; counter < limit; ++counter)• prefix increment
– ++ is placed immediately in front of its operand– value of the expression is the variable’s value after
incrementing• postfix increment
– ++ comes immediately after the operand– expression’s value is the value of the variable before it is
incremented
24Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Prefix and Postfix Increments
25Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Using Increment and Decrement Operators
• avoid using the increment and decrement operators in complex expressions in which the variables to which they are applied appear more than once.
• Example:x = 5;i = 2;y = i * x + ++i;– Implementation dependent– 13 (2 * 5 + 3) or (3 * 5 + 3)
26Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Function for Factorial
27Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Celsius-to-Fahrenheit Conversion Table
28Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
29Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Conditional Loops (1)
• Using a condition to control the loop─ The exact number of loop repetitions is
undetermined• Example
1. Print an initial prompting message.2. Get the number of observed values.3. while the number of values is negative
1) Print a warning and another prompting message.2) Get the number of observed values.
30Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Conditional Loops (2)
• Exampleprintf("Enter number of observed values> ");scanf("%d", &num_obs); /* initialization */while (num_obs < 0) {
printf("Negative number invalid; try again> ");scanf("%d", &num_obs); /* update */
}
31Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Program – Monitoring Gasoline Storage Tank (1)
32Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Program – Monitoring Gasoline Storage Tank (2)
33Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Execution of the Program
34Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
35Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Sentinel-Controlled Loops
• One way to signal the program to stop reading and processing new data.
• sentinel value– an end marker that follows the last item in a list of data– The loop exit when the sentinel value is read
• Structure1. Get a line of data.2. while the sentinel value has not been encountered
3. Process the data line.4. Get another line of data.
36Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Example – Sum of Scores• Sentinel Loop
– Initialize sum to zero.– Get first score.– while score is not the sentinel
• Add score to sum.• Get next score.
• Incorrect Sentinel Loop– Initialize sum to zero.– while score is not the sentinel
• Get score• Add score to sum
37Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Sentinel-Controlled while Loop
38Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
for Statement for Sentinel Loop• /* 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);
}
39Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Endfile-Controlled Loops (1)
• The return value of scanf is the number of data items it actually obtained.
• input_status = scanf("%d%d%lf", &part_id, &num_avail, &cost);– returns a result of 3 on success
• If scanf runs into difficulty with invalid or insufficient data, the function returns as its value the number of data items scanned before encountering the error or running out of data.
40Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Endfile-Controlled Loops (2)
• To detect the end-of-file condition, scanfreturns as its result the value of the standard constant EOF
• Endfile-controlled loop:1. Get the first data value and save input status2. While input status does not indicate that end of
file has been reached3. Process data value4. Get next data value and save input status
41Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Sum of Scores – Batch Version
42Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Infinite Loops on Faulty Data• Assume the user responds to the prompt
Enter next score (-99 to quit)>in Fig. 5.10 with the faulty data “7o”– Infinite loops
• Changing the loop repetition condition to– input_status == 1
• To warn of bad inputif (input_status == EOF) {
printf("Sum of exam scores is %d\n", sum);} else {
fscanf(inp, "%c", &bad_char);printf("*** Error in input: %c ***\n", bad_char);
}
43Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
44Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Nested Loops• Nested Loops consists of an outer loop with one
or more inner loops• Do not use the same variable as the loop control
variable of both an outer and an inner for loop in the same nest.
• Invalid Examplefor (i=0; i<5; i++){
sum =0;for(i=0; i<4; i++)
sum = sum + i;}
45Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
46Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
5.12Program to Process
Bald Eagle
Sightings for a Year
47Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
48Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
The do-while Statement
• A loop must execute at least one time.• Example
– Get a data value.– If data value isn’t in the acceptable range, go back to step 1.
• Implementationdo {
printf("Enter a letter from A through E> ");scanf("%c", &letter_choice);
} while (letter_choice < 'A' || letter_choice > 'E');
49Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
do-while Statement Syntax
50Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Flag-Controlled Loops
• Sometimes a loop repetition condition becomes so complex that placing the full expression in its usual spot is awkward
• In many case, the condition may be simplified by using a flag
• 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) and 0
(false)
51Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
52Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Program Execution
• Execution of the get_int() function call– next_int = get_int(10, 20)
• Execution results– Enter an integer in the range from 10 to 20 inclusive> @20– Invalid character >>@>>. Skipping rest of line.– Enter an integer in the range from 10 to 20 inclusive> 2o– Number 2 is not in range.– Enter an integer in the range from 10 to 20 inclusive> 20
• The do-while is often the structure to choose when checking for valid input
53Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
54Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Case Study – Collecting Area for Solar-Heated House
• Problem: estimate the appropriate size for the collecting area of a solar-heated house– Factors considered
• Average number of heating degree days for the coldest month of a year
• Heating requirement per square foot of floor space• Floor space• Efficiency of the collection method
– Accessing two files• hdd.txt: average heating degree days in the area for each
month• solar.txt: average solar insolation for each month
55Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Analysis
56Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Data Requirements• Inputs
– Average heating degree days file– Average solar insolation file– heat_deg_days– coldest_mon– solar_insol– heating_req– efficiency– floor_space
• Variables– energy_resrc
• Output– heat_loss– collect_area
57Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Design – Initial Algorithm
1. Determine the coldest month and the average heating degree days for that month
2. Find the average daily solar insolation per ft2
for the coldest month3. Get from the user the other inputs
1. heating_req2. efficiency3. floor_space
4. Estimate the collecting area5. Display results
58Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Structure Chart for Computing Solar Collecting Area Size
59Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Program to Approximate Solar Collecting Area Size (1)
60Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Program to Approximate Solar Collecting Area Size (2)
61Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Program to Approximate Solar Collecting Area Size (3)
62Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Program to Approximate Solar Collecting Area Size (4)
63Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
64Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
How to Debug and Test Programs
• There are three general categories of errors:– Syntax error– Run-time error– Logic error
• The first step in locating a hidden error is to examine the program output to determine which part of the program is generating incorrect results.
65Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Using Debugger Programs• Single-step execution
– execute your program one statement at a time using debugger
• Trace your program’s execution and observe the effect of each C statement on variables you select
• A breakpoint is like a fence between two segments of a program.
• When the program stops at a breakpoint, you can examine the values of selected variables to determine whether the program segment has executed correctly.
66Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Debugging without a Debugger
• Insert extra diagnostic calls to printf that display intermediate results at critical points in your program.
• By comparing these results at the end of a run, you may be able to determine which segment of your program contains bugs.
67Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Debugging without a Debugger (2)
• Examplewhile (score != SENTINEL) {
sum += score;if (DEBUG)printf("***** score is %d, sum is %d\n", score, sum);printf("Enter next score (%d to quit)> ", SENTINEL);scanf("%d", &score); /* Get next score. */
}• turn your diagnostics on by inserting
– #define DEBUG 1
68Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Off-by-One Loop Errors• Common logic error of loops is a loop that
executes one more time or one less time than required
• Make sure that the initial and final values of the loop control variable are correct and that the loop repetition condition is right.– loop boundaries: initial and final values of the loop
control variable• Example
for (count = 0; count <= n; ++count)sum += count;
69Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Outline • 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 Loops• The do-while Statement and Flag• Illustration• How to Debug and Test Programs• Common Programming Errors
70Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Common Programming Error (1)
• Remember to end the initialization expression and the loop repetition condition of for loop with semicolons.
• Remember to use braces around a loop body consisting of multiple statements.while (x > xbig)
x -= 2;++xbig;
– The compiler will associate the first closing brace encountered with the innermost structure.
71Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Common Programming Errors (2)
72Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Common Programming Errors (3)
• Be sure to verify that a loop’s repetition condition will eventually become false (0); otherwise, an infinite loop may result.
• An equality test mistyped as an assignment operationdo {
. . .printf("One more time? (1 to continue/0 to quit)> ");scanf("%d", &again);
} while (again = 1); /* should be: again == 1 */
73Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab
Common Programming Errors (4)
• Use a do-while only when there is no possibility of zero loop iterations.
• Do not use increment, decrement, or compound assignment operations as subexpressions in complex expressions– Difficult to read or even produce varying results in
different implementation of C• a *= b + c; is equivalent to a = a * (b + c);