2. After studying this chapter you will be able to: O BJECTIVES Understand the basic components of a loop: initialization, control expression, and update. Understand and use pretest, post-test, and count-controlled loops. Differentiate between event-controlled and counter-controlled loops. Write loops in C++ using while , for , and do...while loops. Understand the limitations and use of break and continue statements in loops.
8. Pretest Loop In each iteration, the loop control expression is tested first. If it is true, the loop action(s) is executed; if it is false, the loop is terminated. Post-test Loop In each iteration, the loop action(s) are executed. Next, the loop control expression is tested. If it is true, a new iteration is started; otherwise, the loop terminates. Note:
9. Figure : Pretest and post-test loops “ WHILE” test at the top…. “WHILE” test at the bottom CONDITION CONDITION
10. Figure : Two different strategies for starting exercise CONDITION CONDITION False True
11. Figure : Minimum number of iterations in two loops It is important that you understand this critical difference between the two basic types…
22. Figure : for statement The for is just a special case of a while loop.
23. The for loop is constructed in this way… for ( initialization statement(s) , while test expression , update statement(s) ) { body of loop… }
24. A for loop is used when your loop is to be executed a known number of times. You can do the same thing with a while loop, but the for loop is easier to read and more natural for counting loops. Note:
27. In C/C++ the for loop counter is almost always initialized to a ZERO . So, if you want to do something 5 times, the for loop would be coded like this… for (int i = 0; i < 5; i++) { do something… } It is also legal to have the test expression limit be a variable, as in: for (int i = 0; i < Num; i++)