Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.

Slides:



Advertisements
Similar presentations
Repetition Statements Perform the same task repeatedly Allow the computer to do the tedious, boring things.
Advertisements

CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
Basic Control Structures Control order of execution of statements sequential selection iteration - Repeat some action while a certain condition is true.
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
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.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
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.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
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.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Programming Logic and Design Fifth Edition, Comprehensive
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Java Prepared by Gary Langner Types of Loops u for loop (entrance controlled) –do an action for a definite number of times u while loop (entrance controlled.
Pascal Programming Pascal Loops and Debugging. Pascal Programming Pascal Loops In our first brush with the while do loops, simple comparisons were used.
Overview Go over parts of quiz? Another iteration structure for loop.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
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)
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Unit 3 Lesson 9 Repetition Statements (Loops)
Chapter 5: Control Structures II (Repetition)
Loop Structures.
Control Structures II (Repetition)
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Java Programming: Guided Learning with Early Objects
Control Structures - Repetition
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Alternate Version of STARTING OUT WITH C++ 4th Edition
3 Control Statements:.
Repetition Control Structure
Chapter 6: Repetition Statements
Repetition Statements (Loops) - 2
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:

Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements

Mr. Dave Clausen2 Repetition Statements u Our third control structure: iteration or repetition (completes our 3 control structures: sequence, selection, iteration) u Two main categories of repetition: u definite loop u repeats a predetermined number of times u indefinite loop u repeats a number of times that has not been predetermined.

Mr. Dave Clausen3 Repetition Forms u Three loop types: u for u while u do while u Three basic constructs u A variable is assigned some value. u The value of the variable changes at some point in the loop. u The loop repeats until the variable reaches a predetermined value, the program then executes the next statement after the loop.

Mr. Dave Clausen4 Pretest Loops u Pretest Loop (Entrance Controlled Loops) u a loop where the control condition (Boolean expression) is tested BEFORE the loop. u If the condition is true, the loop is executed. u If the condition is false the loop is not executed u Therefore, it is possible that these loops may not be executed at all (when the condition is False) u There are two pretest loops u for loop u while loop

Mr. Dave Clausen5 Post Test Loops u Post Test Loops (exit-controlled loop) u a loop where the control condition (Boolean expression) is tested AFTER the loop has been executed. u If the condition is true, the loop is executed again. u If the condition is false the loop is not executed again u Therefore, this type of loop will always be executed at least once. u There is one post test loop: do…while

Mr. Dave Clausen6 Fixed repetition loops u Fixed repetition loop u a loop used when you know in advance how many repetitions need to be executed. u also known as a definite loop: u ( you know the definite number of repetitions necessary to solve the problem) u the “for” loop is: u a fixed repetition loop u and a pretest loop

Mr. Dave Clausen7 Variable Condition Loops u Variable Condition Loops u needed to solve problems where the conditions change within the body of the loop. u Also called indefinite loops: u the loop repeats an indefinite number of iterations until some condition is met, or while some condition is met. u The loop terminates depending upon conditions involving sentinel values, Boolean flags, arithmetic expressions, end of line, or end of file markers. u While and do…while loops are variable condition loops.

Mr. Dave Clausen8 The for Loop u General form: for( ; ; ) for(lcv = 1; lcv <= 10; lcv=lcv+1) //Loop Heading cout<< lcv << endl; //Loop body

Mr. Dave Clausen9 Syntax and Semantics of the for Loop for ( ; ; ) termination statement true false initializer update Loop header Loop body

Mr. Dave Clausen10 The for Loop Internal Logic u The control variable is assigned an initial value in the initialization expression u The termination condition is evaluated u If termination condition is true u the body of the loop is executed and the update expression is evaluated u If the termination condition is false u program control is transferred to the first statement following the loop.

Mr. Dave Clausen11 Increment Operator u The Increment operator adds 1 to the variable u Instead of x = x + 1 you can write as + +x u if the + + occurs before the x (+ + x) it is called a prefix operator u if the + + occurs after the x (x+ +) it is called a postfix operator u Our text uses the prefix operator u the prefix executes faster on most compilers

Mr. Dave Clausen12 Decrement Operator u The Decrement operator subtracts 1 from the variable u Instead of x = x - 1 you can write as --x u if the -- occurs before the x (-- x) it is called a prefix operator u if the -- occurs after the x (x--) it is called a postfix operator u Our text uses the prefix operator u the prefix executes faster on most compilers

Mr. Dave Clausen13Accumulator u An accumulator is a variable used to keep a running total or sum of successive values of another variable u i.e. sum = sum + grade; u you should initialize the value of the accumulator before the loop: sum = 0; u the accumulator statement occurs in the body of the loop //lcv means loop control variable sum=0; for(lcv = 1; lcv <= 100; ++lcv) sum = sum + lcv;

Mr. Dave Clausen14 Scope of Loop Control Variable u The loop control variable must be declared before it is used. u The rules for the scope of the variable apply here u If the variable is only going to be used as a loop counter, and for nothing else… u You can limit it’s scope by declaring it when it is initialized in the loop for(int i = 1; i<=10; ++i) cout<<i<<endl;//i is only referenced in loop

