Outline 5.1 REPETITION IN PROGRAMS

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

Chapter 04 (Part III) Control Statements: Part I.
Objectives In this chapter, you will learn about:
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
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.
Chapter 5 Repetition and Loop Statements Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.
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.
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.
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)
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.
Unit 4 Repetition and Loops. Key Concepts Flowcharting a loop Types of loops Counter-controlled loops while statement Compound assignment operator for.
Programming Logic and Design Fifth Edition, Comprehensive
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
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.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Chapter 5 Repetition and Loop Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville,
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Loops and Files. 5.1 The Increment and Decrement Operators.
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.
Chapter 7 Problem Solving with Loops
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while 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)
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.
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.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
CHAPTER 6: REPETITION AND LOOP STATEMENTS
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Repetition and Loop Statements
Structured Program
Chapter 5: Repetition and Loop Statements
Repetition and Loop Statements
Repetition and Loop Statements
EPSII 59:006 Spring 2004.
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

Repetition and Loop Statements Chapter 5 Repetition and Loop Statements

Outline 5.1 REPETITION IN PROGRAMS 5.2 COUNTING LOOPS AND THE WHILE STATEMENT 5.3 COMPUTING A SUM OR A PRODUCT IN A LOOP 5.4 THE FOR STATEMENT 5.5 CONDITIONAL LOOPS 5.6 LOOP DESIGN 5.7 NESTED LOOPS 5.8 THE DO-WHILE STATEMENT AND FLAG-CONTROLLED LOOPS 5.9 PROBLEM SOLVING ILLUSTRATED CASE STUDY: COMPUTING RADIATION LEVELS 5.10 HOW TO DEBUG AND TEST PROGRAMS 5.11 COMMON PROGRAMMING ERRORS

前言 Three types of program structure sequence selection repetition  This chapter The repetition of steps in a program is called loop This chapter discuss three C loop control statement while for do-while

5.1 Repetition in programs Loop A control structure that repeats a group of steps in a program Loop body The statements that are repeated in the loop Three questions to determine whether loops will be required in the general algorithm: (Figure5.1) 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?

Figure 5.1 Flow Diagram of Loop Choice Process

Table 5.1 Comparison of Loop Kinds (Page 211) When Used C Implementation Structure Section Containing an Example Counting loop while for 5.2 5.4 Sentinel-controlled loop while, for 5.6 Endfile-controller loop Input validation loop do-while 5.8 General conditional loop 5.5, 5.9

5.2 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 Figure 5.2 shows a program fragment that computes and displays the gross pay for seven employees.

Figure 5.2 Program Fragment with a Loop

Flowchart for a while Loop Loop repetition condition statement

The while Statement Loop repetition condition Loop control variable The condition that controls loop repetition Loop control variable The variable whose value controls loop repetition The loop control variable must be Initialization Testing Updating

Syntax of the while Statement Syntax: while (loop repetition condition) statement Example: /* Display N asterisks. */ count_star = 0; while (count_star < N) { printf(“*”); count_star = count_star + 1; }

5.3 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 Fig.5.4 Program to Compute Company Payroll

Figure 5.4 Program to Compute Company Payroll

Figure 5.4 Program to Compute Company Payroll (cont’d)

Compound Assignment Operators Assignment statements of the form variable = variable op expression Where op is a C arithmetic operator  variable op = expression Table 5.3 Ex. time = time – 1;  time -= 1;

Compound Assignment Operators Simple Assignment Operators Compound Assignment Operators count_emp = count_emp + 1; count_emp += 1; time = time -1; time -= 1; product = product * item; product *= item; total = total / number; total /= number; n = n % (x+1); n %= x+1;

5.4 The for Statement Three loop control components Initialization of the loop variable Test of the loop repetition condition Change (update) of the loop control variable Using a for statement in a counting loop. (Figure 5.5)

Figure 5.5 Using a for Statement in a Counting Loop

Syntax of for Statement Syntax: for (initialization expression; loop repetition condition; update expression) statement Example: /* Display N asterisks */ for (count_star = 0; count_star <N; count_star += 1) printf(“*”);

Increment and Decrement Operators Side effect a change in the value of a variable as a result of carrying out an operation

Figure 5.6 Comparison of Prefix and Postfix Increments

Example 5.3 Function factorial computes the factorial of an integer represented by the formal parameter n. The loop body executes for decreasing values of i from n through 2, and each value of i is incorporated in the accumulating product. Loop exit occurs when i is 1. (Figure 5.7)

