You are on page 1of 56

Chapter 4b

Repetition Control Structure


The Objectives
1. To use while, do-while, and for loops to execute
statements repeatedly.
2. To understand the flow of control in loops.
3. To use Boolean expressions to control loops.
4. To write nested loops.
5. To know the similarities and differences of three
types of loops.
6. (Optional) To implement program control with
break and continue.
Why is Repetition Needed ?
• Ability to repeat an operation or a series of
operations many times.
• An action or a series of actions.
• C++ has three repetition , or looping
structures that allow us to repeat a set of
statements until certain conditions are met:
• while
• do-while
• for
while Looping Structure4
while Loop
Trace whileLoop
Initialize count
int count = 0;
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
(count < 2) is True?
int count = 0;
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
Print Welcome to C++
int count = 0;
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
Increase count by 1
int count = 0; NOW count is 1
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
(count < 2) is still true since
int count = 0; count is 1
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
Print Welcome to C++
int count = 0;
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
Increase count by 1
int count = 0; NOW count is 2
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
(count < 2) is false since
int count = 0; NOW count is 2
while (count < 2)
{
count << “Welcome to C++”;
count++;
}
Trace whileLoop
The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2)


{
count << “Welcome to C++”;
count++;
}
Controlling while Loop
• When a program needs to be tested again and
again on certain data it will operate a large
amount of data.
• To overcome the problem, we have four cases:
 Counter controlled while loops
 Sentinel controlled while loops
 Flag controlled while loops
 User controlled while loops
 EOF-controlled while loops (EOF means End-Of-File)
Counter-controlled while loops
• We know how many pieces of data need to be read.
• Use a counter, by initializing the value to 0.
• If counter < N, the body of the while statement executes
until the value of counter >= N
• The structure :

counter = 0; //initializethe loop control variable


while (counter< N) //testthe loop control variable
{…

counter ++ //updatethe loop control variable

}
Example of a while loop : Counter-controlled
#include <iostream>
using namespace std;

int main ()
{
double score, sum=0,average;
int studProc;

studProc = 0; //initialization
while (studProc< 10)//condition
{
cout << ”Enter your score:”;
cin>>score;
sum += score;
studProc++;//updating
}
average = sum/10;
cout << ”The average is : ” << average;
}
Output:

Enter your score: 60


Enter your score: 50
Enter your score: 90
Enter your score: 80
Enter your score: 55
Enter your score: 97
Enter your score: 86
Enter your score: 40
Enter your score: 65
Enter your score: 73
The average is : 69
Sentinel-Controlled while loops
• We do not know how many data needs to be read.
• The last entry called sentinel, is a special value.
• A sentinel value is a value that is not a legitimate data value for a
particular problem (but is of proper type) that is used as a
“stopping” value.
• The while loop continues to execute as long as the program has not
read the sentinel.
• General structure :
cin>> variable;
while (variable != -1)
{

cin>>variable;

} Sentinel Value
Example of a while loop : Sentinel-controlled
Example of a while loop : Sentinel-controlled
User Controlled while Loops
• Uses a user predefined variable to control the
loop
char continueLoop = 'Y';
while (continueLoop == 'Y')
{
// Execute body once
// Prompt the user for confirmation
cout << "Enter Y to continue and N to quit: ";
cin >> continue Loop;
}
Example of a while loop :User-controlled
#include <iostream>
using namespace std;

int main ()
{
int count=0;
double score, sum=0,average;
char answer=‘y’; //initialization
while (answer==‘y’|| answer==‘Y’) //condition
{
cout << ”Enter your score:”;
cin>>score;
sum += score;
count++;
cout<<”Do you want to continue? y/Y for Yes:”;
cin>>answer; //updating
}
average = sum/count;
cout << ”The average is : ” << average << endl;
Example of a while loop : User-controlled
Output:

Enter your score:60


Do you want to continue? y/Y for Yes: y
Enter your score:50
Do you want to continue? y/Y for Yes: y
Enter your score:90
Do you want to continue? y/Y for Yes: y
Enter your score:80
Do you want to continue? y/Y for Yes: y
Enter your score:55
Do you want to continue? y/Y for Yes: n
The average is :67
Flag-Controlled while Loops
• Uses a bool variable to control the loop
• Example :
found = false; //initialize the loop control variable
while (!found) //test the loop control variable
{

if (expression)
found = true //re-initialize the loop control variable

}
Example of a while loop : Flag-controlled
#include <iostream>
using namespace std;

int main()
{
char letter;
Bool found = false;//initialization
while (!found)//condition
{
cout<<"Enter a letter. Press x to stop : ";
cin>>letter;
if (letter=='x')
{
found = true; //updating
cout<<"\nSTOP\n";
}
}
}
Example of a while loop : Flag-controlled

Output:

Enter a letter. Press x to stop : s


Enter a letter. Press x to stop : x

STOP
EOF-Controlled while Loops
• Is used when the data file is frequently altered, added or deleted
• Example :

cin>> variable; //initialize the loop control variable

while (cin)
{
……cin>> variable; //re-initialize the loop control variable
……
}

• The loop stops when the system detects the end-of-file signal( by pressing
<Ctrl-Z>).
Example of a while loop : EOF-controlled
#include <iostream>
using namespace std;

int main( )
{
int n = 0;
float sum = 0;
cout<<"Enter your numbers:^Z to stop.\n";
while (cin>> n)
sum += n;
cout <<"SUM = "<< sum<<endl;
}
Example of a while loop : EOF-controlled

Output:

Enter your numbers:^Z to stop.


1 2 3 4 5 ^Z
SUM = 15
Press any key to continue . .
do…while Looping Structure
do…while Loop
do…while Loop
#include <iostream>
using namespace std;

int main()
{
int a;//initialization
do
{
cout << "To stop enter a number between 10 & 20 : ";
cin >> a; //updating
} while (a < 10 || a > 20); //condition
cout <<"END"<<endl;
}
Output :
To stop enter a number between 10 & 20 : 3
To stop enter a number between 10 & 20 : 10
for Looping Structure
for Loop
Trace for Loop
int i:
for (i=0; i<2; i++)
{ declare i
cout << “Welcome to C++”;
}
Trace for Loop
execute initializer
int i:
NOW i is 0
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
(i < 2) is true
int i:
since i is 0
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
Print
int i:
Welcome to C++
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
Execute adjustment statement
int i: NOW i is 1
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
(i < 2) is still true
int i:
since i is 1
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
Print
int i:
Welcome to C++
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
Execute adjustment statement
int i: NOW i is 2
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
(i < 2) is false
int i:
since i is 2
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Trace for Loop
Exit the loop. Execute the next
int i:
statement after the loop
for (i=0; i<2; i++)
{
cout << “Welcome to C++”;
}
Comparing for and while Loops
Comparing for and while Loops
Comparing while, do..while & for loops
Recommendations
• Use the one that is most intuitive and
comfortable for you.
• In general, a for loop may be used if the number
of repetitions is known, as, for example, when
you need to print a message 100 times.
• A while loop may be used if the number of
repetitions is not known, as in the case of reading
the numbers until the input is 0.
• A do-while loop can be used to replace a while
loop if the loop body has to be executed before
testing the continuation condition.
Nested for Loop
Other Statement Related to Looping
• break
 causes a loop to terminate
 terminate only the inner loop in nested loop
• continue
 transfers to the testing expression in while and
do…while statement
 transfers to the updating expression in a for
statement.
The continue Statement
The break Example
Output

You might also like