Lecture Programming in C++ - Chapter 6: Repetition. On completion of this chapter students will know how to: Create while loops, create do-while loops, create for loops, trace and debug loops, use loops to solve problems.
Chapter 6 Repetition while Loop Simplest loop Two parts: test expression and loop body Pretested loop – Execute loop body if test true – Bypass loop body if test false Lesson 6.1 General Structure while (expression) { Logical expression (variable or arithmetic expression) Boolean results (True or False) statement1 statement2 … Lesson 6.1 } Steps In Using a while Loop 1. Initialize variable acting as test expression 2. Evaluate the boolean test 3. If true execute statements within loop 4. Update the variable 5. Go back to step 2 Note: if no change to variable then infinite loop (never ends) is created Lesson 4.1 Example while Loop Initialize variables int i= 0, number = 1; while (number) Variable as expression { value other than zero tests true cout