cpts121-7-1

# cpts121-7-1 - 1 C ptS 121 L7-1 – Pro f C hris Hundha us e...

This preview shows pages 1–5. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 C ptS 121 L7-1 – 10/5/09 Pro f. C hris Hundha us e n CptS 121 Fall ‘09 Lecture 7-1 HK Chapter 5: More Iteration Lecture Outline I. Sentinel-controlled loops II. Endfile-controlled loops III. Flag-controlled loops 2 C ptS 121 L7-1 – 10/5/09 Pro f. C hris Hundha us e n Sentinel-Controlled Loops Often we want to continue looping until a certain value, called a “sentinel,” is encountered For example, suppose we change the requirements of the Tollbooth application slightly: There is no maximum on the total weight of the vehicles that cross the bridge on a given day We will read in vehicle data interactively The user will tell us that there are no more vehicles for the day by entering ‘n’ when asked whether there is another vehicle that needs to cross (‘n’ = “No” the sentinel value) 3 C ptS 121 L7-1 – 10/5/09 Pro f. C hris Hundha us e n Sentinel-Controlled Loop in the Tollbooth Application #include <stdio.h> #define SENTINEL_VALUE 'n' #define POUNDS_PER_TON 2000 … void main() { int count, axles; char continue; double weight, tons, toll, total_tolls; count = tons = total_tolls = 0; printf("Did at least one car cross the bridge? (y/n) "); scanf(" %c ",&continue); /* Note blanks absorb whitespace */ while (continue != SENTINEL_VALUE) { axles = read_num_axles(); /* assume these two functions read */ weight = read_weight(infile); /* prompt user interactively */ toll = compute_toll(axles,weight); count++; /* Another car has crossed. */ total_tolls += toll; /* Another toll has been collected. */ tons += weight/2000.0; /* Add weight of this car to total*/ printf("Did another car cross the bridge? (y/n) "); scanf(" %c ",&continue); /* Note blanks absorb whitespace */ } 4 C ptS 121 L7-1 – 10/5/09 Pro f. C hris Hundha us e n Sentinel-Controlled Loop in the Tollbooth Application (cont.) Note that this could also be rewritten as a for loop: … printf("Did at least one car cross the bridge? (y/n) "); for (scanf(" %c ",&continue); continue != SENTINEL; scanf(" %c ",&continue)) { axles = read_num_axles(); /* assume these two functions read */ weight = read_weight(infile); /* prompt user interactively */...
View Full Document

## This note was uploaded on 01/25/2011 for the course CPTS 121 taught by Professor Hundhaus during the Spring '09 term at Washington State University .

### Page1 / 16

cpts121-7-1 - 1 C ptS 121 L7-1 – Pro f C hris Hundha us e...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online