0% found this document useful (0 votes)
26 views

Unit2 ControlStructures

Control structures notes point presentation

Uploaded by

Ngulle Nanga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Unit2 ControlStructures

Control structures notes point presentation

Uploaded by

Ngulle Nanga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

1

CS 103 Lecture 3 Slides

Control Structures

Mark Redekopp
2

Announcements
• Lab 2 – Due Friday
3

Review
• Write a program to ask the user to enter two integers
representing hours then minutes. Output the
equivalent number of seconds.
• To get started…
– Go to http://bytes.usc.edu/cs103/in-class-exercises
• printseconds
– We've started the program for you…look at the
• General template for a program with the #includes, using
namespace std; and int main() function which returns 0
– We've declared variables where you can store the input
and computation results
– Now you add code to
• Get input from the user
• And compute the answer and place it in the 'sec' variable
4

If..else statements

MODULE 5: CONDITIONAL
STATEMENTS
5

Comparison Operators
• Control structures like if, while, and for require conditions to
determine what code should execute
• To perform comparison of variables, constants, or expressions
in C/C++ we can use the basic 6 comparison operators
Operator(s) Meaning Example
== Equality if(x == y)

!= Inequality if(x != 7)

< Less-than if(x < 0)

> Greater-than if(y > x)

<= Less-than OR equal to if(x <= -3)

>= Greater-than OR equal to if(y >= 2)


6

Logical AND, OR, NOT


• Often want to combine several conditions to make a decision
• Logical AND => x > 0 && y > 0
• Logical OR => x == 1 || x == 2
• Logical NOT => !(x < 0)
• Precedence (order of ops.) => ! then && then ||
– !cond1 || cond2 && !cond3
– ( ( !cond1 ) || (cond2 && ( !cond3 ) ) )

A B AND A B OR A NOT
False False False False False False False True
False True False False True True True False
True False False True False True
True True True True True True
7

Exercise
• Which of the following is NOT a condition to check if
the integer x is in the range [-1 to 5]
• x >= -1 && x <= 5
• -1 <= x <= 5
• !( x < -1 || x > 5)
• x > -2 && x < 6
8

bools, ints, and Conditions


• Loops & conditional statements require a condition to be
evaluated resulting in a true or false result.
• In C/C++…
– 0 means false / Non-Zero means true
– bool type available in C++ => ‘true’ and ‘false’ keywords can be used
but internally
• true = non-zero (usually 1) and
• false = 0
• Any place a condition would be used a bool or int type can be
used and will be interpreted as bool
int x = 100; bool done = false; int x=100, y=3, z=0;
if(x) while( ! done ) if( !x || (y && !z) )
{ x--; } { cin >> done; } { /* code */ }
• Example:
9

Conditions and DeMorgans


• Write a condition that eats a sandwich if it has
neither tomato nor lettuce
– if ( !tomato && !lettuce) { eat_sandwich(); }
– if ( !(tomato || lettuce) ) { eat_sandwich(); }

• DeMorgan's theorem says there is always two


ways to express a logic condition
– !a && !b  !(a || b)
– !a || !b  !(a && b)

• More details in EE 109 and CS 170


10

If..Else Flow Chart


if (condition1)
{
// executed if condition1 is true
True False }
condition else
{
// executed if condition1
// above is false
}

// following statements
If Block Else
Statements Block Statements

Following
statements
11

If…Else If…Else
• Use to execute only if (condition1)
{
certain portions of code // executed if condition1 is true
}
• else if is optional else if (condition2)
{
– Can have any number of // executed if condition2 is true
// but condition1 was false
else if statements }
• else is optional else if (condition3)
{
// executed if condition3 is true
• { … } indicate code // but condition1 and condition2
associated with the if, }
// were false

else if, else block else


{
optional
// executed if neither condition
if else if else if else // above is true
}
12

else if if (condition1)
{
// executed if condition1 is True
}
else if (condition2)
{
// executed if condition2 is True
True False
condition // but condition1 was False
}
1 else

These 2 are equivalent


