unit 7a
play

Unit 7a 'while' and 'for' Loop Syntax and Semantics 2 Control - PowerPoint PPT Presentation

1 Unit 7a 'while' and 'for' Loop Syntax and Semantics 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


  1. 1 Unit 7a 'while' and 'for' Loop Syntax and Semantics

  2. 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. 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'

  4. 4 Generalizing and repeating code MOTIVATION FOR LOOPS

  5. 5 Motivation for Loops #include <iostream> using namespace std; • Take a simple task such int main() { cout << 1 << endl; as outputting the first cout << 2 << endl; cout << 3 << endl; 1000 positive integers // hundreds more cout statements – We could write 1000 cout << 999 << endl; cout << 1000 << endl; cout statements return 0; } – Yikes! We could do it but it would be painful! #include <iostream> using namespace std; int main() • Or we could use a loop { for(int i=1; i <= 1000; i+=1 ) { cout << i << endl; } return 0; }

  6. 6 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?

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

  8. 8 Why We Need Loops (3) #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; }

  9. 9 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 = 1) • Initialization Loop – Initialization of the variable(s) that will 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 • (cout << i << endl;) Body – 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

  10. 10 Types of Loops • There are 2 (and a half) kinds of loops • for loops and while ( do..while ) loops There is a variant of the while loop which is the do..while loop which we'll cover later. int i; int i = 1; 4 parts: for ( i = 1; i <= 1000; i++ ) while ( i <= 1000 ) • Initialization { { • cout << i << endl; // repetitive task Condition } cout << i << endl; • Body // following statements i++; // update • Update } // following statements There is a variant of the while loop which is the do..while loop which we'll cover later.

  11. 11 Type 1: while Loops • A while loop is essentially a repeating 'if' statement // initialization // initialization if (condition) while ( condition ) { { // executed if condition1 is true // executed if condition1 is true } // update statement // following statements } // go to top, eval cond1 again // following statements Initialization Initialization False False condition condition True True If Block while Block Statements Statements Update Statement Following Following statements statements

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

  13. 13 Type 1: Applying the 4 Parts • Examine the guessing game code #include <iostream> using namespace std; • When using a loop there are int main() { almost always FOUR parts: int guess; • Initialization int secretNum = /* some code */ – 1 or more variables that are part of cin >> guess; while(guess != secretNum) the loop { cout << "Wrong, guess again: " << endl; • Body cin >> guess; } • Condition cout << "You got it!" << endl; – Condition for continuing return 0; } • Update: – 1 or more variables involved in the Always make sure you have the 4 parts condition (without the update, the (it's easy to forget initialization and/or update) condition could be TRUE forever leading to an "infinite loop")

  14. 14 What Goes In a Loop Body • What do we put in a #include <iostream> using namespace std; int main() while or for loop { int guess; body? int secretNum = /* some code */ • ANYTHING! cin >> guess; while(guess != secretNum) { – Expressions & variable cout << "Enter guess: " << endl; cin >> guess; assignment } – Function calls cout << "You got it!" << endl; return 0; } – if..else statements – Even other loops!

  15. 15 Hand Tracing (1) int main() { • Ensure you understand int x, y; cin >> x; the meaning (semantics) while( (x % 2) == 0){ x = x/2; of a while loop by tracing } through the code to the cin >> y; while(y > 0){ right if( y >= 10 ){ y -= 5; • Show all changes to x and } else if( y >= 5 ){ y for: y -= 3; } – x = 24 else { y -= 1; – y = 18 } } return 0; }

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

  17. 17 Type 2: for Loops • 'for' loops have the same ability as a 'while' loop but makes the 4 parts of a loop EXPLICIT // initialization for( init ; condition ; update ) while ( condition ) { { // executed if condition is true // executed if condition is true } // go to top, do update, eval cond. again // Update statement } // following statements // following statements init init condition condition False False True True while Block For Block Update Statement Example Statements for( int i=1; i < 1000; i++) Following { Update cout << i << endl; statements Following }

  18. 18 Type 2: 'for' Loop Sequencing Condition: T T F • 'for' loop 1 2 5 8 4 7 for( init; condition; update ) { – performs initialization 3 6 // executed if condition is true } // go to top, do update, eval cond. again statement once // following statements 9 – 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

  19. 19 Some Examples #include <iostream> #include <iostream> using namespace std; using namespace std; int main() int main() { { int i; int i; for(i=0; i < 5; i++) for(i=8; i > 0; i=i/2 ) { { cout << i << endl; cout << i << endl; } } return 0; return 0; } } Program Output: Program Output: 0 8 1 4 2 2 3 1 4 The initial value, condition, and update statement can be any valid expression!

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend