(6-2) Iteration in C II H&K Chapter 5 Instructor - Andrew S. O’Fallon CptS 121 (February 19, 2016) Washington State University.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Arrays H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 13, 2011) Washington State University.
Modular Programming (2) H&K Chapter 6 Instructor – Gokcen Cilingir Cpt S 121 (July 8, 2011) Washington State University.
Iteration in C H&K Chapter 5 Instructor – Gokcen Cilingir Cpt S 121 (July 1, 2011) Washington State University.
Selection structures – logical expressions and if statements H&K Chapter 4 Instructor – Gokcen Cilingir Cpt S 121 (June 28, 2011) Washington State University.
Arrays (III) H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 15, 2011) Washington State University.
Chapter 5 Repetition and Loop Statements Instructor: Alkar & Demirer.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 5: Control Structures II (Repetition)
1 CS 201 Repetition Debzani Deb. 2 Overview Loops  Endfile-Controlled loop  Nested loop  Do-While loop  Flag-Controlled loop Hand Tracing the code.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Looping Exercises Deciding Which Loop to Use At this.
Chapter 5: Control Structures II (Repetition)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
13&14-2 Know the forms of loop statements in C (while,do/while,for). Understanding how data conversion occurs. Read/Write data in files using Unix redirection.
(4-2) Selection Structures in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 16, 2015) Washington State University.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
(2-2) Functions I H&K Chapter 3 Instructor - Andrew S. O’Fallon CptS 121 (Spetember 9, 2015) Washington State University.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
(5-1) Selection Structures III in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 21, 2015) Washington State University.
(4-3) Selection Structures II in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 18, 2015) Washington State University.
(9-1) Strings I H&K Chapter 8 Instructor - Andrew S. O’Fallon CptS 121 (October 19, 2015) Washington State University.
(6-3) Modular Programming H&K Chapter 6 Instructor - Andrew S. O’Fallon CptS 121 (October 2, 2015) Washington State University.
(3-1) Functions II H&K Chapter 3 Instructor - Andrew S. O’Fallon CptS 121 (September 9, 2015) Washington State University.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
(7-2) Arrays I H&K Chapter 7 Instructor - Andrew S. O’Fallon CptS 121 (October 9, 2015) Washington State University.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Chapter 7 Problem Solving with Loops
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
ECE Application Programming
Lesson #5 Repetition and Loops.
REPETITION CONTROL STRUCTURE
Lesson #5 Repetition and Loops.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
Lesson #5 Repetition and Loops.
Java Programming Loops
Chapter 5: Control Structures II (Repetition)
Java Programming Loops
Lesson #5 Repetition and Loops.
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

(6-2) Iteration in C II H&K Chapter 5 Instructor - Andrew S. O’Fallon CptS 121 (February 19, 2016) Washington State University

C. Hundhausen, A. O’Fallon 2 Don’t Forget About Flowcharts! Recall: flowcharts provide visual representations of algorithms and/or processes Excellent tool for verifying logical flow

C. Hundhausen, A. O’Fallon 3 General Structure of Flowchart for Loops Process body of loop Condition? Yes or T No or F

C. Hundhausen, A. O’Fallon 4 Conditional Loops (1) In the previous lecture, we considered loops whose number of iterations was known at the time the loop started In practice, we don’t always know in advance how many times a loop will execute! – Often, the loop body itself determines whether another execution is necessary

C. Hundhausen, A. O’Fallon 5 Conditional Loops (2) Consider, for example, the following extension to the Tollbooth application: – Suppose that, for safety reasons, the tollbooth limits the number of vehicles that can cross the bridge on a given day to a certain tonnage. – Suppose that you want to read in vehicle data from a file to simulate cars crossing the bridge. – When the maximum tonnage has been reached, not more data are read from file.The program prints out a message reporting the revenues collected for the day the number and total weight of all cars that crossed for the day – See next slide for a possible solution