{
True False // executed if neither condition
cond2
condition // above is True
}

if (condition1)
If Block Else
If BlockIf Else
Else {
Statements Block Statements // executed if condition1 is True
Statements Statements Statements
}
else
{
Following if (condition2){
statements // executed if condition2 is True
// but condition1 was False
}
else
Following {
// executed if neither condition
Statements // above is True
}
}
13

Single Statement Bodies


• The Rule: Place code for an if (x == 5)
y += 2;
if, else if, or else construct in else
curly braces { … } y -= 3;
• The Exception:
– An if or else construct with a if (x == 5)
single statement body does not y += 2;
require { … } else
if(x < 5)
– Another if counts as a single
y = 6;
statement else
• Prefer { … } even in single y = 0;
statement bodies so that
editing later does not
introduce bugs
14

PROBLEM SOLVING IDIOMS


15

Rule/Exception Idiom
• Name: Rule/Exception // Default action

• Description: Perform a default if( /* Exceptional Case */ )


{
action and then us an ‘if’ to // Code to apply to
// exceptional case
correct for exceptional cases }

• Structure: Default action code Structure


followed by if statement with
code to correct the exceptional bool primeMember = /* set somehow */;

case double shippingFee = 7.99;


if( primeMember == true )
• Example(s): {
shippingFee = 0;
– Shipping for "members" }

Example
16

Look-up Table Idiom


• Name: Look-up Table (Parallel cases) if( /* Condition 1 */ )
{
– A table can describe the mapping of input // Case 1 code
to output }
else if( /* Condition 2 */ )
• Description: Break input into {
// Case 2 code
mutually exclusive cases, taking some }
else if( /* Condition 3 */ )
action or producing some output in {
each case }
// Case 3 code

• Structure: Single level else { /* Default */


// Default code
'if..else if..else' statement }
Score Grade Look-up Table Structure
(input) (output)
if( weather == "hot" ) {
> 90 A clothing = "t-shirt";
Weather Dress
80-89 B }
Hot T-shirt else if( weather == "mild" ) {
70-79 C clothing = "long sleeves";
Mild Long Sleeves }
55-69 D else { /* Default */
Cold Sweater clothing = "sweater";
< 55 F }
17

Decision Tree (Subcase) Idiom


• Name: Decision Tree (Subcase) if( /* Condition 1 */ )
{
• Description: The result of one // Case 1 code

condition determines which if( /* Subcondition 1a */ ) {


// Subcase 1a code
condition (subcase) to check next }
else {
• Structure: Nested 'if' statements // Subcase 1b code
}

}
else if( /* Condition 2 */ )
Customer Service Call Menu {
// Case 2 code

Top-level Account Hours of if( /* Subcondition 2a */ ) {


Cases: Issues Operation // Subcase 2a code
}
}
Sub-Cases: Balance Cancel
18

Exercises
• Conditionals In-Class Exercises
– discount
– weekday
– nth
19

The Right Style


• Is there a difference
int x;
between the following cin >> x;
two code snippets
if( x >= 0 ) { cout << "Positive"; }
• Both are equivalent but if( x < 0 ) { cout << "Negative"; }
– Two if statements implies
both can execute
– An if..else implies a int x;
cin >> x;
mutually exclusive
relationship where only 1 if( x >= 0 ) { cout << "Positive"; }
can execute else { cout << "Negative"; }

• For mutually exclusive


cases, use if..else for
clarity sake
20

Find the bug


// What’s the problem below
• What's the problem with int x;
this code… cin >> x;
if (x = 1)
{ cout << "x is 1" << endl; }
else
• Common mistake is to { cout << "x is not 1" << endl; }
use assignment '=' rather
than equality
comparison '==' operator // What’s the problem below
int x;
• Assignment puts 1 into x cin >> x;
and then uses that value if (x = 1) // x == 1
of x as the "condition" { cout << "x is 1" << endl; }
else
– 1 = true so we will { cout << "x is not 1" << endl; }
always execute the if
portion
21

Switch (Study on own)


