cs103l fall 2019 unit 2: control structures. if… else,...

49
UNIT 2: CONTROL STRUCTURES. IF… ELSE, FOR, WHILE CS103L FALL 2019

Upload: others

Post on 24-Jun-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

UNIT 2: CONTROL STRUCTURES. IF…ELSE, FOR, WHILE

CS103L FALL 2019

Page 2: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

LEARNING OBJECTIVES

▸ Understand control flow statements:

▸ if, else-if, else

▸ while, do-while

▸ for

Page 3: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 4: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 5: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 6: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 7: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

LOGICAL OPERATOR PRACTICE

▸ x=100;y=-3;z=0

▸ !x || y && !z

▸ With parens: ((!x) || ( y && (!z)))

Page 8: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 9: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

IF STATEMENTS

▸ Controlling the flow of your code

Page 10: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 11: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

}

Page 12: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 13: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

IN CLASS EXERCISES

▸ discount

▸ weekday

▸ N-th

Page 14: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 15: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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”; }

Page 16: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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; }

Page 17: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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; }

Page 18: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

= VS == FIXED

▸ Fixed code

int x; cin >> x;

if( x == 1) { cout << “x is 1!” << endl; } else { cout << “x is not 1.” << endl; }

Page 19: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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; }

Page 20: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

LOOPS

▸ Doing something more than once

Page 21: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 22: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

LOOP TYPE #1: WHILE LOOP

▸ While loop

▸ Do something while a condition is true

▸ Two forms:

▸ while(condition){ //something }

▸ do { //something } while(condition)

Page 23: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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);

Page 24: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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);

Page 25: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 26: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

IN CLASS EXERCISES

▸ countodd

Page 27: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 28: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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;

}

Page 29: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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;

}

Page 30: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 31: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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 +

… … …

Page 32: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 33: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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/

Page 34: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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/

Page 35: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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;

}

Page 36: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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++;

Page 37: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 38: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 39: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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:

Page 40: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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…

Page 41: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 42: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

Page 43: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

IN-CLASS EXERCISES

▸ 5-per line (A, B, C)

Page 44: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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)

Page 45: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

}}

Page 46: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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

}}

}

Page 47: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

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)

Page 48: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

IN CLASS EXERCISES

▸ randcalls

▸ seed

▸ seedtime

Page 49: CS103L FALL 2019 UNIT 2: CONTROL STRUCTURES. IF… ELSE, …bytes.usc.edu/files/cs103/slides_fa19/Unit2.pdf · DO-WHILE LOOP Body is executed Then condition is checked, if true, body

TEXT

ACKNOWLEDGEMENTS

▸ Yellow code samples courtesy Mark Redekopp

▸ All graphics from Wikimedia Commons unless otherwise noted