repetition and loop statementscmliu/pl/ntut-c06su/notes/ch5...2 mobile computing & software...

73
1 Mobile Computing & Software Engineering Lab Mobile Computing & Software Engineering Lab Repetition and Loop Statements Chuan-Ming Liu Computer Science & Information Engineering National Taipei University of Technology Taiwan

Upload: others

Post on 11-Oct-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

1Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Repetition and Loop Statements

Chuan-Ming LiuComputer Science & Information Engineering

National Taipei University of TechnologyTaiwan

Page 2: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 3: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 4: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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?

Page 5: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

5Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Loop Choice Process

Page 6: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

6Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Loop Kinds

Page 7: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 8: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 9: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

9Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

The while Statement – Example

Page 10: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 11: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

11Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Flowchart for a while Loop

Page 12: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 13: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

13Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Syntax of while Statement

Page 14: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 15: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 16: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

16Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Computing Company Payroll

Page 17: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

17Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Multiplying a List of Numbers

Page 18: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

18Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Compound Assignment Operators

• variable = variable op (expression);• variable op= expression;

Page 19: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 20: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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);

Page 21: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

21Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Loop Using for Statement

Page 22: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

22Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Syntax – for Statement

Page 23: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 24: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

24Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Prefix and Postfix Increments

Page 25: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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)

Page 26: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

26Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Function for Factorial

Page 27: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

27Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Celsius-to-Fahrenheit Conversion Table

Page 28: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 29: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 30: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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 */

}

Page 31: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

31Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Program – Monitoring Gasoline Storage Tank (1)

Page 32: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

32Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Program – Monitoring Gasoline Storage Tank (2)

Page 33: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

33Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Execution of the Program

Page 34: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 35: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 36: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 37: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

37Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Sentinel-Controlled while Loop

Page 38: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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);

}

Page 39: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 40: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 41: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

41Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Sum of Scores – Batch Version

Page 42: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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);

}

Page 43: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 44: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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;}

Page 45: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

45Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Page 46: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

46Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

5.12Program to Process

Bald Eagle

Sightings for a Year

Page 47: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 48: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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');

Page 49: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

49Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

do-while Statement Syntax

Page 50: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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)

Page 51: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

51Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Page 52: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 53: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 54: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 55: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

55Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Analysis

Page 56: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 57: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 58: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

58Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Structure Chart for Computing Solar Collecting Area Size

Page 59: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

59Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Program to Approximate Solar Collecting Area Size (1)

Page 60: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

60Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Program to Approximate Solar Collecting Area Size (2)

Page 61: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

61Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Program to Approximate Solar Collecting Area Size (3)

Page 62: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

62Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Program to Approximate Solar Collecting Area Size (4)

Page 63: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 64: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 65: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 66: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 67: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 68: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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;

Page 69: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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

Page 70: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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.

Page 71: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

71Mobile Computing & Software Engineering LabMobile Computing & Software Engineering Lab

Common Programming Errors (2)

Page 72: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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 */

Page 73: Repetition and Loop Statementscmliu/PL/NTUT-C06Su/notes/Ch5...2 Mobile Computing & Software Engineering Lab Outline • Repetition in Programs • Counting Loops and the whileStatement

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);