• Again used to execute only
switch(expr) // expr must eval to an int
certain blocks of code {
• Cases must be a constant case 0:
// code executed when expr == 0
• Best used to select an action break;
case 1:
when an expression could be 1 // code executed when expr == 1
of a set of constant values break;
case 2:
• { … } around entire set of cases case 3:
case 4:
and not individual case // code executed when expr is
• Computer will execute code // 2, 3, or 4
break;
until a break statement is default:
// code executed when no other
encountered // case is executed
– Allows multiple cases to be break;
combined }

• Default statement is like an else


statement
22

Switch (Study on own)


• What if a break is switch(expr) // expr must eval to an int
{
forgotten? case 0:
// code executed when expr == 0
– All code underneath will be break;
case 1:
executed until another // code executed when expr == 1
break is encountered // what if break was commented
// break;
case 2:
case 3:
case 4:
// code executed when expr is
// 3, 4 or 5
break;
default:
// code executed when no other
// case is executed
break;
}
23

? Operator
• A simple if..else statement can be expressed with the
? operator
– int x = (y > z) ? 2 : 1;
– Same as:
if(y > z) x = 2;
else x = 1;
• Syntax: (condition) ? expr_if_true : expr_if_false;
• Meaning: the expression will result/return
expr_if_true if condition evaluates to true or
expr_if_false if condition evaluates to false
24

Performing repetitive operations

MODULE 6: LOOPS (ITERATIVE


STATEMENTS)
25

Need for Repetition


#include <iostream>

• We often want to repeat a using namespace std;

