CSIS 113A Lecture 5 Random Numbers, while, do-while.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Control Structures II (Repetition)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
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)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
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.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Previously Repetition Structures While, Do-While, For.
1 Chapter 9 Additional Control Structures Dale/Weems.
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.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 05 (Part III) Control Statements: Part II.
C++ Programming Lecture 10 Functions – Part II
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Control Structures RepetitionorIterationorLooping Part I.
1 CS161 Introduction to Computer Science Topic #8.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
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.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Advanced loop controls. Loop Controls Recall from last week loop controls Event-controlled loops using sentinels repeats until a control variable takes.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Introduction to Computer Programming
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Control Structures II (Repetition)
Introduction To Repetition The for loop
Lecture 7: Repeating a Known Number of Times
Controlling execution - iteration
Loop Structures.
Quick Test What do you mean by pre-test and post-test loops in C?
Control Structures II (Repetition)
Programming Fundamentals
Lecture 4B More Repetition Richard Gesick
Control Structure Senior Lecturer
Chapter 6: Repetition Statements
Computing Fundamentals
2.6 The if/else Selection Structure
Chapter 5: Control Structures II (Repetition)
Repetition Statements (Loops) - 2
Presentation transcript:

CSIS 113A Lecture 5 Random Numbers, while, do-while

Random Numbers rand() – Returns a pseudo-random integral number in the range 0 to RAND_MAX –number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. RAND_MAX is a constant defined in. –Its default value may vary between implementations but it is guaranteed to be at least

Scaling Use the mod operator % – x = rand() % 100; Generates a random number between 0 & 99 More rand() – rand() % is in the range 1 to 100 Typical use with variables –Val = (rand() % max) + min; »Returns random number between min and max

Seeding Can interject more randomness in algorithm by seeding it –srand(value); Where do you get value? –Best to seed from time of day clock Must include –Use time(0) so »srand(time(0)) Only call srand() one time –Do not include in a loop!

Example #include #include using namespace std; int main() { srand(time(0)); // See from time of day clock for(int i = 0; i < 10; i++) { cout << (rand() % 100) + 1 << endl; } }

The while Loop Syntax Parts of a while –Keyword while, a boolean test, loop body

Counted while Loops To use the while statement to build a counted loop, you must do three things: –1. Create a counter variable, and initialize it before the loop is encountered. –2. Test the counter variable inside the while loop's boolean condition expression –3. Update your counter at the end of the loop body. This takes the place of the for loop's update expression.

A Counted while Skeleton –int counter = 0; while (counter < 10 ) { // Loop body statements counter++; }

Common while Loop Errors I Several problems common to counted while loops Using an "expired" counter –Define and initialize counter in for initializer Looks empty if you forget initialization Allows you to use the same variable name in each loop –The while requires counter initialization before loop –You must remember to initialize your counter just before you enter the loop

Common while Loop Errors II Endless Loops –Not unique to while loops Change exponential for loop bounds to –Counted while loops are especially susceptible Counter update is often far removed from test Makes it easy to forget the update –Solution? Use loop-building strategy that starts with bounds Get mechanics working before attacking the goal

Common while Loop Errors III The phantom semicolon –If you put a semicolon after the test condition of a while loop, its body becomes the null statement u int counter = 0; while (counter < 10 ); { // This is unreachable counter++; }

Indefinite Loops How many times will this loop execute? int someNumber = rand() % 1000; while ( someNumber != 500 ) { someNumber = rand() % 1000; cout << someNumber << endl; } You can’t tell. That’s why it’s an indefinite loop –This is where the while loop really shines

Indefinite One way Indefinite works –integer variable someNumber is assigned a value between 0 and 999, using the rand() function –Variable someNumber is compared to 500 in while test If it is not equal to 500 then the loop body is entered In the loop body, the number of repetitions is incremented and displayed A new value for someNumber is then generated This kind of indefinite loop is called a Sentinel Loop –A specific value [500] is searched for

Sentinel Ranges I Sentinel doesn't have to be a single value –It may include a range of values Here's a problem that requires a sentinel range "Generate random integer numbers until a negative number is generated. Display the sum, count, and average of the numbers entered"

Sentinel Ranges II Questions you should ask –1. What is the loop's bounds? –2. What are the necessary preconditions? –3. What actions are required to advance the loop? –4. What is the loop's goal? –5. What are the goal preconditions? –6. What actions are necessary in the body? –7. What postconditions are necessary for the goal?

Sentinel Ranges III 1. What is the loop's bounds? –Answer: A negative number was generated –The C++ loop condition should look like this: while (num >= 0) 2. What are the necessary preconditions? –Look at the test condition; num must have a value –int num = rand();

Sentinel Ranges IV 3. What actions advance the loop? –Must change something in the test expression –Should generate another random number At this point, the "mechanics" are finished –You can test the loop to see that it works 4. What is the loop's goal? –Display the count, sum and average of positive integers generated

Sentinel Ranges V What are the goal preconditions? –Must have variables for the count and sum Sum should be a double because of overflow count and sum must both be initialized int count = 0; double sum = 0.0; 6. What actions are necessary to advance goal? –Add num to sum, incr count, before next num count++; sum += num;

Sentinel Ranges VI 7. What post-condition actions are required? –Must check for a count of zero. Means no numbers were entered Can't compute the average if there are no numbers –If count is > 0 then Compute and display the sum and the average

Primed and Inline Tests I So far, all our indefinite loops have been primed –Initialize the test condition before the loop Usually this involves reading a value This is called priming the loop –Test the value in the loop condition –Process the value in the body of the loop –Initialize the test condition at bottom of loop body Preparing for the next repetition of the loop Means "preparation" statements appear in two places

Intentional and Necessary Bounds Suppose you search a String for the letter "F" –A sentinel bounds is the obvious choice while (s[i] != 'F') i++; But what if the letter 'F' is not in the String s ? –You need to supply an additional bounds to use in case the value you are looking for is not found –This additional bounds is called a necessary bounds while (i < s.length && s[i] != 'F') i++;

Two Logical Problems The impossible condition if (age > 65 && age < 21) … –Solution? Change order if you are trying to bound value Change AND to OR The unavoidable condition if (age > 21 || age < 65) –Solution? Change OR to AND

Bottom-Testing One more loop in addition to for and while –The do-while loop is an exit-condition loop –That means the test is located after the body do { Statements; } while ( boolean condition ); Notice position of semicolon Generally not the loop of choice. [See next page]

The do-while Illustrated

C++ Jumps: break and continue Two jump statements from inside a loop –To restart the loop: use continue For while and do-while this jumps to the test With for it jumps to the update expression –To exit the loop: use break for (int i = 0; i < 7; i++) { if ( i % 2 == 0) continue; if ( i == 5 ) break; cout<< i << endl; }