Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.

Slides:



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

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.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Computer Science 1620 Programming & Problem Solving.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 12 – Craps Game Application: Introducing Random.
1 Random numbers Random  completely unpredictable. No way to determine in advance what value will be chosen from a set of equally probable elements. Impossible.
What is the out put #include using namespace std; void main() { int i; for(i=1;i
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Slides by Evan Gallagher Fundamental Data Types 09/09/13.
1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Chapter 5: Control Structures II (Repetition)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Copyright © 2013 by John Wiley & Sons. All rights reserved. LOOPS CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30,
Formatting, Casts, Special Operators and Round Off Errors 09/18/13.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
CSIS 113A Lecture 5 Random Numbers, while, do-while.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
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.
CS221 Random Numbers. Random numbers are often very important in programming Suppose you are writing a program to play the game of roulette The numbers.
1 CS161 Introduction to Computer Science Topic #9.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Input Validation 10/09/13. Input Validation with if Statements You, the C++ programmer, doing Quality Assurance (by hand!) C++ for Everyone by Cay Horstmann.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Two: Fundamental Data Types Slides by Evan Gallagher.
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Random numbers in C++ Nobody knows what’s next....
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Arithmetic, Functions and Input 9/16/13. Arithmetic Operators C++ has the same arithmetic operators as a calculator: * for multiplication: a * b – Not.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Week 9 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright © 2013 by John Wiley & Sons. All rights reserved. LOOPS CHAPTER Slides by James Tam Department of Computer Science, University of Calgary April.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Slides by Evan Gallagher
Slides by Evan Gallagher
Monte Carlo Methods Some example applications in C++
Repetitive Structures
REPETITION CONTROL STRUCTURE
C++ Programming: CS150 For.
Controlling execution - iteration
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Topics Introduction to Repetition Structures
LOOPS.
Lecture 4B More Repetition Richard Gesick
Chapter 5 - Functions Outline 5.1 Introduction
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Module 4 Loops.
Wednesday 09/23/13.
Let’s all Repeat Together
CS150 Introduction to Computer Science 1
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Loops Wrap Up 10/21/13

