Control Structures - Repetition

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

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)
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.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
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.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Control Structures Repetition or Iteration or Looping Part II.
Control Structures RepetitionorIterationorLooping Part I.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
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.
Control Structures Repetition or Iteration or Looping Part II.
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II
CS161 Introduction to Computer Science
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Loop Structures.
Control Structures II (Repetition)
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Java Programming: Guided Learning with Early Objects
( Iteration / Repetition / Looping )
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 5: Control Structures II
Control Structures – Selection
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
TOPIC 4: REPETITION CONTROL STRUCTURE
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Additional Control Structures
Chapter 7 Additional Control Structures
Chapter 6: Repetition Statements
Computing Fundamentals
Chapter 5: Control Structures II (Repetition)
Topics Introduction to Repetition Structures
Repetition Statements (Loops) - 2
Control Statements Paritosh Srivastava.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Control Structures - Repetition Chapter 5

Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled Loops Flag Controlled Loops EOF Controlled Loops for Loops The do … while Looping Structure

Why Is Repetition Needed? Consider a task that the computer might automate Calculate and print paychecks Read invoices from a file and print monthly statements Read inputs from a sensor and adjust the air-fuel mixture of an engine In general The "Input – process – output" cycle

Why Is Repetition Needed? The algorithm requires a set of actions to be done over and over again Same set of actions Number of times to be executed is unknown at design time We need a structure which allows Statement(s) to be repeated A method of testing to see whether the statements should be repeated

The Repetition Structure The while loop provides the repetition structure Statement(s) to be repeated A means of checking whether the statement(s) will be repeated Syntax: while ( logicalExpression ) statement;

Phases of Loop Execution Loop entry => flow of control reaches first statement inside loop Iteration => each pass thru the loop Loop test => condition tested before each iteration Loop exit => when termination condition occurs in while statement, loop is NOT executed another time while (condition) statement 1 statement 2 true false

While Loop Illustration Loop Iteration Loop Test Loop Exit Loop Entry

Counter Controlled Loops For when you know exactly how many times the loop should run There are 10 employees for which to print checks There are 60 sensor inputs per second The program needs a Loop Control Variable

Count Controlled Loop Uses a Loop Control Variable (LCV) x = 0; while (x <= 10) { cout << “count = “ << x << endl; x = x + 1; } What gets printed?

Count Controlled Loops The LCV must be ... I nitialized I ncremented I nspected Amen

Count Controlled Loops Initialized x = 0; while (x <= 10) { cout << “count = “ << x << endl; x = x + 1; } Inspected Incremented

Sentinel Controlled Loops Suppose you want to read some positive integers and average them You do not have a preset number of data items in mind. Suppose the number –999 marks the end of data. Then the -999 is your "sentinel" View sample program cin>>variable; while(variable != sentinel) { . . . cin>> variable; }

The flag is set according to some condition Flag Controlled Loops A flag controlled loop uses a Boolean variable to control the loop Example Let found be the Boolean variable found = false; while(!found) { . . . if(expression) found = true; } The flag is set according to some condition

Do you need to know how many items are in the file? Why? Why not? EOF Controlled Loops End of File Controlled Do you need to know how many items are in the file? Why? Why not?

Testing the State of an I/O Stream The name of the input stream (used by itself) returns a value returns a 0 if it is NOT successful it returns a NON zero value if it IS successful

Testing the State of an I/O Stream When reading a file (a named input stream) we wish to know when it reaches the end Since the name returns a 0 or non-0, this can be used as a Boolean value Used to control program sequencing, control a file reading loop

EOF Controlled Loops Can also be used in keyboard entry situations cin>>variable; while(cin) { . . . cin>>variable; // Ctrl-Z to signify eof } Although a sentinel controlled loop might be more user friendly

EOF Controlled Loops In addition to checking the value of an input stream variable … The function eof with an input stream variable can also be used to determine the end of file status. Syntax: istreamVar.eof() Example infile.get(ch); while(!infile.eof()) { cout<<ch; }

A Special Count Controlled Loop The for ( … ) statement Initialization : initializes the LCV Condition : usually a comparison, acts like a while ( …) Incrementing statement : LCV is incremented (or decremented) for ( initialization ; test expression ; update ) { 0 or more statements to repeat }

The for ( … ) Loop Example -- what gets printed? How did it Happen? x gets initialized value of x inspected x gets incremented

The for ( … ) Loop All three of the portions inside the parentheses can be multiple statements separated by commas Any or all of the three portions inside the parenthesis may be missing accomplish those tasks some other way the two semicolons MUST be there

for Loops Note the sequence of events in a for loop Is it possible that the initialization and condition could be set so that that the loop statement would never execute?

A Different Looping Statement Recall that the while ( … ) statement always checked the condition BEFORE the loop In certain situations we wish to check the condition at … The END of the loop After the statement

The Do-While Statement Condition tested at end/bottom of loop Guarantees loop body executes at least once

The do-while Illustrated Note: always at least one iteration Loop Iteration Loop Entry Loop Exit Loop Trest

The Do-While Statement Can be used for a counting loop What gets printed?? How do you change it to go 10 times?

What makes this easier than the while ( … ) loop for this task? The Do While Statement This logic sometimes more suitable for some algorithms Example : trap for valid input do { cout << “Enter value (1 - 5) -> “; cin >> value; if (value < 1 || value > 5) cout << “Invalid input\a” << endl; while (value < 1 || value > 5); What makes this easier than the while ( … ) loop for this task?

do-while Loop vs. while Loop PRE-TEST loop (entry-condition) The looping condition is tested before executing the loop body. Loop body may not be executed at all. POST-TEST loop (exit-condition) The looping condition is tested after executing the loop body. Loop body is always executed at least once.

The break; Statement We saw it in the switch statement Causes immediate exit from innermost block switch, while, do-while, for Can be used to break out of purposely designed infinite loop not a good idea … a lazy shortcut Use only as last resort to avoid baffling combinations of multiple Boolean flags and nested ifs

The continue; Statement Valid only in loops Terminates current loop iteration NOT entire loop Causes branch to bottom of loop skips rest of loop statements Loop then prepares for next iteration for (…) would increment lcv all loops would check condition

Guidelines for Choosing a Looping Statement Simple count-controlled use for (…) loop Event controlled, body always executed at least once use do-while Event controlled and nothing known about first execution use while, possibly for When in doubt => use while

Testing and Debugging For do-while loops, make sure to try data sets to make loop go exactly one time For data-dependant loop where expressions based on values other than constants make sure to test for proper number of iterations Make sure switch statements have every branch tested including default

Testing and Debugging Remember to use break at end of case alternatives in switch statements otherwise next case is also executed! Case labels in switch statement must be values or named constants -- no variables Both switch expression & case constant cannot be floating point Provide default for switch when possibility of case values not being matched

Testing and Debugging Make sure all needed switch cases are present Choose looping structure carefully for( ; ; ) loop heading must have two semicolons -- even if portions omitted Break statement can exit only one level of nesting innermost switch or loop where break is located