Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.

Slides:



Advertisements
Similar presentations
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
Advertisements

Outline 5.1 REPETITION IN PROGRAMS
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
CS201 - Repetition loops.
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.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 CS 201 Repetition Debzani Deb. 2 Overview Loops  Endfile-Controlled loop  Nested loop  Do-While loop  Flag-Controlled loop Hand Tracing the code.
Chapter 5: Loops and Files.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 5 (Loop Statements)
Chapter 5 Repetition and Loop Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 5: Control Structures II (Repetition)
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.
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Unit 4 Repetition and Loops. Key Concepts Flowcharting a loop Types of loops Counter-controlled loops while statement Compound assignment operator for.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 ICS103 Programming in C Ch5: Repetition and Loop Statements.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Program Errors and Debugging Week 10, Thursday Lab.
Chapter 5 Repetition and Loop Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville,
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.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
© 2012Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CISC105 – General Computer Science Class 4 – 06/14/2006.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
PGT C Programming1 Week 4 – Repetition Structures / Loops.
Chapter 5 Repetition and Loop Statements. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-2 Figure 5.1 Flow Diagram of Loop Choice Process.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
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.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Repetition statements
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Chapter 5: Repetition and Loop Statements
Repetition and Loop Statements
Repetition and Loop Statements
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of Technology

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-2 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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-3 Repetition in Programs (Cont’) 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?

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-4 Figure 5.1 Flow Diagram of Loop Choice Process

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-5 Loop Kinds

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-6 Counting Loops and the while Statement 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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-7 The while Statement

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-8 The while Statement (Cont’) 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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-9 Figure 5.3 Flowchart for a while Loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-10 The while Statement (Cont’) 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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-11 The while Statement (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-12 Computing a Sum or a Product in a Loop accumulator –a variable used to store a value being computed in increments during the execution of a loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-13 Figure 5.4 Program to Compute Company Payroll

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-14 Multiplying a List of Numbers

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-15 Compound Assignment Operators variable = variable op (expression); variable op= expression;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-16 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. /* Display nonnegative numbers < max */ for (i = 0; i < max; i += 1) printf("%d\n", i);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-17 Figure 5.5 Using a for Statement in a Counting Loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-18

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-19 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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-20 Figure 5.6 Comparison of Prefix and Postfix Increments

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-21 Increment and Decrement Operators (Cont’) 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)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-22 Figure 5.7 Function to Compute Factorial

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-23 Figure 5.8 Displaying a Celsius-to- Fahrenheit Conversion Table

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-24 Conditional Loops 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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-25 Conditional Loops (Cont’) Example printf("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 */ }

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-26 Figure 5.9 Program to Monitor Gasoline Storage Tank

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-27 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-28 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-29 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 exits when the sentinel value is read. Structure –Get a line of data. –while the sentinel value has not been encountered Process the data line. Get another line of data.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-30 Calculates the 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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-31 Figure 5.10 Sentinel-Controlled while Loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-32 Using a for Statement to Implement a 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); }

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-33 Endfile-Controlled Loops 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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-34 Endfile-Controlled Loops (Cont’) To detect the end-of-file condition, scanf returns as its result the value of the standard constant EOF Endfile-controlled loop: –Get the first data value and save input status –While input status does not indicate that end of file has been reached Process data value Get next data value and save input status

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-35 Figure 5.11 Batch Version of Sum of Exam Scores Program

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-36 Infinite Loops on Faulty Data assume the user responds to the prompt Enter next score (-99 to quit)> in Fig with the faulty data “7o” –Infinite loops!! Changing the loop repetition condition to –input_status == 1 To warn of bad input if (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); }

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-37 Nested 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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-38 Figure 5.13 Nested Counting Loop Program

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-39 Figure 5.12 Program to Process Bald Eagle Sightings for a Year

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-40 The do-while Statement and Flag- Controlled Loops 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. Implementation do { printf("Enter a letter from A through E> "); scanf("%c", &letter_choice); } while (letter_choice 'E');

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-41

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-42 Flag-Controlled Loops for Input Validation flag –a type int variable used to represent whether or not a certain event has occurred

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-43 Figure 5.14 Validating Input Using do-while Statement

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-44 Flag-Controlled Loops for Input Validation (Cont’) Execution results Enter an integer in the range from 10 to 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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-45 Figure 5.15 Structure Chart for Computing Solar Collecting Area Size

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-46 Figure 5.16 Program to Approximate Solar Collecting Area Size

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-47 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-48 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-49 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-50 How to Debug and Test Programs 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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-51 Using Debugger Programs single-step execution –execute your program one statement at a time 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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-52 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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-53 Debugging without a Debugger (Cont’) Example while (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

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-54 Off-by-One Loop Errors loop boundaries –initial and final values of the loop control variable Make sure that the initial and final values of the loop control variable are correct and that the loop repetition condition is right. Example for (count = 0; count <= n; ++count) sum += count;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-55 Common Programming Errors Remember to end the initialization expression and the loop repetition condition 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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-56 Common Programming Errors (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-57 Common Programming Errors (Cont’) 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 operation do {... printf("One more time? (1 to continue/0 to quit)> "); scanf("%d", &again); } while (again = 1); /* should be: again == 1 */

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-58 Common Programming Errors (Cont’) Use a do-while only when there is no possibility of zero loop iterations. a *= b + c; is equivalent to a = a * (b + c);