CS103L FALL 2018 UNIT 2: CONTROL STRUCTURES. IF…bytes.usc.edu/files/cs103/slides/Unit2.pdfDO-WHILE...
Transcript of CS103L FALL 2018 UNIT 2: CONTROL STRUCTURES. IF…bytes.usc.edu/files/cs103/slides/Unit2.pdfDO-WHILE...
UNIT 2: CONTROL STRUCTURES. IF…ELSE, FOR, WHILE
CS103L FALL 2018
TEXT
LEARNING OBJECTIVES
▸ Understand control flow statements:
▸ if, else-if, else
▸ while, do-while
▸ for
TEXT
QUICK WARMUP
▸ Write a program to ask the user to enter two integers representing hours then minutes
▸ In class exercises
▸ http://bytes.usc.edu/cs103/in-class-exercises/in-class-exercises-set1/
▸ printseconds
▸ Skeleton code including variables is already started
TEXT
COMPARISONS AND LOGICAL OPERATORS
▸ Often we want to check if a condition is true or false
▸ Is x == 100? Is y < 35.5? Is x > z?
▸ Control flow statements require conditions
▸ In C/C++ the integer value 0 means ‘false’. Any value other than 0 is ‘true’
▸ Have bool type and true/false constants to help
▸ Behind the scenes ‘true’ == 1, ‘false’ == 0
TEXT
CONDITIONS
▸ Conditions usually arrive from comparisons and logical operators
▸ Comparisons:
▸ ==, !=, >, <, >=, <=
▸ Equals to, not equals, greater than, less than, greater than or equal, less than or equal
TEXT
LOGICAL OPERATORS
▸ Combine the result of expressions ‘logically’
▸ Logical AND: && operator expr_1 && expr_2
▸ x == 1 && y <= 2
▸ Logical OR: || operator expr_1 || expr_2
▸ x >= 5 || x < 0
▸ Logical NOT: ! operator !expr_1
▸ !(x >= 5 || x < 0)
▸ !x && y < 0
▸ Operator precedence: ! then && then ||
6
Logical AND, OR, NOT• Often want to combine several conditions to make a decision• Logical AND => expr_a && expr_b• Logical OR => expr_a || expr_b• Logical NOT => ! expr_a• Precedence (order of ops.) => ! then && then ||
– !x || y && !z– ( ( !x ) || (y && ( !z ) ) ) … if x=100, y= -3, z=0 then this expression is…
• Write a condition that eats a sandwich if it has neither tomato nor lettuce– if ( !tomtato && !lettuce) { eat_sandwich(); }– if ( !(tomato || lettuce) ) { eat_sandwich(); }
A B ANDFalse False False
False True False
True False False
True True True
A B ORFalse False False
False True True
True False True
True True True
A NOTFalse True
True False
TEXT
LOGICAL OPERATOR PRACTICE
▸ x=100;y=-3;z=0
▸ !x || y && !z
▸ With parens: ((!x) || ( y && (!z)))
TEXT
LOGICAL OPERATOR PRACTICE
▸ Which of the following does *not* check if an integer x is in the range [-1 to 5] (inclusive)
▸ x >= -1 && x <=5
▸ -1 <= x <= 5
▸ !(x < -1 || x > 5)
▸ x > -2 && x < 6
TEXT
IF STATEMENTS
▸ Controlling the flow of your code
TEXT
CONTROL STATEMENT #1: IF…ELSE IF…ELSE
▸ Used to control what code executes based on one or more conditions
▸ Form 1: basic if statement
▸ else block is optional
8
If..Else Flow Chart
condition
if (condition1){// executed if condition1 is True
}else{// executed if neither condition// above is True
}
// following statementsIf Block
StatementsElse
Block Statements
True False
Following statements
8
If..Else Flow Chart
condition
if (condition1){// executed if condition1 is True
}else{// executed if neither condition// above is True
}
// following statementsIf Block
StatementsElse
Block Statements
True False
Following statements
TEXT
IF STATEMENT
▸ Use if to execute only parts of your code
▸ else if is optional, can have as many as you need
▸ final else is also optional, will execute if *none* of the conditions are true
▸ Use {} brackets to associate code with the condition
9
If…Else If…Else
• Use to execute only certain portions of code
• Else If is optional– Can have any number of
else if statements• Else is optional• { … } indicate code
associated with the if, else if, else block
if (condition1){// executed if condition1 is True
}else if (condition2){// executed if condition2 is True// but condition1 was False
}else if (condition3){// executed if condition3 is True// but condition1 and condition2// were False
}else{// executed if neither condition// above is True
}
TEXT
FULL IF STATEMENT FLOW CHART
10
Flow Chart
condition1
if (condition1){// executed if condition1 is True
}else if (condition2){// executed if condition2 is True// but condition1 was False
}else{// executed if neither condition// above is True
}// following statements
If Block Statements
True False
Following Statements
condition
If Block Statements
ElseBlock Statements
True False
Following statements
Else If Statements
cond2
Else Statements
TEXT
IN CLASS EXCERCISES
▸ discount
▸ weekday
▸ N-th
TEXT
STYLE NOTES
▸ Code “style”
▸ What do we mean by that?
▸ Often there are many, many different ways to write even simple code
▸ Try to choose version that is clear, shows intent
TEXT
STYLE QUESTION
▸ Which is better?
▸ Why?
int x; cin >> x;
if( x >= 0) { cout << “Positive”; } if( x < 0 ) { cout << “Negative”; }
int x; cin >> x;
if( x >= 0) { cout << “Positive”; } else { cout << “Negative”; }
TEXT
COMMON BUG
▸ What’s wrong here?
int x; cin >> x;
if( x = 1) { cout << “x is 1!” << endl; } else { cout << “x is not 1.” << endl; }
TEXT
= VS ==
▸ Common mistake to use = (assignment) instead of == (equals to)
▸ The = operator returns the value assigned, so ( x = 1) returns 1
▸ if( x = 1) will always get 1 → true
▸ if() block will always execute! int x; cin >> x;
if( x = 1) { cout << “x is 1!” << endl; } else { cout << “x is not 1.” << endl; }
TEXT
= VS == FIXED
▸ Fixed code
int x; cin >> x;
if( x == 1) { cout << “x is 1!” << endl; } else { cout << “x is not 1.” << endl; }
TEXT
? OPERATOR
▸ Often we find ourselves writing code of the form:
▸ ? is a short cut: z = x > 0 ? 2 : 1;
▸ Syntax: condition ? expr_if_true : expr_if_false;
if (x>0) { z = 2; } else { z = 1; }
TEXT
LOOPS
▸ Doing something more than once
TEXT
WHY DO WE NEED LOOPS?
▸ Almost *all* programs have at least one loop…
▸ Print out numbers 1 - 100
▸ Play a game of rounds until there is a winner
▸ Can we do this without loops?
▸ Maybe?
19
Need for Repetition• We often want to repeat a
task but do so in a concise way– Print out all numbers 1-100– Keep taking turns until a
game is over• Imagine the game of 'war'…it
never ends!!
• We could achieve these without loops, but…
#include <iostream>using namespace std;
int main(){cout << 1 << endl;cout << 2 << endl;...cout << 100 << endl;return 0;
}
#include <iostream>using namespace std;
int main(){bool gameOver;gameOver = take_turn();if( ! gameOver ){gameOver = take_turn();if( ! gameOver ) {
...{
}}
Assume this produces a true/false result indicating if the game is over after performing a turn
19
Need for Repetition• We often want to repeat a
task but do so in a concise way– Print out all numbers 1-100– Keep taking turns until a
game is over• Imagine the game of 'war'…it
never ends!!
• We could achieve these without loops, but…
#include <iostream>using namespace std;
int main(){cout << 1 << endl;cout << 2 << endl;...cout << 100 << endl;return 0;
}
#include <iostream>using namespace std;
int main(){bool gameOver;gameOver = take_turn();if( ! gameOver ){gameOver = take_turn();if( ! gameOver ) {
...{
}}
Assume this produces a true/false result indicating if the game is over after performing a turn
TEXT
LOOP TYPE #1: WHILE LOOP
▸ While loop
▸ Do something while a condition is true
▸ Two forms:
▸ while(condition){ //something }
▸ do { //something } while(condition)
TEXT
WHILE LOOP
▸ condition is evaluated first
▸ If condition is true, body is executed
▸ After body, condition is checked again
▸ Body *should* update condition
▸ Why?
▸ How many times will body execute?
20
while Loop• While
– Cond is evaluated first– Body only executed if cond. is
true (maybe 0 times)
• Do..while– Body is executed at least once– Cond is evaluated– Body is repeated if cond is true
// While Type 1:while(condition){// code to be repeated// (should update condition)
}
// While Type 2:do {// code to be repeated// (should update condition)
} while(condition);
TEXT
DO-WHILE LOOP
▸ Body is executed
▸ Then condition is checked, if true, body is executed again
▸ Body should update condition
▸ How many times will body execute?
20
while Loop• While
– Cond is evaluated first– Body only executed if cond. is
true (maybe 0 times)
• Do..while– Body is executed at least once– Cond is evaluated– Body is repeated if cond is true
// While Type 1:while(condition){// code to be repeated// (should update condition)
}
// While Type 2:do {// code to be repeated// (should update condition)
} while(condition);
TEXT
WHILE LOOP = REPEATING IF
▸ While loop is like a repeating if statement
▸ If your description of the problem (algorithm) contains:
▸ “until <xxx> is true”
▸ “as long as <yyy> is bigger than <x>
▸ “while the player’s guess is wrong”
▸ Then you need a while loop
21
while Loop
• One way to think of a while loop is as a repeating 'if' statement
• When you describe a problem/solution you use the words 'until some condition is true' that is the same as saying 'while some condition is not true'
// guessing gamebool guessedCorrect = false;if( !guessedCorrect ){
guessedCorrect = guessAgain();} // want to repeat if cond. check again if( !guessedCorrect ){
guessedCorrect = guessAgain();} // want to repeat if cond. check again
// guessing gamebool guessedCorrect = false;while( !guessedCorrect ){
guessedCorrect = guessAgain();}
An if-statement will only execute once
A 'while' loop acts as a repeating 'if' statement
TEXT
IN CLASS EXERCISES
▸ countodd
TEXT
FOR LOOP
▸ Very common looping structure
▸ Anatomy: 24
for Loop• Init stmt executed first• Cond is evaluated next• Body only executed if cond. is true• Update stmt executed• Cond is re-evaluated and execution
continues until it is false• Multiple statements can be in the
init and update statements
for(init stmt; cond; update stmt){// body of loop
}
// Outputs 0 1 2 3 4 (on separate lines)for(i=0; i < 5; i++){
cout << i << endl;}
// Outputs 0 5 10 15 … 95 (on sep. lines)for(i=0; i < 20; i++){
cout << 5*i << " is a multiple of 5";cout << endl;
}// Same output as previous for loopfor(i=0; i < 100; i++){
if(i % 5 == 0){cout << i << " is a multiple of 5";cout << endl;
}}
// compound init and update stmts.for(i=0, j=0; i < 20; i++,j+=5){
cout << j << " is a multiple of 5";cout << endl;
}
Initialization statement
conditional expression
update statement
TEXT
FOR LOOP
▸ Initialization statement:
▸ Any valid statement, executed first
▸ Conditional Expression:
▸ Expression evaluated next
▸ Body:
▸ Executed if conditional expression is true
▸ Update statement:
▸ Any valid statement, executed after body
▸ Condition is checked again after Update and body is executed if true… until condition is false
24
for Loop• Init stmt executed first• Cond is evaluated next• Body only executed if cond. is true• Update stmt executed• Cond is re-evaluated and execution
continues until it is false• Multiple statements can be in the
init and update statements
for(init stmt; cond; update stmt){// body of loop
}
// Outputs 0 1 2 3 4 (on separate lines)for(i=0; i < 5; i++){
cout << i << endl;}
// Outputs 0 5 10 15 … 95 (on sep. lines)for(i=0; i < 20; i++){
cout << 5*i << " is a multiple of 5";cout << endl;
}// Same output as previous for loopfor(i=0; i < 100; i++){
if(i % 5 == 0){cout << i << " is a multiple of 5";cout << endl;
}}
// compound init and update stmts.for(i=0, j=0; i < 20; i++,j+=5){
cout << j << " is a multiple of 5";cout << endl;
}
TEXT
TYPICAL FOR LOOP
▸ Initialization statement
▸ Used to initialize counter variable
▸ Condition
▸ Check to see if counter is past desired range
▸ Update statement
▸ Used to update counter variable
24
for Loop• Init stmt executed first• Cond is evaluated next• Body only executed if cond. is true• Update stmt executed• Cond is re-evaluated and execution
continues until it is false• Multiple statements can be in the
init and update statements
for(init stmt; cond; update stmt){// body of loop
}
// Outputs 0 1 2 3 4 (on separate lines)for(i=0; i < 5; i++){cout << i << endl;
}
// Outputs 0 5 10 15 … 95 (on sep. lines)for(i=0; i < 20; i++){cout << 5*i << " is a multiple of 5";cout << endl;
}// Same output as previous for loopfor(i=0; i < 100; i++){if(i % 5 == 0){
cout << i << " is a multiple of 5";cout << endl;
}}
// compound init and update stmts.for(i=0, j=0; i < 20; i++,j+=5){cout << j << " is a multiple of 5";cout << endl;
}
TEXT
FOR VS. WHILE LOOP
▸ When to use while (rule of thumb)?
▸ When we don’t know (can’t quantify) how many times the loop will run
▸ When to use for (rule of thumb)?
▸ When we know how many times, or can quantify how many times the loop will run
▸ Any for loop can be turned into while loop
▸ And vice-versa
▸ Try it!
//guessing game bool guess = false; while(!guess) { guess = guessAgain(); }
int x; cin >> x; for(i = 0; i < x; i++) { cout << i << endl; }here we don’t know x ahead of time, but we can quantify the loop count
TEXT
LOOP PRACTICE
▸ Write a loop to compute the Liebniz approximation to 𝛑/4 using the first 10 terms:
▸ 𝛑/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9…
▸ In-class exercises: liebnizapprox
▸ Tip: write out a table to determine the patternIteration fraction Sign
1 1/1 +
2 1/3 -
3 1/5 +
… … …
TEXT
M0RE LOOP PRACTICE
▸ Write for loops to compute the following approximations out to 10 terms
▸ ex = 1 + x + x2/2! + x3/3! + x4/4!…
▸ Wallis approximation for 𝛑/2
▸ 𝛑/2 = 2/1 * 2/3 * 4/3 * 4/5 * 6/5 * 6/7 * 8/7 …
▸ In class exercises: wallisapprox
TEXT
INFINITE LOOPS
▸ All programmers do it from time-to-time…
▸ An infinite loop is a loop that never exits
▸ while or for loop where condition is always true:
36
The Loops That Keep On Giving• There's a problem with the loop below• We all write "infinite" loops at one time or another • Infinite loops never quit• When you do write such a program, just type "Ctrl-C" at the
terminal to halt the program#include <iostream>using namespace std;int main(){ int val;bool again = true;while(again = true){cout << "Enter an int or -1 to quit";cin >> val;if( val == -1 ) {
again = false;}
}return 0;
}
#include <iostream>using namespace std;int main(){ int i=0;while( i < 10 ) {
cout << i << endl;i + 1;
}return 0;
}
http://blog.codinghorror.com/rubber-duck-problem-solving/
TEXT
INFINITE LOOPS…INFINITE LOOPS…INFINITE LOOPS…INFINITE LOOPS…
▸ If you write one, hit ‘ctrl-c’ on your keyboard to stop the program running
▸ If you’re already in the debugger, you can figure out which loop is infinite
▸ Fixed:
37
The Loops That Keep On Giving• There's a problem with the loop below• We all write "infinite" loops at one time or another • Infinite loops never quit• When you do write such a program, just type "Ctrl-C" at the
terminal to halt the program#include <iostream>using namespace std;int main(){ int val;bool again = true;while(again == true){cout << "Enter an int or -1to quit";cin >> val;if( val == -1 ) {
again = false;}
}return 0;
}
#include <iostream>using namespace std;int main(){ int i=0;while( i < 10 ) {
cout << i << endl;i = i + 1;
}return 0;
}
http://blog.codinghorror.com/rubber-duck-problem-solving/
TEXT
NEAT WHILE-LOOP TRICK TO READ MULTIPLE INPUTS
▸ What’s going on here?
▸ Observe: if (cin >> val) is successful the expression is ‘true’
▸ What does that do?
▸ Ctrl-D makes (cin >> val) fail → false
▸ Nice way to loop and read inputs
▸ We will use this technique again later
38
Getting All The Inputs• Notice another way to receive
all the numbers entered by a user while(cin >> val){ // do stuff }
• In this approach cin does two things– It does receive input into the
variable 'val'– It returns 'true' if it successfully
got input, 'false' otherwise
• Keeps grabbing values one at a time until the user types Ctrl-D
#include <iostream>using namespace std;int main(){ int val;// reads until user hits Ctrl-D// which is known as End-of-File(EOF)cout << "Enter an int or Ctrl-D ";cout << " to quit: " << endl;
while(cin >> val){cout << "Enter an int or Ctrl-D "cout << " to quit" << endl; if(val % 2 == 1){cout << val << " is odd!" << endl;
}else {cout << val << " is even!" << endl;
}}return 0;
}
TEXT
SIDE NOTE ON SYNTAX
▸ Remember { } is a compound statement.
▸ if, while, do-while only require a statement for the body
▸ So sometimes we write “single statement bodies”
▸ Personal preference
▸ I usually always go with { }… why?
▸ First three examples are OK- I don’t like the third
39
Single Statement Bodies• An if, while, or for construct
with a single statement body does not require { … }
• Another if, while, or for counts as a single statement
if (x == 5)y += 2;
elsey -= 3;
for(i = 0; i < 5; i++)sum += i;
while(sum > 0)sum = sum/2;
for(i = 1 ; i <= 5; i++)if(i % 2 == 0)
j++;
TEXT
MORE IN-CLASS EXERCISES
▸ Determine if a number is prime or not?
▸ How to determine if prime (identify the algorithm)
▸ What numbers could be factors?
▸ When can we stop?
▸ Reverse digits of an integer
▸ User enters 123 → 321
▸ User enter -5467 → -7645
TEXT
NESTED LOOPS
▸ Often we want to go over all combinations of two (or more variables) over some range
▸ 2D coordinates for images, 3D coordinates, row-column (matrix operations)
▸ Usually two (or three) for loops, tightly nested
TEXT
NESTED LOOPS
▸ For each iteration of the outer loop, one complete iteration of the inner loop runs
▸ This program outputs:
▸ 0 0
▸ 0 1
▸ 0 2
▸ 1 0
▸ 1 1
▸ 1 2
43
Nested Loops• Inner loops execute fully (go through every iteration before the
next iteration of the outer loop starts)
#include <iostream>#include <iomanip>using namespace std;
int main(){for(int i=0; i < 2; i++){ for(int j=0; j < 3; j++){// Do something based// on i and jcout << i << “ “ << j;cout << endl;
}}return 0;
}
0 00 10 21 01 11 2
Output:
TEXT
NESTED LOOPS
▸ Commonly used for row-column operations like images or matrices
▸ Here we’re printing out row*column
▸ Output isn’t pretty though…
▸ 1234567891011122468101214…
44
Nested Loops• Write a program using nested
loops to print a multiplication table of 1..12
• Tip: Decide what abstract “thing” your iterating through and “read” the for loop as “for each “thing” …– For each “row” …
• For each column… print the product
#include <iostream>
using namespace std;
int main(){for(int r=1; r <= 12; r++){ for(int c=1; c <= 12; c++){
cout << r*c;}
}return 0;
}
1 2 31 1 2 32 2 4 63 3 6 9
This code will print some not so nice output:
12345678910111224681012141618202224…
44
Nested Loops• Write a program using nested
loops to print a multiplication table of 1..12
• Tip: Decide what abstract “thing” your iterating through and “read” the for loop as “for each “thing” …– For each “row” …
• For each column… print the product
#include <iostream>
using namespace std;
int main(){for(int r=1; r <= 12; r++){ for(int c=1; c <= 12; c++){
cout << r*c;}
}return 0;
}
1 2 31 1 2 32 2 4 63 3 6 9
This code will print some not so nice output:
12345678910111224681012141618202224…
TEXT
NESTED LOOP EXAMPLE
▸ Fix #1: add newline at the end of each row.
▸ Where does that go in the code?
▸ Now we get:
▸ 1 2 3 4 5 6 7 8 9 10 11 12
▸ 2 4 6 8 10 12 14 16 18 20 22 24
▸ …
45
Nested Loops• Tip: Decide what abstract “thing”
your iterating through and “read” the for loop as “for each “thing” …– For each “row” …
• For each column… print the product followed by a space
• Print a newline
#include <iostream>
using namespace std;
int main(){for(int r=1; r <= 12; r++){ for(int c=1; c <= 12; c++){
cout << “ “ << r*c;}cout << endl;
}return 0;
}
1 2 31 1 2 32 2 4 63 3 6 9
This code will still print some not so nice output:
1 2 3 4 5 6 7 8 9 10 11 122 4 6 8 10 12 14 16 18 20 22 24
TEXT
NESTED LOOP EXAMPLE
▸ cout can be “fed” things that change its’ behavior
▸ setw(x): print each thing padded to a width of 4 (with spaces)
▸ Fixes our printing problem
46
Nested Loops• Tip: Decide what abstract
“thing” your iterating through and “read” the for loop as “for each “thing” …– For each “row” …
• For each column… print the product
#include <iostream>#include <iomanip>using namespace std;
int main(){for(int r=1; r <= 12; r++){ for(int c=1; c <= 12; c++){
cout << setw(4) << r*c;}cout << endl;
}return 0;
}
1 2 31 1 2 32 2 4 63 3 6 9
TEXT
IN-CLASS EXERCISES
▸ 5-per line (A, B, C)
TEXT
BREAK AND CONTINUE
▸ Sometimes we want to exit a loop early
▸ Or we want to skip to the next iteration of the loop
▸ break
▸ Jump immediately out of the loop to the code that follows
▸ None of the loop conditions are checked, or update statement run (for loop)
▸ continue
▸ Jump immediately to the top of the loop
▸ Checks the condition (for, while) and runs the update statement (for loop)
TEXT
BREAK AND CONTINUE
▸ Examples:
▸ Games
▸ Searching in an array or list
▸ When an error occurs
48
break and continue• Break
– Ends the current loop [not if statement] immediately and continues execution after its last statement
• Continue – Begins the next iteration of the nearest
loop (performing the update statements if it is a for loop)
– Can usually be accomplished with some kind of if..else structure
– Can be useful when many nested if statements…
bool done = 0;while ( !done ) {cout << "Enter guess: " << endl;cin >> guess;if( guess < 0 )break;
}// ... Process guess
}
// Guess an int >= 0while( !done ) {cin >> guess;if(guess < 0){continue;
}// Can only be here if guess >= 0
}// Equivalent w/o using continuewhile( !done ) {cin >> guess;if(guess >= 0){// Process
}}
TEXT
BREAK AND CONTINUE
▸ Only apply to the loop they’re in, not all nested for or while loops
49
break and continue• Break and continue apply only to
the inner most loop (not all loops being nested)– Break ends the current (inner-most)
loop immediately – Continue starts next iteration of inner-
most loop immediately
• Consider problem of checking if a '!' exists anywhere in some lines of text– Use a while loop to iterate through
each line– Use a for loop to iterate through each
character on a particular line– Once we find first '!' we can stop
bool flag = false;while( more_lines == true ){// get line of text from userlength = get_line_length(...);
for(j=0; j < length; j++){if(text[j] == '!'){flag = true;break; // only quits the for loop
}}
}
bool flag = false;while( more_lines == true && ! flag ){// get line of text from userlength = get_line_length(...);
for(j=0; j < length; j++){if(text[j] == '!'){flag = true;break; // only quits the for loop
}}
}
TEXT
PRE-PROCESSOR DIRECTIVES
▸ C++ has what is known as a pre-processor
▸ Scans your code looking for lines that start with #
▸ #include literally “includes” the whole of another file in your source code
▸ We use to bring in elements of C++ standard library
▸ Later we’ll write our own “header” files and #include them too
▸ #define pattern_1 pattern_2
▸ Looks for all examples of the text in pattern_1 and replaces with pattern_2
▸ #define PI 3.141592 (replaces all occurrences of PI with 3.141592)
TEXT
GENERATING RANDOM NUMBERS
▸ Generating (pseudo) random numbers is very important for lots of applications in computer science
▸ We’ll need them for PA1
▸ #include <cstdlib>
▸ Gives us the function rand() which returns an integer between 0 and RAND_MAX (a constant also defined by <cstdlib>
▸ int r = rand();
▸ How to generate uniform (pseudo) random numbers between [0,1]?
▸ double r = ((double)rand())/RAND_MAX;
TEXT
PSEUDO-RANDOM
▸ Why do I keep saying pseudo random?
▸ Most random number generators in CS are pseudo random (PRNG)
▸ They generate long sequences of random-looking numbers
▸ Aren’t really random, sometimes (usually for us) this is OK
▸ “Seeding” the PRNG gives the offset into the sequence
▸ If you seed the same PRNG with the same seed, you’ll always get the same sequence
▸ Useful for testing
TEXT
SEEDING PRNG
▸ If you are testing, seed with 0, or whatever # you want
▸ When you want the PRNG to produce “random” results, seed with “time”
▸ Integer # of seconds since Jan. 1, 1970
▸ #include <ctime>
▸ Ex:
▸ srand(0);
▸ srand( time(0) );
▸ Only call srand() once at the beginning of your program. Otherwise you might get strange results.
TEXT
SRAND() AND RAND()
▸ Example:
▸ srand(time(0));
▸ int r1 = rand();
▸ int r2 = rand();
▸ Sequence of numbers in r1 and r2 will be different each time you run your program.
TEXT
IN CLASS EXERCISES
▸ randcalls
▸ seed
▸ seedtime
TEXT
ACKNOWLEDGEMENTS
▸ Yellow code samples courtesy Mark Redekopp
▸ All graphics from Wikimedia Commons unless otherwise noted