Loop Design What goes into coding a loop. Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated.

Slides:



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

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.
Computer Science 1620 Loops.
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.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
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.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Control Structures Repetition or Iteration or Looping Part II.
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.
Review the following : Flowcharting Variable declarations Output Input Arithmetic Calculations Conditional Statements Loops.
Control Structures RepetitionorIterationorLooping Part I.
Overview Go over parts of quiz? Another iteration structure for loop.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
 for loop  while loop  do-while loop for (begin point; end point ; incrementation ) { //statements to be repeated }
Loops and Files. 5.1 The Increment and Decrement Operators.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
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.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Calvin College Controlling Behavior The if, switch and for Statements.
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.
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.
Control Structures 1 The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
C++ Programming Lecture 12 Functions – Part IV
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
01/05/100 1 Loops/Iteration Used to repeat an action Must have a STOP condition Three flavors - for, while, do/while.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
REPETITION CONTROL STRUCTURE
Loop Structures.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
JavaScript: Control Statements.
Lecture 4B More Repetition Richard Gesick
Arrays & Functions Lesson xx
Iteration with While You can say that again.
TOPIC 4: REPETITION CONTROL STRUCTURE
Alternate Version of STARTING OUT WITH C++ 4th Edition
Loops A loop is a repetition control structure.
Chapter 6: Repetition Statements
Computing Fundamentals
CS150 Introduction to Computer Science 1
Looping III (do … while statement)
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Loops.
Programming Fundamental
Presentation transcript:

Loop Design What goes into coding a loop

Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated sum or product. ● Those that do some repeated processing. ● We will concentrate in the first loop form: those that form some accumulated sum or product. ● Three things have to be designed, in this order: ● What is done inside the loop. ● What has to be done before the loop starts in order for it to work properly (the loop initialization) ● How we end the loop.

A loop skeleton Initialize variables. while/for/do statement loop code end of loop The important points are: 1) Design the loop. 2)Align variables so they have the correct values when the loop starts 3) Decide on a good termination condition.

Example 1 Let us write a loop to add some numbers which are read in. The loop body is very simple: cin >> number; total += number; so the whole thing becomes: Initialize variables while/for/do statement cin >> number; total += number end of loop output total

Adding numbers (continued 1) What variables have to be initialized? The only variables used in the loop are number and total. number is being read in, does not need initialization; however, total does. Both need declarations. Before we look at the declaration, let's look at the initial value of total. What should it be? What should the value be if no numbers have been read? Yes, 0. So, this is the declaration/initialization part: int number; // number to add int total = 0; // Contains the sum of all read in numbers. Note that these declarations do not necessarily have to be at the beginning!

Adding numbers (continued 2) This leaves something like: int total = 0; // Contains the sum of all read in numbers. while/for/do statement int number; cin >> number; total += number; end of loop cout << “Sum is “ << total << endl; Now we have to decide how we are ending the loop.

Adding numbers (continued 3) There are many ways to end the loop; we will discuss two: 1) Knowing beforehand how many items to add. 2) Placing a marker at the end Let us do (1) first.

Adding numbers (continued 4a) Program to add a sequence of numbers, knowing beforehand how many there are. For added versatility, we will read in how many numbers there are in the program. This leaves: int num_data; cin >> num_data; int total = 0; repeat num_data times: int number; cin >> number; total += number; end of loop cout << “Sum is “ << total << endl;

Adding numbers (continued 5a) There are two simple ways to code “repeat num_data times”: The textbook has: for (count = 1; count <= num_data; count++).... but, among many C and C++ programmers, an idiom has developed: for (count = 0; count < num_data; count++)... You are free to use either form, but you will prefer to use the second one when working with arrays, vectors or strings, later on in this course. For that reason, I prefer to always use the second form. The complete program is on the next slide.

Adding numbers (variant (a) final version) // Program to add a given amount of numbers // Michael Rothstein // 01/30/2014 #include using std::cin; using std::cout; using std::endl; int main() { int num_data; cin >> num_data; int total = 0; for(int count = 0;count < num_data;count++){ int number; cin >> number; total += number; } cout << "Sum is " << total << endl; }

Adding numbers, variant a (discussion) ● This example shows how to code a loop when we know in advance the number of times the loop should execute, or when we know, in advance, a maximum number of times that the loop should execute. ● This program may work in some situations, namely, when the number of data is small; however, if we have to count many numbers, we may have a problem. It is very hard to count a large number of things accurately. For that reason, let us look at an alternative way to end the loop.

Adding numbers 1 (continued 3b) So, we are adding a column of numbers. As we discussed before, counting is error prone, so we should try to think up something else). One idea could be to end the numbers with a signal, a “fake” number. (This number is called a sentinel ). It should be a number that cannot occur in the data; for example, if all the numbers are positive, -1 could be a good sentinel value. We will again read in the numbers to add, one by one. Remember, our program skeleton:

Adding numbers (continued 4b) int total = 0; // Contains the sum of all read in numbers. while/for/do statement int number; cin >> number; total += number; end of loop cout << “Sum is “ << total << endl; But, we have to check whether number is -1. That leaves:

Adding numbers (continued 5b) int total = 0; // Contains the sum of all read in numbers. while ( number != -1){ int number; cin >> number; total += number; } cout << “Sum is “ << total << endl; Except that we are reading the number after checking for it! Two solutions: 1) Read before and switch things around. 2) No switch, just check after reading. Will explore both solutions in the next slides.

Adding numbers (continued 6b1) In this alternative, we are going to switch things around: int total = 0; // Contains the sum of all read in numbers. int number; cin >> number; while ( number != -1){ total += number; cin >> number; } cout << “Sum is “ << total << endl; The final version is in the next slide.

Adding numbers, option b1, final version // Program to add numbers until a -1 is input, version 1 // Michael Rothstein // 01/30/2014 #include using std::cin; using std::cout; using std::endl; int main(){ int total = 0; int number; cin >> number; while (number != -1){ total += number; cin >> number; } cout << "Sum is " << total << endl; }

Adding numbers (continued 6b2) In this version, we will simply check after reading. However, since we will not have read a number in the while statement statement, we will have to change the while statement to a nonsense condition: int total = 0; // Contains the sum of all read in numbers. while ( 1){ // This is actually what is usually done. Another idiom! int number; cin >> number; if ( number == -1 ) break; total += number; } cout << “Sum is “ << total << endl; The final version is on the next slide.

Adding numbers, option b2, final version // Program to add numbers until a -1 is input, version 2 // Michael Rothstein // 01/30/2014 #include using std::cin; using std::cout; using std::endl; int main() { int total = 0; // Contains the sum of all read in numbers. while (1){ int number; cin >> number; if( number == -1 ) break; total += number; } cout << "Sum is " << total << endl; }

Adding numbers, final discussion Options b1 and b2 had an unpleasant situation: we basically had half of the loop before we knew whether to finish. This situation is known as loop and a half and the solutions presented are the best ones known at present. Some people prefer option b1 because they do not like to use break, whereas other people prefer b2 because they don't like multiple input statements. As you can see, programming is full of choices. There is not a set way to do many things. Also, C++ has many idioms; you are free to use them or adopt your own, but be consistent.