tailieunhanh - Lecture Programming in C++ - Chapter 6: Repetition
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 Pre-tested loop Execute loop body if test true Bypass loop body if test false Lesson General Structure while (expression) { statement1 statement2 } Logical expression (variable or arithmetic expression) Boolean results (True or False) Lesson 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 Example while Loop int i= 0, number = 1; while (number) { cout > number; i++; if (i > 50) break; } Initialize variables Variable as expression value other than zero tests true Loop body Statements that provide exit from loop Lesson Example while Loop int i= 0; while (i > number; i++; if (i > 50) break; } Initialize variables Variable as expression value other than zero tests true Loop body Statements that provide exit from loop Lesson Example while Loop int i= 0; while (i > id_num; } while ((id_num 1999)); Lesson Better do while Loop do { cout > id_num; if ((id_num 1999)) { cout << “\n invalid number entered” << “\n please check and re-enter”; } else break; } while (1); Decision Statement – Chapter 5 Expression always true Exit loop if id number is valid Lesson Recap while(s) while Most commonly used when repetition not counter controlled Pre-tested Loop body may not be .
đang nạp các trang xem trước