Topics *Sentinel Loops *Nested Loops *Random Numbers

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Processing Input – When and/or How to Stop? We need to know, when getting input from a user, when they are done. One method is to hire a sentinel (as shown) or more correctly choose a value whose meaning is STOP! As long as there is a known range of valid data points, we can use a value not in it.

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Processing Input – When and/or How to Stop? We will write code to calculate the average of some salary values input by the user. Don't know how many there will be. Use a sentinel value to mark the end of the list. Since salaries are never negative, we can safely choose -1 as our sentinel value.

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Processing Input – When and/or How to Stop? Suppose the user entered the sentinel value as the first input. We need to protect against dividing by zero. Using an if-else statement before dividing.

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved #include using namespace std; int main() { double sum = 0; int count = 0; double salary = 0; // get all the inputs cout << "Enter salaries, -1 to finish: "; cin >> salary; while (salary != -1) { sum = sum + salary; count++; cin >> salary; } ch04/sentinel.cpp The Complete Salary Average Program

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved // process and display the average if (count > 0) { double average = sum / count; cout << "Average salary: " << average << endl; } else { cout << "No data" << endl; } return 0; } A program run: Enter salaries, -1 to finish: Average salary: 20 The Complete Salary Average Program

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Sometimes it is easier and a bit more intuitive to ask the user to “Hit Q to Quit” instead or requiring the input of a sentinel value. Sometimes picking a sentinel value is simply impossible – if any valid number is allowed, which number could be chosen? Using Failed Input for Processing

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Using the input attempt directly we have: cout << "Enter values, Q to quit: "; while (cin >> value) { // process value here } cin.clear(); Using Failed Input for Processing

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Nested Loops Nested loops are used mostly for data in tables as rows and columns. The processing across the columns is a loop, as you have seen before, “nested” inside a loop for going down the rows. Each row is processed similarly so design begins at that level. After writing a loop to process a generalized row, that loop, called the “inner loop,” is placed inside an “outer loop.”

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Nested Loops Write a program to produce a table of powers. The output should be something like this:

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Nested Loops The first step is to solve the “nested” loop. There are four columns and in each column we display the power. Using x to be the number of the row we are processing, we have (in pseudo-code): You would test that this works in your code before continuing. If you can’t correctly print one row, why try printing lots of them?

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Nested Loops Now, putting the inner loop into the whole process we have: (don’t forget to indent, nestedly)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved #include using namespace std; int main() { const int NMAX = 4; const double XMAX = 5; // Print table header for (int n = 1; n <= NMAX; n++) { cout << setw(10) << n; } cout << endl; for (int n = 1; n <= NMAX; n++) { cout << setw(10) << "x "; } cout << endl << endl; ch04/powtable.cpp The Complete Program for Table of Powers

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved // Print table body for (double x = 1; x <= XMAX; x++) { // Print table row for (int n = 1; n <= NMAX; n++) { cout << setw(10) << pow(x, n); } cout << endl; } return 0; } The program run would be: The Complete Program for Table of Powers

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved More Nested Loop Examples The loop variables can have a value relationship. In this example the inner loop depends on the value of the outer loop. for (i = 1; i <= 4; i++){ for (j = 1; j <= i; j++) cout << "*"; cout << endl; } The output will be: * ** *** ****

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved More Nested Loop Examples for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; i represents the row number or the line number j is each line’s length, which is different for each line. and depends on the current line number, i * * * * * *

More Nested Loop Examples C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved j is each line’s length, which is different for each line. and depends on the current line number, i for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; j stops at: i 1 when i is: i 1 i represents the row number or the line number

More Nested Loop Examples C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; j stops at: i 1 when i is: i 1 i represents the row number or the line number j is each line’s length, which is different for each line. and depends on the current line number, i *

More Nested Loop Examples C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; j stops at: i 1 when i is: i 1 i 2 * * i represents the row number or the line number j is each line’s length, which is different for each line. and depends on the current line number, i *

More Nested Loop Examples C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; j stops at: i i i when i is: i 1 i 2 i 3 i represents the row number or the line number j is each line’s length, which is different for each line. and depends on the current line number, i * * * *

More Nested Loop Examples C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; j stops at: i i i i when i is: i 1 i 2 i 3 i 4 i represents the row number or the line number j is each line’s length, which is different for each line. and depends on the current line number, i * * * * * *

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Random Numbers and Simulations A die toss another die toss and another die toss several tosses of dice one more die is tossed was that an English lesson?

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Simulations A simulation program uses the computer to simulate an activity in the real world (or in an imaginary one).

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Simulations Simulations are commonly used for –Predicting climate change –Analyzing traffic –Picking stocks –Many other applications in science and business

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Randomness for Reality (Simulating) Programmers must model the “real world” at times. Consider the problem of modeling customers arriving at a store. Do we know the rate? Does anyone? How about the shopkeeper!

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Randomness for Reality (Simulating) Ask the shopkeeper: It’s about every five minutes …or so… …give or a take a couple… …or three… …but on certain Tuesdays…

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Randomness for Reality (Simulating) To accurately model customer traffic, you want to take that random fluctuation into account. How?

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The rand Function The C++ library has a random number generator: rand()

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The rand Function rand is defined in the cstdlib header Calling rand yields a random integer between 0 and RAND_MAX (The value of RAND_MAX is implementation dependent)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The rand Function Calling rand again yields a different random integer Very, very, very rarely it might be the same random integer again. (That’s OK. In the real world this happens.)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The rand Function rand picks from a very long sequence of numbers that don’t repeat for a long time. But they do eventually repeat. These sorts of “random” numbers are often called pseudorandom numbers.

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The rand Function rand uses only one pseudorandom number sequence and it always starts from the same place.

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The rand Function When you run your program again on another day, the call to rand will start with: the same random number! Is it very “real world” to use the same sequence over and over? No, but it’s really nice for testing purposes. but…

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Seeding the rand Function You can “seed” the random generator to indicate where it should start in the pseudorandom sequence Calling srand sets where rand starts srand is defined in the cstdlib header

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Seeding the rand Function But what value would be different every time you run your program? How about the time? (hint)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Seeding the rand Function You can obtain the system time. Calling time(0) gets the current time Note the zero. It is required. time is defined in the time header

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Seeding the rand Function Calling srand sets where rand starts. Calling time(0) gets the current time. So, to set up for “really, really random” random numbers on each program run: srand(time(0)); // seed rand() (Well, as “really random” as we can hope for.)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Modeling Using the rand Function Let’s model a pair of dice,

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Modeling Using the rand Function one die at a time.

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Modeling Using the rand Function What are the numbers on one die?

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Modeling Using the rand Function Numbers we can work with please!

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Modeling Using the rand Function What are the bounds of the range of numbers on one die? 1 and 6 (inclusive) We want a value randomly between those endpoints (inclusively)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved a b Modeling Using the rand Function Given two endpoints, a and b, recall there are ( b - a + 1) values between a and b, (including the bounds themselves). (b - a + 1)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved a b Modeling Using the rand Function (b - a + 1) Obtain a random value between 0 and b – a by using the rand() function rand() % (b - a + 1)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved a b Modeling Using the rand Function (b - a + 1) Start at a

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved a b Modeling Using the rand Function (b - a + 1) Add that random value to a and you have: int d = rand() % (b - a + 1) + a; rand() % (b - a + 1)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved a b Modeling Using the rand Function (b - a + 1) int d = rand() % (b - a + 1) + a; a random value in the range. rand() % (b - a + 1)

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Using 1 and 6 as the bounds and modeling for two dice, running for 10 tries, we have: Modeling Using the rand Function

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Modeling Using the rand Function #include using namespace std; int main() { srand(time(0)); for (i = 1; i <= 10; i++) { int d1 = rand() % 6 + 1; int d2 = rand() % 6 + 1; cout << d1 << " " << d2 << endl; } cout << endl; return 0; } ch04/dice.cpp One of many different Program Runs:

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The Monte Carlo Method The premier gaming “table d’darts” at one of the less well known casinos in Monte Carlo, somewhat close but not quite next door to Le Grand Casino.

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved The Monte Carlo Method As long as we’re here, let’s go in!

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Summary

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Summary

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Summary

C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved End Chapter Four Slides by Evan Gallagher