Lecture - 10 (Control-Structure)
Lecture - 10 (Control-Structure)
LECTURE-10: LOOPS
Computer Programming
1
TODAY WE WILL COVER
The while loop
The while Loop for Input Validation
Counters
Statement2;
THE WHILE LOOP
THE WHILE LOOP
Loop: a control structure that causes a
statement or statements to repeat
General format of the while loop:
while (expression)
statement;
statement; can also be a block of
statements enclosed in { }
THE WHILE LOOP – HOW IT WORKS
while (expression)
statement;
expression is evaluated
if true, then statement is executed, and
expression is evaluated again
if false, then the loop is finished and program
statements following statement execute
THE LOGIC OF A WHILE LOOP
THE WHILE LOOP-EXAMPLE
HOW THE WHILE LOOP IN PREVIOUS
SLIDE LINES 9 THROUGH 13 WORKS
FLOWCHART OF THE WHILE LOOP
THE WHILE LOOP IS A PRETEST LOOP
int n = 6;
while (n <= 5)
{
cout << "Hello! ICP\n";
number++;
}
WATCH OUT FOR INFINITE LOOPS
The loop must contain code to make
expression become false
Otherwise, the loop will have no way of
stopping
Such a loop is called an infinite loop, because
int n = 1;
while (n <= 5)
{
cout << "Hello ICP\n";
}
USING THE WHILE LOOP FOR INPUT
VALIDATION
USING THE WHILE LOOP FOR
INPUT VALIDATION
Input validation is the process of inspecting
data that is given to the program as input
and determining whether it is valid.
Continued…
A COUNTER VARIABLE CONTROLS
THE DO-WHILE
LOOP
THE DO-WHILE LOOP
do-while: a posttest loop – execute the loop, then
test the expression
General Format:
do
statement; // or block in { }
while (expression);
int x = 1;
do
{
cout << x << endl;
} while(x < 0);
Continued…
A DO-WHILE LOOP
31
DO-WHILE LOOP NOTES
Loop always executes at least once
Execution continues as long as expression is
33