Electrical Engineering - Chapter 6: Repetition
Simplest loop Two parts: test expression and loop body Pre-tested loop Execute loop body if test true Bypass loop body if test false
Bạn đang xem nội dung tài liệu Electrical Engineering - Chapter 6: Repetition, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
Chapter 6 - Repetition while LoopSimplest loopTwo parts: test expression and loop bodyPre-tested loopExecute loop body if test trueBypass loop body if test falseLesson 6.1General Structurewhile (expression) { statement1 statement2 }Logical expression (variable or arithmetic expression)Boolean results (True or False)Lesson 6.1Steps 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 2Note: if no change to variable then infinite loop (never ends) is createdLesson 4.1Example while Loopint i= 0, number = 1;while (number) { cout > number; i++; if (i > 50) break; }Initialize variablesVariable as expressionvalue other than zero tests trueLoop bodyStatements that provide exit from loopLesson 6.2Example while Loopint i= 0;while (i > id_num; } while ((id_num 1999));Lesson 6.3Better do while Loopdo{ cout > id_num; if ((id_num 1999)) { cout > finalValue;for (int counter = 0; counter > finalValue;for (int counter = 0; counter > finalValue;while (counter > finalValue;for(int counter = 0;counter < finalValue;counter ++)cout << "*";Lesson 6.4Debugging and TestingOff by one errorsCheck loops to ensure you are executing the correct number of timesx < 10 or x <= 10Check loop boundariesCan create infinite loopDoes answer make senseLesson 6.4For Loop Modificationsbreak statementCan use within loop to terminate earlyControversial Multiple expressions for initialization and incrementUse comma separated listfor (I = 1, j = 2; I < 10; I++, j++)Lesson 6.4SummaryCreate while loopsCreate do-while loopsCreate for loopsTrace and debug loopsUse loops to solve problemsLearned how to:Chapter 6