You are on page 1of 9

while, for, do-while

provide
ability to execute the same code multiple times

three constructs
while statement
do-while statement
for statement

syntax
while
(expression)
action
semantics

if expression is true
then execute action
repeat this process until
expression evaluates to
false

expression

true

false

action

action is either a
single statement or a
block

syntax
do
action
while
(expression);
semantics

execute action
if expression is true
then execute action
again
repeat this process until
expression evaluates to
false

action is either a single


statement or a block

action

true
expression
false

init_statement
syntax
for(init_statement;
expression; post_statement)
action
semantics

execute init_statement
evaluate expression if true
execute action
execute post_statement
repeat

example
for (int i = 0; i < 20; ++i)
cout << "i is " << i << endl;

false
expression
true
action

post_statement

what is idiom again?


often need to iterate while keep track of some value across
iterations maximum found, sum, if all positive, etc.
idiom
before loop declare variable to keep track, initialize it
inside loop, update tracking variable, use branching if
necessary to examine
after loop, use the tracking variable that accumulated the
result
example:
cout << "Input number [0 to quit]: ";
int max, n;
cin >> n; max = n;
while (n != 0 ) {
cin >> n;
if ( n > max) max = n;
}
cout << Maximum number: << max << endl;
6

break - exits innermost loop


int sum=0;
while(sum < 100) {
int i; cin >> i;
if (i< 0) {
cout << found negative number\n;
break;
}
sum +=i;
}
continue - skip the remaining statements and start a new iteration (evaluate
expression)
int sum=0;
for (int i = 0; i < 20; ++i) {
int intVar; cin >> intVar;
if(intVar < 0) continue;
sum +=i;
}
avoid break/continue with loops as they make code less readable (avoid
regular loop exit)
first try to code loop without them
7

iterative constructs can be nested: one


iterative construct may be inside the body of
another
example:

for (int i = 0; i < 10; ++i) // outer loop


for (int j = 0; j < 10; ++j) // inner loop
cout << i << j << endl;

what would this code output?


note, there is no need for curly brackets

nesting may be more than two loops deep


for/while/do-while can be mixed in nesting
besides nested loops, loop body may contain
other code

including branching constructs: a branching construct


nested in the loop
8

key points
make sure there is a statement that will
eventually nullify the iteration criterion (i.e.,
the loop must stop)
make sure that initialization of any loop
counters or iterators is properly performed
have a clear purpose for the loop
document the purpose of the loop and how the
body of the loop advances the purpose of the loop

You might also like