int main()
task but do so in a concise {
cout << 1 << endl;
way cout << 2 << endl;
...
– Print out all numbers 1-100 cout << 100 << endl;
return 0;
– Keep taking turns until a }
game is over #include <iostream> Assume this performs
• Imagine the game of 'war'…it using namespace std; code to "take a turn"
and thenproduces a
never ends!! int main()
true/false result
indicating if the game
{
• We could try to achieve bool gameOver;
is over

gameOver = take_turn();
these without loops, but… if( ! gameOver ){
gameOver = take_turn();
if( ! gameOver ) {
...
{
}
}
26

4 Necessary Parts of a Loop


• Loops involve writing a task to be repeated
• Regardless of that task, there must be Initialization
4 parts to a make a loop work (e.g. i = 0)
• Initialization
– Initialization of the variable(s) that will Loop
control how many iterations (repetitions) Condition
the loop will executed (e.g. i < 1000)
• Condition
– Condition to decide whether to repeat the True
task or stop the loop Body

False
• Body (cout << i << endl;)
– Code to repeat for each iteration
Update Statement
• Update (e.g. i += 1)
– Modify the variable(s) related to the
condition Code after the loop
27

Type 1: while Loops


• A while loop is essentially a repeating 'if' statement
initialization 1
while (condition1) 2 5 8 Initialization
{ T T F (e.g. i = 0)
3 6
// Body: if condition1 is true
4 7 Loop
} // go to top, eval cond1 again Condition
9 (e.g. i < 1000)
// following statements
// only gets here when cond1 is false True
int i=0; Loop task

False
while (i < 1000) (cout << i << endl;)
{
cout << i << endl;
i++; Update Statement
} (e.g. i += 1)
// following statements
Code after the loop
While loop printing 0 to 999
28

while vs. do..while Loops


• while loops have two
// While:
variations: while and do..while while(condition)
{
• while // code to be repeated
// (should update condition)
– Cond is evaluated first }
– Body only executed if condition is
true (maybe 0 times)
// Do while:
• do..while do {
// code to be repeated
– Body is executed at least once // (should update condition)
– Cond is evaluated } while(condition);

– Body is repeated if cond is true


29

while Loop
// guessing game
• One way to think of a while bool guessedCorrect = false;
if( !guessedCorrect )
loop is as a repeating 'if' {
guessedCorrect = guessAgain();
statement }
// want to repeat if cond. check again
• When you describe a if( !guessedCorrect )
{
problem/solution you use guessedCorrect = guessAgain();
} // want to repeat if cond. check again
the words 'until some
condition is true' that is the An if-statement will only execute once
same as saying 'while some
// guessing game
condition is not true' bool guessedCorrect = false;
– "Until they guess correctly" is while( !guessedCorrect )
{
the same as "while they do guessedCorrect = guessAgain();
NOT guess correctly" }

A 'while' loop acts as a repeating 'if'


statement
30

Using Flow Charts to Find Loops

Do..While Loop
Accept Guess Draw out a flow chart of the
desired sequence and look
for the repetitive sequence
Correct
Here we check at the end
False to see if we should
repeat…perfect for a
Accept Guess
do..while loop

do
True Correct
{ accept_guess }
False while ( ! correct )
Accept Guess

Correct

False

Post-Loop
Code
31

Finding the ‘while’ Structure


Accept Guess Draw out a flow chart of the
desired sequence and look
for the repetitive sequence
Correct Accept Guess
Here we check at the end
False to see if we should
repeat…perfect for a
Accept Guess False Not

While loop
do..while loop
Correct
while loop
Correct
do True
True { accept_guess }
False while ( ! correct ) Accept Guess
Accept Guess But a while loop
checks at the
beginning of the
Correct loop, so we must Post-Loop
accept one guess Code
False
before starting:

accept_guess
Post-Loop while( ! correct )
Code { accept_guess }
32

Type 2: 'for' Loop


Condition: T T F
• 'for' loop 1 2 5 8
for( init; condition; update)
4 7

{
– performs initialization 3 6
// executed if condition is true
} // go to top, do update, eval cond. again
statement once
9 // following statements
– checks the condition // only gets here when cond. is false

each iteration before init


False
deciding to execute the condition
body or end the loop True
For Block
– performs the update Statements
statement after each Update
execution of the body Following
33

for Loop
for(init stmt; cond; update stmt)
{
• Initialization stmt executed first // body of loop
}
• Cond is evaluated next
• Body only executed if cond. is true // Outputs 0 1 2 3 4 (on separate lines)
for(i=0; i < 5; i++){
• Update stmt executed }
cout << i << endl;

• Cond is re-evaluated and execution // Outputs 0 5 10 15 … 95 (on sep. lines)


continues until it is false for(i=0; i < 20; i++){
cout << 5*i << " is a multiple of 5";
• Multiple statements can be in the cout << endl;
}
init and update statements // Same output as previous for loop
– Separate with commas for(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;
}
34

for vs. while Loop Notice we


// guessing game cannot predict
• 'while' Rule of thumb: Use bool guessedCorrect = false;
while( !guessedCorrect )
how many
times this will
when exact number of {
guessedCorrect = guessAgain();
run.

iterations is unknown when }

loop is started (i.e. condition int x;


Though we
don't know x we
cin >> x;
updating inside the loop for(i=0; i < x; i++){ can say the loop
cout << 5*i << " "; will run exactly
body) } x times.
cout << endl;
• 'for' Rule of thumb: Use
when number of iterations is for(init stmt; cond; update stmt)
{
known when loop is started // body of loop
}
(independent of loop body) // Equivalent while structure

• Both can be converted to


the other…try it on the right
35

LOOP IDIOMS & PRACTICE


36

Map Idiom
• Name: Map for(/* loop thru each input */)
{
• Description: Convert (map) // Get next input, x
// Produce next output, f(x)
each value in a collection to }
another value
Structure
• Structure: Use a loop to
Output the first n odd integers
process a series of input values Input: 0, 1, 2, ..., n-1
and convert to the desired Output: 1, 3, 5, , 2(n-1)+1
output values Given a threshold of 70, indicate if
– Usually with a n-to-n input- students have passed a quiz
output relationship Input: 78, 61, 85, 93, 54
Output: T, F, T, T, F
• Example(s):
– See examples on the right Take the absolute value of each input
Input: -18, -13, 36, 2, -21
Output: 18, 13, 36, 2, 21
37

Reduce Idiom
• Name: Reduce / Combine / // Declare reduction variable, r
// Set r to identity value
Aggregate
for(/* loop thru each input */)
• Description: Combine/reduce all {
elements of a collection to a // Get next input, x
// Update r using x
single value }
• Structure: Use a "reduction" Structure
variable and a loop to process a
series of input values, combining Average a series of 4 numbers
each of them to form a single (or Input: 2, 3, 1, 8
Average: 3.5
constant number of) output value double sum = 0;
in the reduction variable double x;
for(int i=0; i < 4; i++)
– An n-to-1 input-output relationship { cin >> x;
• Example(s): sum += x;
}
– See example on the right cout << sum / 4.0 << endl;
38

Selection Idiom
• Name: Selection // declare/initialize any state variables
// needed to track the desired result
• Description: Select a subset // loop through each instance
(possibly one or none) of for( /* each input, i */ ) {
// Check if input meets the property
elements from a collection if(property is true for i) {
// Update state (variables) as needed
based on a particular property }
}
• Structure: Loop through each // Output the state variables
element and check whether it Structure
meets the desired property. If
so, perform a map, reduce, or Count Positive Integers
other other update operation. Input: 2, -3, -1, 8
Output: 2
• Example(s):
– Count all positive integers inputs
39

Exercises
• In-class exercises:
– countodd
– liebnizapprox
– wallis
– revdigits
40

Loop Practice
• Write a for loop to compute the first 10 terms of
the Liebniz approximation of π/4:
• π/4 = 1/1 – 1/3 + 1/5 – 1/7 + 1/9 …
• Tip: write a table of the loop counter variable vs. desired
value and then derive the general formula
• In-class exercise:
– liebnizapprox
Counter (i) Desired Pattern Counter (i) Desired Pattern
0 +1/1 for(i=0;i<10;i++) 1 +1/1 for(i=1; i<=19; i+=2)
1 -1/3 Fraction: 3 -1/3 Fraction:
2 +1/5 5 +1/5
… … +/- => … … +/- =>
9 -1/19 19 -1/19
41

Loop Practice
• Write for loops to compute the first 10 terms of
the following approximations:
– ex: 1 + x + x2/2! + x3/3! + x4/4! …
• Assume 1 is the 1st term and assume functions
– fact(int n) // returns n!
– pow(double x, double n) // returns xn
– Wallis:
• π/2 = 2/1 * 2/3 * 4/3 * 4/5 * 6/5 * 6/7 * 8/7 …
• In-class Exercise
– wallisapprox
42

20-second Timeout: Chunking


• Right now you may feel overwhelmed with all the little details
(all the parts of a for loop, where do you need semicolons,
etc.)
• As you practice these
concepts they will
start to "chunk"
together where you can
just hear "for loop" and
will immediately know
the syntax and meaning
• Chunking occurs where
something more abstract
takes the place of many https://designbyben.wordpress.com/tag/chunking/

smaller pieces
43

On your own time, practice tracing the following loops

TRACING EXECUTION 1
44

Tracing Exercises (Individually)


• To understand a loop's execution int i;
make a table of relevant variable cout << "For 1: " << endl;
for(i=0; i < 5; i++){
values and show their values at cout << i << " ";
the time the condition is checked }
• If the condition is true perform cout << i+10 << endl;
the body code on your own (i.e.
perform specified actions), do
the update statement, & repeat
i (at condition check) Actions of body
0 "0 "
1 "1 "
2 "2 "
3 "3 "
4 "4 "
5 -
Done "0 1 2 3 4 15\n"
45

Tracing Exercises (for 2-4)


• Perform hand tracing on the following loops to find
what will be printed:

int i; int i, j=1; int i, j=1;

cout << "For 2: " << endl; cout << "For 3: " << endl; cout << "For 4: " << endl;
for(i=0; i < 5; i++){ for(i=0; i < 20; i+=j){ for(i=10; i > 0; i--){
cout << 2*i+1 << " "; cout << i << " "; cout << i+j << " ";
} j++; i = i/2; j = j*2;
cout << endl; } }
cout << endl; cout << endl;

Answers at end of slide packet


46

Tracing Exercises (for 5-6)


• Perform hand tracing on the following loops to find what will
be printed:

int i = 3; double T = 8;
char c = 'a';
cout << "For 6: " << endl;
cout << "For 5: " << endl; for(i=0; i <= T; i++){
for( ; c <= 'j'; c+=i ){ // Force rounding to 3 decimal places
cout << c << " "; cout << fixed << setprecision(3);
} // Now print the number
cout << endl; cout << sin(2*M_PI*i/T) << endl;
}

Answers at end of slide packet


47

Tracing Exercises (while 1-2)


• Perform hand tracing on the following loops to find
what will be printed:

int i=15, j=4; int i=1; j=1;


cout << "While loop 1: " << endl; cout << "While loop 2: " << endl;
while( i > 5 && j >= 1){ while( i || j ){
cout << i << " " << j << endl; if(i && j){
i = i-j; j = !j;
j--; }
} else if( !j ){
i = !i;
}
cout << i << " " << j << endl;
}

Answers at end of slide packet


48

Tracing Exercises (while 3)


• Perform hand tracing cout << "While loop 3: " << endl;
on the following loops bool found = false;
int x = 7;
to find what will be while( !found ){
if( (x%4 == 3) &&
printed: (x%3 == 2) &&
(x%2 == 1) )
{
found = true;
}
else {
x++;
}
}
cout << "Found x = " << x << endl;

Answers at end of slide packet


49

LOOP ODDS & ENDS


50

break statement
• break
– Ends the current loop [not if statement] immediately and continues
execution after its last statement
• Consider two alternatives for stopping a loop if an
invalid (negative) guess is entered
bool done = false; bool done = false;
while ( done == false ) { while ( done == false ) {
cout << "Enter guess: " << endl; cout << "Enter guess: " << endl;
cin >> guess; cin >> guess;
if( guess < 0 ) if( guess < 0 )
done = true; break;
} }
else { // Process guess
// Process guess // If guess < 0 we would skip this
} }
}
51

continue statement
• continue
– Ends the current loop [not if statement] immediately and
continues execution after its last statement
• Consider two alternatives for repeating a loop to get a
new guess if an invalid (negative) guess is entered
– Often continue can be eliminated by changing the if
condition
bool done = false; bool done = false;
while ( done == false ) { while( done == false) {
cout << "Enter guess: " << endl; cout << "Enter guess: " << endl;
cin >> guess; cin >> guess;
if( guess >= 0 ) { if(guess < 0){
// Process Guess continue;
} }
} // Process guess (only here if guess>=0)
}
52

Single Statement Bodies


• An if, while, or for construct if (x == 5)
y += 2;
with a single statement body else
y -= 3;
does not require { … }
• Another if, while, or for for(i = 0; i < 5; i++)
counts as a single statement sum += i;

while(sum > 0)
sum = sum/2;

for(i = 1 ; i <= 5; i++)


if(i % 2 == 0)
j++;
53

The Loops That Keep On Giving


• There's a problem with the loops 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> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ int val; {
bool again = true; int i=0;
while(again = true){ while( i < 10 ) {
cout << "Enter an int or -1 to quit"; cout << i << endl;
cin >> val; i + 1;
if( val == -1 ) { }
again = false; return 0;
} }
}
return 0;
}
http://blog.codinghorror.com/rubber-duck-problem-solving/
54

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> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ int val; {
bool again = true; int i=0;
while(again == true){ while( i < 10 ) {
cout << "Enter an int or -1to quit"; cout << i << endl;
cin >> val; i = i + 1;
if( val == -1 ) { }
again = false; return 0;
} }
}
return 0;
}
http://blog.codinghorror.com/rubber-duck-problem-solving/
55

