1 Unit 7 'while' Loops
2 Control Structures • We need ways of making decisions in our program – To repeat code until we want it to stop – To only execute certain code if a condition is true – To execute one segment of code or another • Language constructs that allow us to make decisions are referred to as control structures • The common ones are: – if statements – switch statements – while loops – for loops
3 Loops • Loops are structures of code that may be repeated some number of times • Examples: – Sum each student's grades (for all students in the class) – Search through a sequence of numbers for a particular value – Attend lecture • We need some condition to tell us when to stop looping, otherwise we'll repeat our code forever and never stop (a.k.a. an infinite loop) • Several kinds of loops: 'while', 'do..while', and 'for' – We will focus on 'while' and 'do..while' in this unit
4 Why We Need Loops (1) #include <iostream> using namespace std; • Suppose we are writing int main() { a program for a simple int guess; int secretNum = /* some code */ cin >> guess; turn-based guessing if(guess != secretNum) { /* What should we do here? */ game where the user must guess a secret } else { cout << "You got it!" << endl; number } return 0; • If they guess incorrectly } what should we do?
5 Why We Need Loops (2) #include <iostream> using namespace std; • What if they guess int main() { wrong a second time? int guess; int secretNum = /* some code */ cin >> guess; What should we do? if(guess != secretNum) { cin >> guess; if(guess != secretNum) { /* What should we do here? */ } else { cout << "You got it!" << endl; } } else { cout << "You got it!" << endl; } return 0; }
6 Why We Need Loops (2) #include <iostream> using namespace std; • We can never write int main() { enough if statements int guess; int secretNum = /* some code */ cin >> guess; because someone might if(guess != secretNum) { cin >> guess; always use one more if(guess != secretNum) { cin >> guess; turn than we have if if(guess != secretNum) { /* What should we do here? */ } statements else { cout << "You got it!"<< endl; • But we see there is a } } else { repetitive structure in cout << "You got it!" << endl; } this code } else { • Let's use a loop cout << "You got it!" << endl; }
7 while Loops • A while loop is essentially a repeating 'if' statement if ( condition ) while ( condition ) { { // executed if condition1 is true // executed if condition1 is true } } // go to top, eval cond1 again // following statements // following statements // only gets here when cond1 is false False False condition condition True True If Block while Block Statements Statements Following Following statements statements
8 while Loops • A while loop is essentially a repeating 'if' statement Condition: T T F while ( condition ) 3 5 1 { // executed if condition1 is true 2 4 } // go to top, eval cond1 again 6 // following statements // only gets here when cond1 is false False condition True while Block Statements Following statements
9 When Do I Use a While Loop (1) • When you don't know #include <iostream> using namespace std; int main() in advance how many { int guess; times something int secretNum = /* some code */ cin >> guess; should repeat? while(guess != secretNum) { cout << "Enter guess: " << endl; cin >> guess; – How many guesses will } cout << "You got it!" << endl; the user need before return 0; } they get it right?
10 When Do I Use a While Loop (2) • Whenever you see or #include <iostream> using namespace std; int main() use the word 'until' in { int guess; a description int secretNum = /* some code */ cin >> guess; • Important Tip: while(guess != secretNum) { cout << "Enter guess: " << endl; cin >> guess; – "until" = "while not" } cout << "You got it!" << endl; – Saying "keep guessing return 0; } until you are correct" is the same as "keep guessing while you are not correct"
11 What Goes In an while Block • What do we put in an #include <iostream> using namespace std; int main() while loop? { int guess; • ANYTHING! int secretNum = /* some code */ cin >> guess; while(guess != secretNum) { – Expressions & variable cout << "Enter guess: " << endl; cin >> guess; assignment } cout << "You got it!" << endl; – Function calls return 0; } – Even other if..else statements
12 What Goes In an while Condition • What do we put in a int main() { while condition? int x, y, val; bool done; • ANYTHING. // Uses Boolean result of comparison while( x > 0 ) { /* code */ } – The compiler will // Uses value of bool variable. interpret what is in the // Executes if done == false. while( !done ) { /* code */ } parentheses as a // Interprets number as a bool Boolean // Executes if val is non-zero while( val ) { /* code */ } • 0 = false // Interprets return value as bool • Non-0 = true // Executes if the min is non-zero while( min(x,y) ) { /* code */ } return 0; }
13 Hand Tracing (1) int main() { • Trace through the code int x, y; cin >> x; and show all changes to x while( (x % 2) == 0){ x = x/2; and y for: } – x = 24 cin >> y; while(y > 0){ – y = 18 if( y >= 10 ){ y -= 5; } else if( y >= 5 ){ y -= 3; } else { y -= 1; } } return 0; }
14 Hand Tracing (2) int main() { • Trace through the code int x, y; cin >> x; and show all changes to x while( (x % 2) == 0){ x = x/2; and y for: } – x = 27 cin >> y; while(y > 0){ – y = 6 if( y >= 10 ){ y -= 5; } else if( y >= 5 ){ y -= 3; } else { y -= 1; } } return 0; }
15 Exercises 1 • cpp/while/whilen • cpp/while/sum50 • cpp/while/blastoff
16 do..while Loops (1) • while loops have a sibling int main() known as do..while loops { int x, y, val; • do..while loops bool quit; // a while loop – Start with keyword do while( x < val ) { – Followed by the body of code /* body of code */ } to be executed repeatedly in brackets { } // a do..while loop do – Ends with while condition { /* body of code */ and semicolon ( ; ) } while( x < val ); • do..while loops will execute return 0; } the body at least once
17 do..while Loops (2) • do..while loops check the condition after executing at least once and repeat if the condition is true do while ( condition ) { { // executed at least once // executed if condition1 is true } while ( condition );// go to 'do' (top) } // go to top, eval cond1 again //if cond1 evals to true // following statements // following statements // only gets here when cond1 is false // only gets here when cond1 is false False while Block condition Statements True True condition while Block Statements False Following Following statements statements
18 do..while Loops (3) • do..while loops check the condition after executing at least once and repeat if the condition is true do { 3 5 1 // executed at least once 2 4 6 } while ( condition );// go to 'do' (top) Condition: T T F //if cond1 evals to true // following statements 7 // only gets here when cond1 is false while Block Statements True condition False Following statements
19 When Should I Use do..while • We generally prefer while loops • We can use do..while loops when we know we want to execute the code at least one time (and then check at the end) • Even then… – See next slide
20 Converting do..while to while Loops cin >> guess; do while (guess != secretnum) { { cin >> guess; cin >> guess; } while (guess != secretnum); } // go to top, eval cond1 again cout << "You got it!" << endl; cout << "You got it!" << endl; We can duplicate the body of the loop We need to get one guess at least once before we start the loop. and then determine if we should repeat. This seems a natural fit for the do..while structure but we can easily guess = secretnum + 1; while (guess != secretnum) mimic this behavior with a normal { while loop. cin >> guess; } // go to top, eval cond1 again cout << "You got it!" << endl; We can set our variables to ensure the while condition is true the first time.
21 Exercises 2 • cpp/while/dowhilen • cpp/while/goldilocks
22 Common Loop Mistakes int i=0, n=10; • Failing to update the while (i < n) { variables that affect the cout << "Iteration " << i << endl; // Oops forgot to change i condition } cout << "Done" << endl; • Assignment rather than int i=0, n=5; equality check while (i = n) // oops, meant i==n { • Off by one error cin >> i; } • Often leads to infinite cout << "Done" << endl; loops int i=0; // want to print "Hi" 5 times – When you run your while (i <= 5) // oops, meant i < n { program it will not stop cout << "Hi" << endl; i++; – Use Ctrl+c to force quit it }
Recommend
More recommend