6- iterative constructs: while, do-while, for Flashcards
increment
increase value by one, unary operator: ++
decrement
decrease value by one, unary operator: –
Iterative Constructs
provide ability to execute the same code multiple times
1. while statement
2. do-while statement
3. for statement
while
syntax
while (expression)
body
semantics
if expression is true then execute body
body is either a single statement or a block
iteration: single execution of body
iterate until expression evaluates to false
example
while (n != 0) {
cin»_space; n;
if (n > max) max = n;
}
do-while
syntax
do
body
while (expression);
semantics
execute body
if expression is true then iterate again
iterate until expression evaluates to false
example
int max=0, n;
do {
cin»_space; n;
if (n > max) max = n;
} while (n != 0);
for
syntax
for(initStatement;
expression; postStatement)
body
semantics
execute initStatement
evaluate expression, if true: iterate
iteration:
execute body
execute postStatement
repeat expression evaluation
example
for (int i=0; i<20; ++i)
cout «_space;“i is “ «_space;i «_space;endl;
loop variable - declared inside for
its scope is body of the loop
modifying loop variable inside body is poor style, use while instead
break
exits innermost loop
avoid break with loops as they make code less readable (makes regular loop exit unnecessary): first try to code loop without it
continue
skip the remaining statements and start a new iteration (evaluate expression)