NESTED LOOPS
56

What Can Go Inside?


• What kind of code can we put in the body of a loop?
• ANYTHING…even other loops
while (condition) for( init; condition; update)
{ {
// What can go here? // What can go here?
} }

False init
condition False
condition
True What code can we put True
while Block in the body of a For Block
loop?
Statements Statements
Following Update
statements
Following
57

Nested Loop Sequencing


• Key Idea: The inner loop runs in its entirety for each
iteration of the outer loop

Cond1: T T F False
cond1
while (cond1) { 1 9 15

// code1 2 10 True
Cond2: T T F
while(cond2) { 3 5 7 11 13 code1
Cond2: T F // code 2 12
4 6 False
}
// code3 8 14 cond2
} True
16 code2
code3
Following
statements
58

Nested Loops Example 1


• When you write loops int main()
{
consider what the body int secret, guess;
char again = 'y';
of each loop means in // outer loop
while(again == 'y')
an abstract sense { // Choose secret num. 0-19
secret = rand() % 20;
– The body of the outer guess = -1;
// inner loop
loop represents 1 game while(guess != secret)

1 game
(and we repeat that {

1 turn
cout << "Enter guess: ";
over and over) cin >> guess;
}
– The body of the inner cout << "Win!" << endl;
cout << "Play again (y/n): ";
loop represents 1 turn cin >> again;
(and we repeat turn }
return 0;
after turn) }
59

