Control Structures: Iteration
The
do-while
statement
Syntax:
do { statements } while (expression);
Statements in the block are executed iteratively while
expression
is true. The
expression
is evaluated at the end of each iteration. The block of statements is
guaranteed to be executed at least once
Example of a
do-while
loop
The
while
statement
Syntax:
while (expression){ statements }
While
expression
is true, the statements in the block are excuted iteratively. The
expression
is evaluated at the end of each iteration
Example of an infinite loop:
while(1){ statements }
Example of a
while
loop
The
for
statement
Syntax:
for (expression_1; expression_2; expression_3){ statements }
Usually is a more compact substitute for the
while
and
do-while
loops
For example the following two loops are equivalent:
int i = 1; while ( i <= n ) { int s += i; i++; }
for (int i = 1; i <= n; i++) int s += i;
Any of the expressions can be omitted from the statement, making the following statement valid:
for ( ; i > 0 ; ){ ... }
Example of a
for
loop
The logical &&, || operators can be used to evaluate multiple expressions in the
while
and
do-while
and
for
loops
The comma operator can be used to evaluate more than one expression in the loop. For example:
for ( int i = 0, int j = 1; j > 0; i++){ ...}
The
break
statement may be used to break out of a loop
The
continue
statement causes a jump to the evaluation of the expression for loop termination
When two loops are nested, each iteration of the outer loop is accompanied by a complete execution of the inner loop
Exercises...
Back to BA 224 Syllabus
Back to BA 225 C++ Review Page
Back to BA 423 Syllabus
Document:
Local Date:
Last Modified On: