Introduction to Programming
(C++)
Gliceria S. Tan
Instructor
Session 10 Topics
➢ Repetition Structures (while, do-while, for)
➢ The break statement
➢ The continue statement
➢ The Sentinel
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR
Repetition Structures
Repetition (loop/iteration) control structures
allow us to execute specific blocks of code a
number of times.
There are three types of repetition control
structures: the while statement, do-while
statement, and for statement.
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR
The while statement
Syntax:
while(condition){
statement1;
statement2;
...
}
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR
Example:
int x = 0;
while (x<10){
cout<<x;
x++;
}
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR
The do-while statement
Syntax:
do{
statement1;
statement2;
...
}while(condition);
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR
Example:
int x = 0;
do{
cout<<x;
x++;
}while (x<10);
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR
The for statement
Syntax:
for(initialization; condition; inc/dec){
statement1;
statement2;
...
}
Example:
int i;
for(i = 1; i<=10; i++){
cout<<i;
}
The break statement
Causes an immediate exit from any loop. For
example,
int i = 4;
while ( i > 0 ){
cout<<i;
i--;
if(i==1)
break;
}
This causes the loop to exit (or terminate)
when i is 1. As a result, the loop only outputs
the numbers 432.
The continue statement
Used to skip an iteration (ignores executing the rest of
the loop). For example:
int i = 4;
while ( i > 0 ){
if(i==3){
i--;
continue;
}
cout<<i;
i--;
}
The output of the program is 421.
The Sentinel
What is a sentinel?
✓ It is a special value that marks the
end of a list of values.
✓ It is a good technique in exiting a
loop.
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR
The Sentinel
Sample problem:
Using while or do-while loop, repeatedly ask for a
number and display “POSITIVE” if it is positive,
“NEGATIVE” if it is negative. The flow of execution
will only terminate when a sentinel value of 0 is
entered.
Sample output:
Enter a number: 1
POSITIVE
Enter a number: -3
NEGATIVE
Enter a number: 0
Bye!
In this flowchart, you START
do not know how
many numbers will be
entered. In fact, the INPUT n
number of values
entered could be n>0
T OUTPUT
different each time “POSITIVE”
F
the flowchart is
executed. n<0
T OUTPUT
“NEGATIVE”
By using a sentinel F
value of 0, the loop n == 0
T
STOP
terminates when the
F
condition n == 0 is
evaluated.
sentinel
START
HOMEWORK:
Using do-while loop, INPUT n
write the equivalent
program of the
flowchart. n>0
T OUTPUT
“POSITIVE”
Sample output: F
T OUTPUT
Enter a number: 1 n<0
“NEGATIVE”
POSITIVE
F
Enter a number: -1
NEGATIVE T
n == 0 STOP
Enter a number: 0
Bye! F
“QUOTE OF THE DAY!”
GLICERIA S. TAN, MIS COMPUTER PROGRAMMING 1
INSTRUCTOR