Figure 5.7 Function to Compute Factorial

Increments and Decrements Other Than 1 Example 5.4 Use a loop that counts down by five to display a Celsius-to-Fahrenheit conversion table. (Figure 5.8)

Figure 5.8 Displaying a Celsius-to-Fahrenheit Conversion

5.5 Conditional Loops Not be able to determine the exact number of loop repetitions before loop execution begins Ex. Print an initial prompting message Get the number of observed values While the number of values is negative Print a warning and another prompting message

Example 5.5 (Figure 5.9) The program is designed to assist in monitoring the gasoline supply in a storage tank at the Super Oil Company refinery. The program is to alert the supervisor when the supply of gasoline in the tank falls below 10% of the tank’s 80,000 barrel storage capacity. The barrel used in the petroleum industry equals 42 U.S. gallons

Figure 5.9 Program to Monitor Gasoline Storage Tank

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

Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d) Warning message after running out of the loop in monitor_gas

Example 5.5 (Figure 5.9) There are three critical steps in Fig.5.9 that involve the loop control variable current: current is initialized to the starting supply in the for statement initialization expression current is tested before each execution of the loop body current is updated (by subtraction of the amount removed) during each iteration

5.6 Loop Design Sentinel value An end marker that follows the last item in a list of data A loop that processes data until the sentinel value is entered has the form 1. 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 For program readability, we usually name the sentinel by defining a constant macro.

Problem-Solving Questions for Loop Design (pp. 239) Answer Implications for the Algorithm What are the inputs? Initial supply Amounts removed start_supply remov_gals What are the outputs? amount removed current supply current Is there any repetition? yes subprogram monitor_gas Do I know in advance how many times steps will be repeated? no How do I know how long to keep repeating the steps? As long as the current supply is not below the minimum condition: current >=min_supply

Example 5.6 (Figure 5.10) A program that calculates the sum of a collection of exam scores is a candidate for using a sentinel value. Sentinel loop 1. Initialize sum to zero 2. Get first score 3. while score is not the sentinel 4. Add score to sum 5. Get next score Before the while loop

Example 5.6 (cont) (Figure 5.10) Incorrect sentinel loop 1. Initialize sum to zero 2. while score is not the sentinel 3. Get score 4. Add score to sum Two problems No initializing input statement Sentinel value will be added to sum before exit

Figure 5.10 Sentinel-Controlled while Loop

Sentinel-Controlled Structure One input to get the loop going (initialization) Second to keep it going (updating)

Using a for Statement to Implement a Sentinel Loop The for statement form of the while loop in Fig.5.10 /* 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); }

Endfile-Controlled Loops Pseudocode for an endfile-controlled loop 1. Get the first data values and save input status 2. While input status does not indicate that end of file has been reached 3. Process data value 4. Get next data value and save input status

Figure 5.11 Batch Version of Sum of Exam Scores Program

5.7 Nested Loops Nested loops consist of an outer loop with one or more inner loops. Example 5.7 (Figure 5.12) The program contains a sentinel loop nested within a counting loop.

Figure 5.12 Program to Process Bald Eagle Sightings for a Year Inner loop 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)

Example 5.8 (Figure 5.13) A sample run of a program with two nested counting loops. Not be able to use the same variable as the loop control variable of both an outer and an inner for loop in the same nest.

Figure 5.13 Nested Counting Loop Program

5.8 The do-while Statement and Flag-Controlled Loops do-while statement execute at least one time. Pseudocode 1. Get data value 2. If data value isn’t in the acceptable range, go back to step 1.

Syntax of do-while Statement while (loop repetition condition); Example: /* Find first even number input */ status = scanf(“%d”, &num) while (status>0 && (num%2) != 0)

Flag-Controlled Loops for Input Validation A type int variable used to represent whether or not a certain event has occurred A flag has one of two values 1 (true) 0 (false)

Example 5.10 (Figure 5.14) Function get_int returns an integer value that is in the range specified by its two arguments. The outer do-while structure implements the stated purpose of the function. The type int variable error acts as a program flag. error is initialized to 0 and is changed to 1 when an error is detected.

Figure 5.14 Validating Input Using do-while Statement

5.9 Problem Solving Illustrated Case Study: Collecting Area For Solar-Heated House An architect needs a program that can estimate the appropriate size for the collecting area of a solar-heated house. Considerate factors Average number of heating degree days for the coldest month of a year The heating requirements per square foot of floor space Floor space Efficiency of the collection method