Mr. Dave Clausen15 For Loops u For loops can count down (decrement) for(int counter=20; counter>=15; --counter) cout<< counter << endl; u For loops can count by factors other than one for(int counter=2; counter<=10; counter=counter+2) cout<< counter << endl; u Style u Indent the body of the loop, use blank lines before and after, and use comments.

Mr. Dave Clausen16 While Loops u General form: while ( ) u The parentheses around the Boolean is required. u If the condition is true the body of the loop is executed again. u If the loop condition is false, the program continues with the first statement after the loop. u A while loop may not be executed… why?

Mr. Dave Clausen17 Syntax and Semantics of while Statements while ( ) while ( ) {. } ? statement true false

Mr. Dave Clausen18 While Loops: Discussion u The condition can be any valid Boolean Expression u The Boolean Expression must have a value PRIOR to entering the loop. u The body of the loop can be a compound statement or a simple statement. u The loop control condition needs to change in the loop body u If the condition is true and the condition is not changed or updated, an infinite loop could result. u If the condition is true and never becomes false, this results in an infinite loop also.

Mr. Dave Clausen19 The while Loop Accumulator Write code that computes the sum of the numbers between 1 and 10. int counter = 1; int sum = 0; while (counter <= 10) { sum = sum + counter; counter = counter + 1; }

Mr. Dave Clausen20 Sentinel Values and Counters u Sentinel Value u A value that determines the end of a set of data, or the end of a process in an indefinite loop. P309ex1.cppP309ex1.cpp P309ex1.txtP309ex1.txt u While loops may be repeated an indefinite number of times. u It is common to count the number of times the loop repeats. u Initialize this “counter” before the loop u Increment the counter inside the loop

Mr. Dave Clausen21 do…while loops u General form: do { }while ( ) u The Boolean expression must have a value before it is executed at the end of the loop. u If the loop condition is true, control is transferred back to the top of the loop. u If the loop condition is false, the program continues with the first statement after the loop. u A do...while loop will always be executed at least once… why?

Mr. Dave Clausen22 Syntax and Semantics of do… while Statements do while ( ); do {. } while ( ); statement false ? true

Mr. Dave Clausen23  The condition can be any valid Boolean Expression  The Boolean Expression must have a value PRIOR to exiting the loop.  The body of the loop is treated as a compound statement even if it is a simple statement. { }  The loop control condition needs to eventually change to FALSE in the loop body  If the condition never becomes false, this results in an infinite loop. do…while Loops: Discussion

Mr. Dave Clausen24 Choosing which loop to use. u for loop u when a loop is to be executed a predetermined number of times. u while loop u a loop repeated an indefinite number of times u check the condition before the loop u a loop that might not be executed (reading data) u do...while u a loop repeated an indefinite number of times u check the condition at the end of the loop

Mr. Dave Clausen25 Designing Correct Loops u Initialize all variables properly u Plan how many iterations, then set the counter and the limit accordingly u Check the logic of the termination condition u Update the loop control variable properly

Mr. Dave Clausen26 Off-by-One Error int counter = 1; while (counter <= 10) { // Executes 10 passes counter++; } int counter = 1; while (counter < 10) { // Executes 9 passes counter++; }

Mr. Dave Clausen27 Infinite Loop int counter = 1; while (counter <= 10) { // Executes 5 passes counter = counter + 2; } int counter = 1; while (counter != 10) { // Runs forever counter = counter + 2; } In general, avoid using != in loop termination conditions.

Mr. Dave Clausen28 Testing Loops u Can vary the limit or the control variable, or both u Use a negative value, zero, and a positive value u Display an output trace if things aren’t working

Mr. Dave Clausen29 Error Trapping //”primed” while loop cout<<"Enter a score between ”<<low_double<<“ and “<<high_double; cin>>score; while((score high_double)) { cout<<“Invalid score, try again.”; //update the value to be tested in the Boolean Expression cout<<"Enter a score between ”<<low_double<<“ and “<<high_double; cin>>score; }

Mr. Dave Clausen30 Loop Verification u Loop verification u making sure that the loop performs its intended job. u Input assertions u preconditions stating what is true before the loop is executed u Output assertions u post conditions stating what is true after the loop is executed

Mr. Dave Clausen31 Invariant and variant assertions u Loop Invariant u states a relationship among variables that remains the same throughout all repetitions of the loop. u A statement that is true both: u before the loop is entered, and u after each iteration of the loop u Loop Variant u an assertion that changes between the first and last iterations of the loop u should be stated in a way that guarantees that the loop is exited. u Should address the loop variable being incremented or decremented

Mr. Dave Clausen32 Nested Loops u Nested loop u when a loop is one of the statements within the body of another loop. for (k=1; k<=5; ++k) for (j=1; j<=3; ++j) cout<<(k+j)<<endl; u Each loop needs to have its own level of indenting. u Use comments to explain each loop u Blank lines around each loop can make it easier to read Multab.cpp Multab.txt

Mr. Dave Clausen33 Repetition and Selection u The use of an if statement within a loop to look for a certain condition in each iteration of the loop. u Examples: u to generate a list of Pythagorean Triples u to perform a calculation for each employee u to find prime numbers u let’s look at our Case Study program for Chapter 6 primes.cppprimes.cpp primes.txtprimes.txt