C. Hundhausen, A. O’Fallon 6 Conditional Loops (3) #include #define MAX_TONS_PER_DAY 20 #define POUNDS_PER_TON 2000 … void main(void) { int vehicle_count, axles; double weight, tons, toll, total_tolls; FILE *infile; infile = get_and_open_file(); count = tons = total_tolls = 0; while (tons < MAX_TONS_PER_DAY) { axles = read_num_axles(infile); weight = read_weight(infile); toll = compute_toll(axles,weight); count++; /* Another car has crossed. */ tolls += toll; /* Another toll has been collected */ tons += weight/2000.0; /* Add weight of this car */ /* to running total*/ } printf("%d cars, weighing %.2f tons, crossed the bridge today.", count, tons); printf("$%.2f in tolls was collected today.",total_tolls); }

C. Hundhausen, A. O’Fallon 7 Conditional Loops (4) A possible sequence of questions that can guide loop design, applied to previous example QuestionAnswerImplications for design 1. What are the inputs?Weight of vehicle, # of axles Input vars: weight, axles 2. What are the outputs?# and weight of vehicles that cross bridge; tolls collected Output vars: count, tons, total_tolls

C. Hundhausen, A. O’Fallon 8 Conditional Loops (5) A possible sequence of questions that can guide loop design, applied to previous example (cont.) QuestionAnswerImplications for design 3. Is there repetition?Yes! We repeatedly Get # axles and weight Calculate toll Add weight to total weight Add toll to total tolls Add 1 to vehicle count Program variable needed: MAX_TONS_ PER_DAY

C. Hundhausen, A. O’Fallon 9 Conditional Loops (6) A possible sequence of questions that can guide loop design, applied to previous example (cont.) QuestionAnswerImplications for design 4. Do I know in advance how many steps will be repeated? No.Loop will NOT be controlled by counter 5. How do I know how long to keep repeating steps? As long as the total weight of the vehicles is below the maximum The loop repetition condition is total_tons < MAX_TONS_ PER_DAY

C. Hundhausen, A. O’Fallon 10 Sentinel-Controlled Loops (1) 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)

C. Hundhausen, A. O’Fallon 11 Sentinel-Controlled Loops (2) #include #define SENTINEL_VALUE 'n' #define POUNDS_PER_TON 2000 … void main(void) { 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 */ } …

C. Hundhausen, A. O’Fallon 12 Sentinel-Controlled Loops (3) 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 */ 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) "); } …

C. Hundhausen, A. O’Fallon 13 Endfile-Controlled Loops (1) Often, as in the original toll booth application, we read input data in from a file We want to continue processing data until there is no more data to process In other words, we want to continue processing data until the end of the file is encountered We can use the endfile-controlled loop pattern to do this

C. Hundhausen, A. O’Fallon 14 Endfile-Controlled Loops (2) For example, suppose that we change the requirements of the tollbooth application again – We will read the input values from a text file, as before – We will continue reading axle/weight pairs until we reach the end of the file – We will need to redesign two functions we wrote in class a couple of weeks ago: read_num_axles read_weight – Let's look at the implementation…

C. Hundhausen, A. O’Fallon 15 Endfile-Controlled Loops (3) fscanf actually returns a value indicating the number of items it successfully reads in If it encounters the end of the file, it returns as its result the value of the standard constant EOF (which is a negative integer) We can thus redesign read_num_axles to return EOF if it encounters the end of the file: int read_num_axles(FILE *infile) { int num_axles, input_status; input_status = fscanf(infile,”%d”,&num_axles); if (input_status != EOF) return (num_axles); else return input_status; }

C. Hundhausen, A. O’Fallon 16 Endfile-Controlled Loops (4) For the sake of simplicity, we will assume that data always come in pairs, so we won't check for EOF in read_weight Challenge question: Do you see another problem with adding EOF-checking to read_weight? Explain. The next slide puts the solution together

