1 / 24

Repetition in C++

Repetition in C++. around and around it goes. Repetition as a control structure. Instructions need to be repeated more than one time to process lots of data Could do it by just literally repeating the code, by copy and paste But that isn't flexible, nor is it easy to keep consistent

epurcell
Download Presentation

Repetition in C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Repetition in C++ around and around it goes...

  2. Repetition as a control structure • Instructions need to be repeated more than one time to process lots of data • Could do it by just literally repeating the code, by copy and paste • But that isn't flexible, nor is it easy to keep consistent • Need a "loop"

  3. Two Parts to Repetition • a Body • what needs to be repeated • must be marked off in some fashion like {} • a Control expression • some way to make the repetition stop when desired • Infinite loops not wanted!

  4. a While statement • The body can be either one statement (doesn't need {} then) or more than one statement (a block that has {} around it) • Any kind of statement can be in the body of a loop, including other while statements

  5. The syntax of a while • while (condition) // note no semicolon { statement; statement; statement; } • Indentation useful for humans, not compiler

  6. The semantics of a while • The condition at the top of the loop is evaluated to see if it is true or false • it MUST be - will be coerced to bool ! • If the condition is true, the body will be entered at the top and executed all the way through • Then the condition will be evaluated again, and the process is repeated

  7. The semantics of a while (cont'd) • If the condition at the top turns out to be false, the body of the loop is completely skipped • Execution continues with statements following loop body • PRE-test loop - it is possible the body may not be executed at all!

  8. When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the loop body WHILE LOOP FALSE Expression TRUE body statement

  9. How to control it? • TWO kinds of loops • counter-controlled (x < 5) • when you know how many times you want it to repeat • sentinel-controlled (x != -1) • when you let EVENTS control how many times it repeats

  10. Counter-controlled loops • Three parts • counter variable - declare and initialize outside the loop int ctr = 0; • test the counter at the top of the loop while (ctr < 5) • COUNT inside the loop body ctr = ctr + 1;

  11. An Example int linectr = 0; while (linectr <= 3) { cout << linectr << endl; linectr = linectr + 1; } How many lines of output??

  12. Sentinel-controlled loop • Three parts • Initial read / input before the loop • cin >> num; • Test at top of loop for sentinel value or event • while (num != -1) • Change something inside the loop • cin >> num;

  13. An Example int num; cin >> num; while (num > 0) { cout << num; cin >> num; } How many repetitions of the body??

  14. Causes of infinite loops • Testing the wrong variable • forgetting to change the counter or the situation inside the loop • using the wrong test (< instead of >) • using = instead of ==

  15. Loop Testing and Debugging • Test data should test all sections of program • Check loop termination condition, and watch for “off-by-1” bugs • Use get function for loops controlled by detection of ‘\n’ character • Use algorithm walk-through to verify pre- and postconditions • Trace execution of loop by hand • Use a debugger to run program in “slow motion” or use debug output statements

  16. Counters and Accumulators • Counters used most often to control loops • can also be used just to find out "how many?" • variable must appear on both sides of assignment statement • any mathematical operator can be used • the amount the counter is changed by is a CONSTANT (named or literal)

  17. Counters and Accumulators • Examples • record_count = record_count + 3; • part_count = part_count - 4; • errCount = errCount * 5; • Counters are almost always integers • arithmetic is faster than floating point • does not introduce error of representing floating point numbers • Counters MUST be initialized before use!!

  18. Counters and Accumulators • Accumulators are similar to counters • variable must appear on both sides of assignment operator • accumulators MUST be initialized before use!! • Accumulators are different from counters • accumulators typically use change by a VARIABLE amount, not a constant amount

  19. Counters and Accumulators • Examples • total_bill = total_bill + price; • test_score = test_score + points; • factorial = factorial * number; • Accumulators can be any numeric type, as often float as integer

  20. Finding the largest • a common task (almost same logic as finding smallest) • for two numbers it's simple, one comparison • if (num1 > num2) largest = num1; else largest = num2;

  21. Finding the largest • for more than two numbers, it is more difficult • to do it brute force would involve a very complicated if statement • Better to do it in a loop where only two numbers are compared at a time

  22. Finding the largest cin >> num; while (num != -1) // sentinel { if (num > max) max = num; cin >> num; } // when finished, max contains largest

  23. Finding the largest Except the code on previous slide is not complete! What value do you start max as? Some people start with a 'dummy' value That's not safe (why?) Better to start max with the first value read in - before loop starts (why is it better?)

  24. Nested Loops initialize outer loop while (outer loop condition) { . . . initialize inner loop while(inner loop condition) { inner loop processing and update } . . . } 24

More Related