Case Study: Collecting Area For Solar-Heated House (cont) Problem The program will have to access two data files File hdd.txt Contains numbers representing the average heating degree days in the construction location for each of 12 months Heating degree days = average temperature difference between insides and outside * number of days in the month File solar.txt Contains the average solar insolation for each month (rate at which solar radiation falls on one square foot of a given location)

Case Study: Collecting Area For Solar-Heated House (cont) Analysis Problem Inputs File: average heating degree days, average solar insolation heat_deg_days, coldest_mon solar_insol, heating_req efficiency, floor_space

Case Study: Collecting Area For Solar-Heated House (cont) Analysis Problem Variables energy_resrc Problem Output heat_loss collect_area

Case Study: Collecting Area For Solar-Heated House (cont) Design Initial Algorithm 1. Determine the coldest month and the average heating degree days for this month. 2. Find the average daily solar insolation per ft2 for the coldest month. 3. Get from the user the other problem inputs: heating_req, efficiency, and floor_space. 4. Estimate the collection area needed. 5. Display results.

Case Study: Collecting Area For Solar-Heated House (cont) Design Refinement 1.1 Scan first value from heating degree days file into heat_deg_days, and initialize coldest_mon to 1. 1.2 Initialize ct to 2 1.3 Scan a value from the file into next_hdd, saving status 1.4 as long as no faulty data/end of file, repeat 1.5 if next_hdd is greater than heat_deg_days 1.6 copy next_hdd into heat_deg_days 1.7 copy ct into coldest_days 1.8 Increment ct 1.9 Scan a value from the file into next_hdd, saving status

Case Study: Collecting Area For Solar-Heated House (cont) Design Refinement 4.1 Calculate heat_loss as the product of heating_req, floor_space, and heat_deg_days 4.2 Calculate energy_resrc as the product of efficiency, solar_insol, and the number of days in the coldest month 4.3 Calculate collect_area as heat_loss divided by energy_resrc. Round result to nearest whole square foot

Case Study: Collecting Area For Solar-Heated House (cont) Design Functions nth_item days_in_item Input file hdd.txt 995 900 750 400 180 20 10 10 60 290 610 1051 Input file solar.txt 500 750 1100 1490 1900 2100 2050 1550 1200 900 500 500

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)

5.10 How to Debug and Test Programs Using debugger programs Execute programs one statement at a time (single-step execution) Set breakpoints at selected statements when a program is very long Debugging without a debugger Insert extra diagnostic calls to printf that display intermediate results at critical points #define DEBUG 1 #define DEBUG 0

Example: debug using printf 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); } #define DEBUG 1 turn on diagnostics #define DEBUG 0 turn off

Off-by-One Loop Errors A common logic error A loop executes one more time or one less time for (count = 0; count <= n; ++count) sum += count; Loop boundaries Initial and final values of the loop control variable execute n+1 time

5.11 Common Programming Errors(1/3) Do not confuse if and while statements if statement implement a decision step while/for statement implement a loop 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. Remember to provide a prompt for the users, when using a sentinel-controlled loop. Make sure the sentinel value cannot be confused with a normal data item.

Common Programming Errors (2/3) Use do-while only when there is no possibility of zero loop iterations. Replace the segment with a while or for statement when adding an if statement. if (condition1) do { … } while(condition1);

Common Programming Errors(3/3) Do not use increment, decrement, or compound assignment operators as subexpressions in complex expressions. Be sure that the operand of an increment or decrement operator is a variable and that this variable is referenced after executing the increment or decrement operation.

Chapter Review (1) Two kinds of loops occur frequently in programming: Counting loops The number of iterations required can be determined before the loop is entered. Sentinel-controlled loops Repetition continues until a special data value is scanned.

Chapter Review (2) Pseudocode for each form Counter-controlled loop Set loop control variable to an initial value of 0. While loop control variable<final value ….. Increase loop control variable by 1 Sentinel-controlled loop Get a line of data While the sentinel value has not been encountered Process the data line Get another line of data

Chapter Review (3) Pseudocode for each form Endfile-controlled loop Get first data value and save input status While input status does not indicate that end of the file has been reached Process data value Get next data value and save input status Input validation loop Get a data value if data value isn’t in the acceptable range, go back to first step

Chapter Review (4) Pseudocode for each form General condition loop Initialize loop control variable As long as exit condition hasn’t been met, continue processing C provides three statements for implementing loops: while, for, do-while The loop control variable must be initialized, tested, and updated.

Question? A good question deserve a good grade…