C. Hundhausen, A. O’Fallon 17 Endfile-Controlled Loops (5) #include #define POUNDS_PER_TON 2000 … void main() { int count, test_axles, axles; double weight, tons, toll, total_tolls; FILE *infile; infile = get_and_open_file(); count = tons = total_tolls = 0; test_axles = read_num_axles(infile); while (test_axles != EOF) { axles = test_axles; /* We can accept this value as valid. */ weight = read_weight(infile); /* Assume EOF won't be seen. */ 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*/ test_axles = read_num_axles(infile); /* Prepare for next */ /* iteration. */ } … }

C. Hundhausen, A. O’Fallon 18 Flag-Controlled Loops (1) In the previous examples, we have assumed that input data are always in the proper format: – When we ask for the number of axles, we will obtain an integer (either interactively from the user, or from the input file) – When we ask for the weight, we will obtain a double (either interactively from the user, or from the input file) In the real world, this assumption is faulty – People enter invalid data all the time – Files contain invalid data all the time Flag-controlled loops ensure that valid data are read in

C. Hundhausen, A. O’Fallon 19 Flag-Controlled Loops (2) Recall that the fscanf function returns EOF when the end of the file is encountered Likewise fscanf and scanf return the value 0 when at least one the data values it reads in could not be converted to the specified type – For example, assume the following scanf statement int my_int, input_status; printf("Please enter an integer: "); input_status = scanf("%d",&my_int); If the user were to type in "wow" here, i nput_status would be assigned the value 0, since "wow" cannot be converted to an int

C. Hundhausen, A. O’Fallon 20 Flag-Controlled Loops (3) The final C interative construct, the do-while loop, can be used to trap this situation and re-prompt the user: int my_int, input_status; char skip_ch; do { printf("Please enter an integer: "); input_status = scanf("%d",&my_int); do { /* nested do-while skips rest of data line */ scanf("%c", skip_ch); } while (skip_ch != '\n'); } while (input_status == 0); Notice that, unlike the while and for loop constructs, the do-while loop construct is guaranteed to execute at least once.

C. Hundhausen, A. O’Fallon 21 Flag-Controlled Loops (4) You try it: Given this pattern, tailor interactive versions of read_num_axles so that they only accept valid input (an int or a double ) from the user (work with a partner for 5 minutes) int read_num_axles() { int num_axles, input_status; /* your code goes here */ } double read_weight() { double weight; int input_status; /* your code goes here */ }

C. Hundhausen, A. O’Fallon 22 Flag-Controlled Loops (5) Now let's go one step further. Let's do a reality check on each input value to make sure it's not only of the correct type, but within an acceptable range: – Num_axles should be between 2 and 5 (no unicycles allowed!) int read_num_axles() { int num_axles, input_status, input_ok; char skip_ch; do { printf("Please enter the number of axles: "); input_status = scanf("%d",&num_axles); input_ok = (input_status != 0 && num_axles > 1 && num_axles < 6); /* status flag */ if (!input_ok) printf("The value you entered is invalid."); do { /* skip rest of data line */ scanf("%c", &skip_ch); } while (skip_ch != '\n'); } while (!input_ok); return num_axles; }

C. Hundhausen, A. O’Fallon 23 Flag-Controlled Loops (6) Now let's go one step further (cont.). – Weight should be between and double read_weight() { int input_status, input_ok; char skip_ch; double weight; do { printf("Please enter the vehicle weight: "); input_status = scanf("%lf",&weight); input_ok = (input_status != 0 && weight >= && weight <= ); if (!input_ok) printf("The value you entered is invalid."); do { /* skip rest of data line */ scanf("%c", &skip_ch); } while (skip_ch != '\n'); } while (!input_ok); return weight; }

C. Hundhausen, A. O’Fallon 24 References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (8 th Ed.), Addison- Wesley, 2016 P.J. Deitel & H.M. Deitel, C How to Program (7 th Ed.), Pearson Education, Inc., 2013.

C. Hundhausen, A. O’Fallon 25 Collaborators Chris Hundhausen