Chapter 5 Loops - PowerPoint PPT Presentation

wendi
chapter 5 loops n.
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 5 Loops PowerPoint Presentation
Download Presentation
Chapter 5 Loops

play fullscreen
1 / 37
Download Presentation
235 Views
Download Presentation

Chapter 5 Loops

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Chapter 5 Loops §5.1 The “while” Loop §5.2 The “do-while” Loop §5.3 The “for” Loop §5.4 Nested loop §5.5 “break” and “continue”

  2. Motivations Question: please write a program to print a string (e.g., "Welcome to C++!") ten times. -- Easy! --How about 1000 times? cout << "Welcome to C++!" << endl; cout << "Welcome to C++!" << endl; cout << "Welcome to C++!" << endl; cout << "Welcome to C++!" << endl; cout << "Welcome to C++!" << endl;

  3. §4.1 The “while” Loop int count = 0; while (count < 100) { cout << "Welcome to C++!\n"; count++; } while (loop-continuation-condition) { // loop-body; Statement(s); }

  4. The loop exits. Execute the next statement. (count < 2): false Print “Welcome to C++” Increase count by 1 (count < 2): true Initialize count Print “Welcome to C++” (count < 2) : true Increase count by 1 Trace while Loop int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } 0 1 2 count Welcome to C++! Welcome to C++!

  5. Example: Multiple Subtraction Quiz The Math subtraction tutor program in Listing 3.4, SubtractionTutor.cpp, generates just one question for each run. Listing 5.4 gives a program that generates ten questions and reports the number of the correct answers after a student answers all ten questions. The program also displays the time spent on the test and lists all the questions, as shown in sample output. SubtractionQuizLoop


  6. Example: Repeat Subtraction Quiz RepeatSubstractionQuiz In the previous subtraction quiz Listing 3.4 , each question can be answered only once. Listing 5.1 gives a program that let the user enter a new answer if the previous answer is incorrect, and terminate until the correct answer is entered.

  7. Unknown # of Loop Executions • How to terminate a loop, if • The number of loop executions is not predetermined? • Two methods • User confirmation, or • Sentinel value

  8. Controlling a Loop with User Confirmation char continueLoop = 'Y'; while (continueLoop == 'Y') { // Execute body once // Prompt the user for confirmation cout << "Enter Y to continue and N to quit: "; cin >> continueLoop; }

  9. Ending a Loop with a Sentinel Value SentinelValue A program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.

  10. Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations. • double data = pow(sqrt(2.0), 2) - 2; • while (data != 0){ • cout << “Data is not zero: "<<data<<endl; • data = pow(sqrt(data), 2) - data; • }

  11. Example: Reading Data from a File Listing 4.10 reads three numbers from the data file. To read many numbers, you need a loop. What to do if you don’t know the number of numbers in the file? -- terminate at the end of file! -- How? Use the eof() function. Listing 5.6 revises Listing 5.10 to read all numbers from the file score.txt. ReadAllData

  12. Check Point int count = 0; while (count<100) { //Point A cout<< "Welcome to C++!\n"; count++; //Point B } //Point C Please analyze the following code. Is count<100 always true/false at Point A, Point B, and Point C?

  13. §5.2 The “do-while” Loop “while” “do-while” do{ // Loop body; Statement(s); } while (loop-continuation-condition);

  14. Example TestDoWhile • Listing 5.7: a program that reads and calculates the sum of an unspecified number of integers. • The input 0 signifies the end of the input.

  15. Check Point int i = 1; while (i<4){ if(i%2 == 0) cout<<i<<endl; i++; } int i = 1; while (i>4){ if(i%2 == 0) cout<<i<<endl; i++; } int i = 1; do{ if(i%2 == 0) cout<<i<<endl; i++; }while (i<4); int i = 1; do{ if(i%2 == 0) cout<<i<<endl; i++; }while (i>4); How many times is the following loop body repeated? What’s the printout?

  16. §5.3 The “for” Loop int i; for (i = 0; i < 100; i++) { cout << "Welcome !\n"; } cout<<“Welcome!\n”; for (initial-action; loop-continuation-condition; action-after-each-iteration) { // loop body; Statement(s); }

  17. (i < 2): true i: 0 Print Welcome to C++! Execute adjustment statement: i : 1 (i < 2): true i: 1 Print “Welcome to C++!” (i < 2): false i: 2 Execute adjustment statement i now is 2 Execute initializer: i: 0 Declare i Exit the loop. Execute the next statement after the loop Trace for Loop int i; for (i = 0; i < 2; i++) { cout << "Welcome to C++!"; }

  18. Note sum=0; i=1; for (; i<=100;){ sum += i; i++;} sum=0; i=1; for ( ; ; ){ if (i>100) break; sum += i; i++;} 1) sum=0; i=1; for (; i<=100; i++) sum += i; 2) sum=0;for (i=1; ; i++){ if (i>100) break; sum += i;} 3) sum=0;for (i=1; i<=100; ){ sum += i; i++;} -- If the loop-continuation-condition in a for loop is omitted, it is implicitly true. -- It may result in infinite loop. All the three control expressions in “for” loop can be omitted But the semicolons can not be omitted

  19. Note • for (int i = 0, j = 0; (i + j < 10); i++, j++) { • // Do something • } “,” operator • The initial-action and action-after-each-iteration can be a list of comma-separated expressions • rarely used in practice

  20. The Operator “ , ” int main(){ int x,y; x=50; for (int i = 0,j = 0;i + j < 10;i++,j++) { y=(x=x-5,x/5); cout<<x<<" "<<y<<endl; } } • “ , ”: • Concatenate expressions • The result value: the value of the rightmost expression • Precedence: the lowest (lower than “=“)

  21. Example: Using for Loops TestSum Problem: Write a program that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.

  22. Floating-point Numbers in Relational Expressions int main(){ // Initialize sum double sum = 0; double prei=0; double i; // Add 0.01, 0.02, ..., 0.99, 1 to sum for (i = 0.01; i <= 1.0; i = i + 0.01){ sum += i; prei=i; } // Display result cout << "The sum is " << sum<<endl; cout<<setprecision(10)<<"i is increased by "<<i-prei<<endl; cout<<"The final i is "<<i<<", and i-1.0 is " <<(i-1.0)<<endl; return 0; } int main() { // Initialize sum double sum = 0; double i=0; // Add 0.01, 0.02, ..., 0.99, 1 to sum for (i = 0.01; i <= 1.0; i = i + 0.01) sum += i; // Display result cout << "The sum is " << sum; return 0; } The sum is 49.5 i is increased by 0.01 The final i is 1, and i-1.0 is 6.661338148e-016 The sum is 50.5 i is increased by 0.009999999776 The final i is 1.009999977, and i-1.0 is 0.009999977425 for (i = 0.01f; i <= 1.0f; i = i + 0.01f){

  23. Which Loop to Use? • while, do-while, and for, are expressively equivalent and mutually conversable.

  24. Which Loop to Use? • “for”: • if the number of repetitions is known. • “while”: • if the number of repetitions is unknown • “do-while”: • to replace a while loop if the loop body has to be executed before testing the continuation condition.

  25. Check Point int i =1; int sum =0; while (sum<10000) { sum +=i; i++; } Convert the following while loop into a for loop.

  26. §5.4 Nested loop Loop with one outer loop and one or more inner loops

  27. Nested Loops TestMultiplicationTable A program that uses nested for loops to print a multiplication table.

  28. Case Study: Monte Carlo Simulation The Monte Carlo simulation refers to a technique that uses random numbers and probability to solve problems. This method has a wide range of applications in computational mathematics, physics, chemistry, and finance. For example: circleArea / squareArea =  / 4.  ≈ 4 * numberOfHits / 1000000. MonteCarloSimulation

  29. Case Study: Converting Decimals to Hexadecimals How do you convert a decimal number to a hexadecimal number? To convert a decimal number d to a hexadecimal number is to find the hexadecimal digits hn, hn-1, hn-2, ... , h2, h1, and h0 such that These hexadecimal digits can be found by successively dividing d by 16 until the quotient is 0. The remainders are h0, h1, h2, ... , hn-2, hn-1, and hn. Dec2Hex

  30. §5.5 “break” and “continue” sum=0; mark=1; for ( i=0; ; ){ if (i>100) break; sum += i; i++;} if(i>0) avgnum = sum/I; … • break: • May only be used inside a loop or a switch statement. • To terminate the current loop/switch immediately and transfer control to the statement immediately following that loop/switch.

  31. “continue” sum=0; mark=1; for ( i=0; ; ){ if (i>100) continue; sum += i; i++;} if(i>0) avgnum = sum/I; … • “continue”: • May only be used inside a loop. • To terminate thecurrent iteration of the loop and proceeds directly to the next. • In the case of a for loop it jumps to its action-after-each-iteration.

  32. Examples • Use of “break” TestBreak • Use of “continue” TestContinue

  33. Case Study: Checking Palindrome Problem: Write a program that tests whether a string is a palindrome. A string is a palindrome if it reads the same forward andbackward. The words“mom,”“dad,”and “noon,” for example, are all palindromes. How do you write a program to check whether a string is a palindrome? Solution: One solution is to check first-last, second-second-last, …, the middle! TestPalindrome

  34. Loop Example: Displaying Prime Numbers • Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. • An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. • Solution: The problem can be broken into the following tasks: • For number = 2, 3, 4, 5, 6, ..., test whether the number is prime. • Determine whether a given number is prime. • Count the prime numbers. • Print each prime number, and print 10 numbers per line. PrimeNumber

  35. Check Point int balance = 100; while(true) { if(balance <9) break; balance -= 9; } cout<<balance<<endl; int balance = 100; while(true) { if(balance <9) continue; balance -= 9; } cout<<balance<<endl; Show the output of the following code.

  36. Summary “while” and “do-while” loops “for” loops Difference between loop statements Use of “break” and “continue”

  37. Homework Questions int balance = 100; int consumed = 0; while(true) { if(balance <10) break; consumed += 5; if(!(consumed%10)) continue; balance -= consumed; cout<<balance<<endl; } 1. How many times is the following loop body repeated? What’s the printout? 2. Convert the above while loop into a for loop.