unit 4 repetition and loops. key concepts flowcharting a loop types of loops counter-controlled...

40
Unit 4 Repetition and Loops

Upload: miranda-mcdonald

Post on 30-Dec-2015

244 views

Category:

Documents


2 download

TRANSCRIPT

Unit 4

Repetition and Loops

Key Concepts

• Flowcharting a loop• Types of loops• Counter-controlled

loops• while statement• Compound assignment

operator• for statement

• Sentinel-controlled loops

• Endfile-controlled loops• Nested loops• do-while statement • Flag-controlled loops• Debuggers• Diagnostic statements• Common errors

Figure 5.1

Flow Diagram of Loop Choice Process

Types of LoopsTable 5.1

Counter-Controlled Loops

• Used when you know the number of times the loop must execute

• General steps:1. Set loop control variable to 02. While loop control variable < final value• Execute statements• Increase loop control variable by 1

Figure 5.3

Flowchart for a while Loop

Figure 5.2

Program Fragment with a Loop

Figure 5.4

Program to Compute Company Payroll

Figure 5.

Program to Compute Company Payroll (cont’d)

Compound Assignment Operators

Table 5.3

Figure 5.5

Using a for Statement in a Counting Loop

for Loop Style

• Separate lines for each expressionfor (count_emp = 0;

count_emp < number_emp;

count_emp += 1 )

{…}

• All expressions on one linefor (i = 0; i < max; i += 1)

{…}

Figure 5.6

Comparison of Prefix and Postfix Increments

Figure 5.7

Function to Compute Factorial

Figure 5.8 Displaying a Celsius-to-Fahrenheit Conversion Table

Conditional Loops

• Execute until a condition is no longer true or becomes true.

• Example using a while statement:printf("Enter number of values> ");scanf("%d", &num_obs);while (num_obs < 0) { printf("Negative, try again> "); scanf("%d", &num_obs);}

Figure 5.9 Program to Monitor Gasoline Storage Tank

Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)

Figure 5.9

Program to Monitor Gasoline Storage Tank (cont’d)

Sentinel-Controlled Loop

• Data value is used to determine end-point.• General format

1. Get a line of data2. While the sentinel value has not been

encountereda. Process the data line.b. Get another line of data.

Correct vs. Incorrect Sentinel Loop

Correct1. Initialize sum to 02. Get first score3. while score is not the

sentinela. Add score to sumb. Get next score

Incorrect1. Initialize sum to 02. while score is not the

sentinela. Get scoreb. Add score to sum

Figure 5.10

Sentinel-Controlled while Loop

Sentinel Loop with a for Statement

/* Accumulate sum of all scores.printf(“Enter first score (or %d to quit)> “, SENTINEL);for (scanf(“%d”, &score);

score != SENTNEL;scanf(“%d”, &score)) {

sum += score;printf(“Enter next score (%d to quit)> ”, SENTINEL);

Endfile-Controlled Loops• Used to read a file into memory.• Loop until EOF.• General format:

1. Get the first data value and save input status.

2. While input status does not indicate that end of file has been reached.

a. Process data value.b. Get next data value and save input status.

Figure 5.11 Batch Version of Sum of Exam Scores Program

Figure 5.12

Program to Process Bald Eagle Sightings for a Year

Figure 5.12

Program to Process Bald Eagle Sightings for a Year (cont’d)

Figure 5.13 Nested Counting Loop Program

do-while Statement

Example 5.9

do {printf(“Enter a letter from A through E>

“);scanf(“%c”, &letter_choice);

} while (letter_choice < ‘A’ || letter_choice > ‘E’);

Flag-Controlled Loops

• Declare a flag variable of type int.• Initialize the flag to a value that is not the exit

condition.• Loop on the flag becoming true or false.• Set the flag within the loop to indicate exit

condition.

Figure 5.14 Validating Input Using do-while Statement

Figure 5.15

Structure Chart for Computing Solar Collecting Area Size

Figure 5.16

Program to Approximate Solar Collecting Area Size

Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

Debugger

Debugger allows:– Single-step execution– Setting breakpoints on a statement–Variable inspections

Diagnostic Calls

• Use printf to output intermediate results.• Define a constant named DEBUG and use

a conditional:#define DEBUG 1

if (DEBUG)

printf("*** score is %d, sum is %d\n", score, sum);

Off by One Errors

• This loop executes n+1 times:for (count = 0; count <= n; ++count)

sum += count;

• Always test at the loop boundaries to verify the loop does the right thing.

Common Errors• Forgetting to use curly braces around

multiple steps• Termination condition never met (infinite

loop)• Mistyping an equality operator (==) as an

assignment operator (=)• Confusing do-while and while• Mistakes related to operator precedence– Avoid increment, decrement, and compound

assignment operators in complex expressions.– Use parentheses to control evaluation order.