Two types of repetition structures: pretest and posttest loops
Pretest:
- Loop condition appears at beginning of pretest loop
- Determines number of times instructions w/in loop body are processed
#f5f5dc;”>Types of pretest loop:
- while
- for
#f5f5dc;”>Posttest:
- Loop condition appears at end of posttest loop
- Determines number of times instructions w/in loop body are processed
- HOWEVER, instructions processed at least once–the first time!
#f5f5dc;”>Types of posttest loop:
- do…while while
#f5f5dc;”>Counter-Controlled Repetition Requires
- the name of a control variable (or loop counter)
- the initial value of the control variable
- the loop-continuation condition that tests for the final value of the control variable to determine when to exit
- the control variable to be incremented (or decremented) each time through the loop
Using while Loop:
- Executes from zero to many times, depending on expression
- while is reserved word
- Syntax of while statement:
while (expression) statement;
- Expression provides entry condition
- Expression (parentheses must be included as part of syntax) must evaluate to true to invoke loop statement(s)
- Statement(s) can be simple or compound (block)
- Statement(s) is/are body of loop
- BE SURE to include an exit condition that will eventually evaluate expression to be false
- Infinite loop: statement(s) continue(s) to execute endlessly
- Loop invocation:
- Statement(s) execute(s) if expression evaluates to true
- Loop condition reevaluated
- Statement(s) continue(s) to execute until expression false
#f5f5dc;">Example: int counter=1; //initialize loop control variable while (counterUsing for Loop:
- Executes a set number of times determined by the counter
- Statement can be a single statement or a compound (block) statement.
- for is reserved word
- Simplifies writing of count-controlled while loop
- Syntax of for statement (for loop control statements):
for (initial statement; test statement (loop condition); update statement) statement;
#f5f5dc;">Example: //printing 1 - 10 using for loop cout
#Mastery22 – #TC1017 by Jose Eduardo Sanchez is licensed under a Creative Commons Attribution 4.0 International License.