Nested Loops
• Inner loops execute fully (go through every iteration before the
next iteration of the outer loop starts)

#include <iostream>
using namespace std;

int main()
{
for(int i=0; i < 2; i++){ Output:
for(int j=0; j < 3; j++){

cout << i << " " << j << endl;


}
}
return 0;
}
60

Nested Loops
• Write a program using nested
#include <iostream>
loops to print a multiplication
table of 1..12 using namespace std;

• Tip: Decide what abstract int main()


{
"thing" your iterating through for(int r=1; r <= 12; r++){
for(int c=1; c <= 12; c++){
and read the for loop as cout << r*c;
}
"for each thing" … }
– For each row… return 0;
}
• For each column…
print the product
This code will print some not so
1 2 3 nice output:
1 1 2 3
___________________________
2 2 4 6
3 3 6 9
61

Nested Loops
• Tip: Decide what abstract "thing"
#include <iostream>
your iterating through and read
the for loop as "for each thing" … using namespace std;

– For each row … int main()


{
• For each column… for(int r=1; r <= 12; r++){
print the product followed by a space for(int c=1; c <= 12; c++){
• Print a newline cout << " " << r*c;
}
cout << endl;
}
return 0;
}

This code will still print some not


1 2 3 so nice output:
1 1 2 3
1 2 3 4 5 6 7 8 9 10 11 12
2 2 4 6
2 4 6 8 10 12 14 16 18 20 22 24
3 3 6 9
62

