【正文】
A First Book of ANSI C Fourth Edition Chapter 5 Repetition A First Book of ANSI C, Fourth Edition 2 Objectives ? Basic Loop Structures ? The while Statement ? Computing Sums and Averages Using a while Loop ? The for Statement A First Book of ANSI C, Fourth Edition 3 Objectives (continued) ? Case Studies: Loop Programming Techniques ? Nested Loops ? The dowhile Statement ? Common Programming and Compiler Errors A First Book of ANSI C, Fourth Edition 4 Introduction ? A section of code that is repeated is called a loop, because after the last statement in the code is executed, the program branches, or loops, back to the first statement and starts another repetition through the code ? Each repetition is also called an iteration or pass through the loop A First Book of ANSI C, Fourth Edition 5 Basic Loop Structures ? Constructing a repeating section of code requires that four elements be present: – Repetition statement ?while statement ?for statement ?dowhile statement – Condition – A statement that initially sets the condition being tested – A statement within the repeating section of code that alters the condition so that it eventually bees false A First Book of ANSI C, Fourth Edition 6 Pretest and Posttest Loops A First Book of ANSI C, Fourth Edition 7 Pretest and Posttest Loops (continued) A First Book of ANSI C, Fourth Edition 8 CounterControlled and ConditionControlled Loops ? Countercontrolled loop: the condition is used to keep track of the number of repetitions – Also known as a fixedcount loop ? Conditioncontrolled loop: the tested condition does not depend on a count being achieved, but rather on a specific value being encountered A First Book of ANSI C, Fourth Edition 9 Basic Loop Structures A First Book of ANSI C, Fourth Edition 10 The while Statement ? The general form of the while statement is while (expression) statement。 ? The transfer of control back to the start of a while statement to reevaluate the expression is known as a program loop ? The following is a valid but infinite