Professional Documents
Culture Documents
Chapter 5
Repetition statements
23:44:46
5.1 while loops
Sentinels:
In computer programming, data values used to signal the start or
end of a data series are called sentinels.
Sentinel values must be selected so as not to conflict with
legitimate data values.
break statement:
A break statement forces an immediate break, or exit, from the
switch, while, for, and do-while statements.
Example:
continue statement
The continue statement applies only to loops created with while,
do-while, and for statements.
When continue is encountered in a loop, the next iteration of the
loop begins immediately. For while loops, this means execution is
transferred automatically to the top of the loop, and reevaluation of
the tested expression is initiated.
Example: Invalid grades are simply ignored, and only valid grades
are added to the total.
while ( count < 30) {
c o u t << ” E n te r a grade : ” ;
c i n >> grade
i f ( grade < 0 | | grade > 100)
continue ;
t o t a l = t o t a l + grade ;
count ++;
}
Example:
Remark:
The for statement only ensures that all expressions in the initializing
list are executed once, before evaluation of the tested expression,
and all expressions in the altering list are executed at the end of the
loop, before the tested expression is rechecked.
Example: The initial is outside the for statement, and the first list
inside the parentheses is left blank.
# include <iostream >
u s in g namespace s t d ;
i n t main ( ) {
i n t count ;
count = 2 ;
/ / i n i t i a l i z e r o u t s i d e th e f o r s ta te m e n t
f o r ( ; count <= 2 0 ; count = count + 2 )
c o u t << count << ” ” ;
r e tu r n 0 ;
}
Example: Both the initializing list and the altering list are outside
the parentheses.
# include <iostream >
u s in g namespace s t d ;
i n t main ( ) {
i n t count ;
count = 2 ; / / i n i t i a l i z e r o u t s i d e th e f o r lo o p
f o r ( ; count <= 2 0 ; ) {
c o u t << count << ” ” ;
count = count + 2 ; / / a l t e r a t i o n s ta te m e n t
}
r e tu r n 0 ;
}
Example: All items inside the parentheses, no need for any useful
statement following the parentheses.
# include <iostream >
u s in g namespace s t d ;
i n t main ( ) {
/ / a l l e x p r e s s i o n s i n s i d e f o r ’ s parentheses
i n t count ;
f o r ( count = 2 ; count <= 2 0 ;
c o u t << count << ” ” , count = count + 2 ) ;
r e tu r n 0 ;
}
In this example, the null statement satisfies the syntactical
requirement of one statement to follow fors parentheses.
Validity checks
The do statement is particularly useful in filtering user-entered input
and providing data validation checks. For example, an operator is
required to enter a valid customer identification number between
1000 and 1999. A number outside this range is to be rejected, and
a new request for a valid number is made.
do {
c o u t << ” \ nEnter an i d e n t i f i c a t i o n number : ” ;
c i n >> id num ;
}
while ( id num < 1000 | | id num > 1 9 9 9 ) ;