Nested Loops
• Use the setw I/O manipulator
#include <iostream>
to beautify the output #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 3
1 1 2 3
2 2 4 6
3 3 6 9
63

break and continue (Nested Loops)


bool flag = false;
• Break and continue apply only to while( more_lines == true ){
// get line of text from user
the inner most loop (not all loops length = get_line_length(...);
being nested)
for(j=0; j < length; j++){
– Break ends the current (inner-most) if(text[j] == '!'){
loop immediately flag = true;
– Continue starts next iteration of inner- break; // only quits the for loop
most loop immediately }
}
• Consider problem of checking if a }
'!' exists anywhere in some lines of bool flag = false;
text while( more_lines == true && ! flag ){
– Use a while loop to iterate through // get line of text from user
length = get_line_length(...);
each line
– Use a for loop to iterate through each for(j=0; j < length; j++){
character on a particular line if(text[j] == '!'){
– Once we find first '!' we can stop flag = true;
break; // only quits the for loop
}
}
}
64

Nested Loop Practice


• In class exercises: checkerboard and flag
• In class exercise: 5PerLineA
– Try to print out the integers from 100 to 200, five per line,
as in:
100 101 102 103 104
105 106 107 108 109
...
195 196 197 198 199
200
• In class exercise: 5PerLineB and 5PerLineC each have
an error. W ee what they print and determine the
error.
65

MODULE 7: C LIBRARIES & RAND()


66

Preprocessor & Directives


• Somewhat unique to C/C++
• Compiler will scan through C code looking for directives (e.g.
#include, #define, anything else that starts with '#' )
• Performs textual changes, substitutions, insertions, etc.
• #include <filename> or #include "filename"
– Inserts the entire contents of "filename" into the given C text file
• #define find_pattern replace_pattern
– Replaces any occurrence of find_pattern with replace_pattern
– #define PI 3.14159
Now in your code:
x = PI;
is replaced by the preprocessor with
x = 3.14159;
67

#include Directive
• Common usage: To include “header files” that allow us to
access functions defined in a separate file or library
• For pure C compilers, we include a C header file with its
filename: #include <stdlib.h>
• For C++ compilers, we include a C header file without the .h
extension and prepend a ‘c’: #include <cstdlib>
C Description C++ Description
stdio.h C Input/Output/File access (printf, iostream I/O and File streams (cin, cout, cerr)
cstdio fopen, snprintf, etc.)

stdlib.h rand(), Memory allocation, etc. fstream File I/O (ifstream, ofstream)
cstdlib
string.h C-string library functions that operate string C++ string class that defines the ‘string’
cstring on character arrays object

math.h Math functions: sin(), pow(), etc. vector Array-like container class
cmath
68

rand() and RAND_MAX


• (Pseudo)random number generation in C is accomplished with
the rand() function declared/prototyped in cstdlib
• rand() returns an integer between 0 and RAND_MAX
– RAND_MAX is an integer constant defined in <cstdlib>
• How could you generate a flip of a coin [i.e. 0 or 1 w/ equal prob.]?
int r;
r = rand();
if(r < RAND_MAX/2){ cout << "Heads"; }
• How could you generate a decimal with uniform probability of being
between [0,1]
double r;
r = staic_cast<double>(rand()) / RAND_MAX;
69

Seeding Random # Generator


• Re-running a program that calls rand() will generate the same sequence of
random numbers (i.e. each run will be exactly the same)
• If we want each execution of the program to be different then we need to
seed the RNG with a different value
• srand(int seed) is a function in <cstdlib> to seed the RNG with the value of
seed
– Unless seed changes from execution to execution, we’ll still have the same
problem
• Solution: Seed it with the day and time [returned by the time() function
defined in ctime]
– srand( time(0) ); // only do this once at the start of the program

– int r = rand(); // now call rand() as many times as you want


– int r2 = rand(); // another random number
– // sequence of random #’s will be different for each execution of program
Only call srand() ONCE at the start of the program, not each Approximate rand() function:
time you want to call rand()!!! val = ((val * 1103515245) + 12345) % RAND_MAX;
70

SOLUTIONS
71

Loop Practice
• Write a for loop to compute the first 10 terms of
the Liebniz approximation of π/4:
• π/4 = 1/1 – 1/3 + 1/5 – 1/7 + 1/9 …
• Tip: write a table of the loop counter variable vs. desired
value and then derive the general formula

Counter (i) Desired Pattern Counter (i) Desired Pattern


0 +1/1 for(i=0; i <10; i++) 1 +1/1 for(i=1; i <=19; i+=2)
1 -1/3 Fraction: 3 -1/3 Fraction:
1/(2*i+1) 1/i
2 +1/5 5 +1/5
… … +/- => … … +/- =>
9 -1/19 pow(-1,i) 19 -1/19 if(i%4==3)
if(i is odd) neg.
neg.
72

Tracing Answers
For 1: While loop 1:
0 1 2 3 4 15 15 4
11 3
For 2: 8 2
1 3 5 7 9 6 1

For 3: While loop 2:


0 2 5 9 14 1 0
0 0
For 4:
11 6 5 While loop 3:
Found x = 11
For 5:
a d g j

For 6:
0.000
0.707
1.000
0.707
0.000
-0.707
-1.000
-0.707
-0.000

You might also like