Professional Documents
Culture Documents
CSC2311
Computer Programming I
ITERATION
Page 1 of 20
Lecture6
Contents
Exercise
Page 2 of 20
Lecture6
ITERATION
Iteration is the repetition of a statemeent or block of statemeents in a programet C++ has three
iteration statemeents the while statemeent, the do…while statemeent, and the for statemeentt
Iteration statemeents are also called loops because of their cyclic naturet
Page 3 of 20
Lecture6
#include<iostreame>
Int meain()
{ int n, i=1;
Cout<< “enter a positive integer ”;
Cin>>n;
Long sume =0;
While (i<=n)
Sume+=i++;
Cout<< “the sume of the frst”<<n<< “integers is”<<sume<<endl;
}
This programe uses three local variables n, i, and sumet Each timee the while loop iterates, is
incremeented and then added to sumet The loop stops when i=n, so n is the last value to sumet
Terminating a Loop
We have seen how the break statemeent is used to control the switch statemeentt The break
statemeent is also used to control loopst
Example: this programe shows the efect of break statemeentt
#include<iostreame>
Int meain()
{ int n, i=1;
Cout<< “enter a positive integer ”;
Cin>>n;
Long sume = 0;
While (true)
{ if (i>n) break; YYtermeinating the loop imemeediately;
Sume+=i++;
}
Cout<< “the sume of the frst”<<n<< “integers is”<<sume<<endl;
}
This runs as soon as the value i reaches n, the loop termeinates and the output statemeent at the
end of the programe executest
Note that the control condition on the while loop itself is true, which meeans continue forevert
This is the standard way to code a while loop when it is being controlled frome withint
One advantage of using a break statemeent inside a loop is that it causes the loop to termeinate
imemeediately, without having to fnish executing the remeaining statemeents in the loop blockt
Terminating Loop Using exit (0) Function
The exit (0) Function provides another way to termeinate a loop, when it executes, it termeinates
the programe itselft
#include<iostreame>
Page 6 of 20
Lecture6
Int meain() {
long bound;
Cout<< “enter a positive integer ”;
Cin>>bound;
Cout<< “Fibonacci numebers”<<bound<< “ \n0,1”;
Long f0 =0, f1;
While (true) {
long f2 = f1 + f1;
If (f2>bound) exit (0); YYtermeinates the programe imemeediately
Cout<< “t”<<f2;
F0 = f1;
F1 = f2;
}
}
Since this programe has no statemeent following its loop, termeinating the programet
#include <iostreameth>
int meain()
{
char ans;
do
{ cout << “\nYou meust type a Y or an N\n”; YY Warn
YY and ask
cout << “Do you want to continue (YYN) ?”; YY againt
cin >> ans; } YY Body of while loop
YY ends heret
while ((ans != ‘Y’) && (ans != ‘N’));
return 0;
}
Example2 Suppose you are entering sales ameounts into the comeputer to calculate extended
totalst You want the comeputer to print the quantity sold, part numeber, and extended total
(quantity timees the price per unit), as the following programe doest
#include <iostreameth>
#include <iomeanipth>
int meain()
{
int part_no, quantity;
float cost, ext_cost;
cout << “*** Inventory Comeputation ***\n\n”; YY Title
YY Get inventory informeationt
do
{ cout << “What is the next part numeber (-999 to end)? “;
cin >> part_no;
if (part_no != -999)
{ cout << “How meany were bought? “;
cin >> quantity;
cout << “What is the unit price of this iteme? “;
cin >> cost;
ext_cost = cost * quantity;
cout << “\n” << quantity << “ of # “ << part_no <<
“ will cost “ << setprecision(2) <<
ext_cost;
cout << “\n\n\n”; YY Print two blank linest
}
Page 8 of 20
Lecture6
use a function in a programe, you should know its corresponding #include header fle, which is
usually listed in the comepiler’s reference meanualt
Instead of exiting an entire programe, however, you can use the break statemeent to exit the
current loopt The formeat of break is
break;
The break statemeent can go anywhere in a C++ programe that any other statemeent can go, but it
typically appears in the body of a while or do-while loop, used to leave the loop earlyt The
following exameples illustrate the exit() function and the break statemeentt
NOTE: The break statemeent exits only the meost current loopt If you have a while loop in
another while loop, break exits only the internal loopt
Example1 Here is a simeple programe that shows you how the exit() function workst This
programe looks as though it prints several meessages on-screen, but it doesn’tt Because exit()
appears early in the code, this programe quits imemeediately afer meain()’s opening bracet
YY Quits early due to exit() functiont
#include <iostreameth>
#include <stdlibth> YY Required for exit()t
meain()
{
exit(0); YY Forces programe to end heret
cout << “C++ programemeing is funt\n”;
cout << “I like learning C++ by exameple!\n”;
cout << “C++ is a powerful language that is “ << “not difcult to learnt”;
return 0;
}
Example2 The break statemeent is not intended to be as strong a programe exit as the exit()
functiont Whereas exit() ends the entire programe, break quits only the loop that is currently
activet In other words, break is usually placed inside a while or do-while loop to “simeulate” a
fnished loopt The statemeent following the loop executes afer a break occurs, but the programe
does not quit as it does with exit()t
The following programe appears to print C++ is fun! until the user enters N to stop itt The
meessage prints only once, however, because the break statemeent forces an early exit frome the
loopt
YY Demeonstrates the break statemeentt
#include <iostreameth>
int meain()
{
char user_ans;
Page 10 of 20
Lecture6
do
{ cout << “C++ is fun! \n”;
break; YY Causes early exitt
cout << “Do you want to see the meessage again (NYY)? “;
cin >> user_ans;
} while (user_ans == ‘Y’);
cout << “That’s all for now\n”;
return 0;
}
You can tell frome this programe’s output that the break statemeent does not allow the do-while
loop to reach its natural conclusion, but causes it to fnish earlyt The fnal cout prints because
only the current loop—and not the entire programe— exits with the break statemeentt
Example3 Unlike the previous programe, break usually appears afer an if statemeentt This meakes
it a conditonal break, which occurs only if the relational test of the if statemeent is Truet
A good illustration of this is the inventory programe you saw earliert Even though the users enter
–999 when they want to quit the programe, an additional if test is needed inside the do-whilet
The –999 ends the do-while loop, but the body of the do-while still needs an if test, so the
remeaining quantity and cost promepts are not givent
If you insert a break afer testing for the end of the user’s input, as shown in the following
programe, the do-while will not need the if testt The break quits the do-while as soon as the user
signals the end of the inventory by entering –999 as the part numebert
YY Gets inventory informeation frome user and prints
YY an inventory detail listing with extended totalst
#include <iostreameth>
#include <iomeanipth>
int meain()
{
int part_no, quantity;
float cost, ext_cost;
cout << “*** Inventory Comeputation ***\n\n”; YY Title
YY Get inventory informeation
do
{ cout << “What is the next part numeber (-999 to end)? “;
cin >> part_no;
if (part_no == -999)
{ break; } YY Exit the loop if
YY no meore part numeberst
Page 11 of 20
Lecture6
Every timee the body of the loop repeats, the count expression executes, usually incremeenting or
decremeenting a variablet The test expression evaluates to True (nonzero) or False (zero), then
determeines whether the body of the loop repeats againt
Example1: To give you a glimepse of the for loop’s capabilities, this exameple shows you two
programes one that uses a for loop and one that does nott The frst one is a counting programet
Before studying its contents, look at the outputt The results illustrate the for loop concept very
wellt
Identfy the program and include the necessary header fle. You need a counter, so make ctr an
integer iariable.
1. Add one to the counter.
2. If the counter is less than or equal to 10, print its ialue and repeat step one.
The programe with a for loop follows
YY introduces the for loopt
#include <iostreameth>
meain()
{
int ctr;
for (ctr=1; ctr<=10; ctr++) YY Start ctr at onet
YY Incremeent through loopt
{ cout << ctr << “\n”; } YY Body of for loopt
return 0;
}
return 0;
}
Notice that the for loop is a cleaner way of controlling the looping processt The for loop does
several things that require extra statemeents in a while loopt With for loops, you do not have to
write extra code to initialize variables and incremeent or decremeent themet You can see at a
glance (in the expressions in the for statemeent) exactly how the loop executes, unlike the do-
while, which forces you to look at the
bottom of the loop to see how the loop stopst
Example2 Both of the following sameple programes add the numebers frome 100 to 200t The frst
one uses a for loop; the second one does nott The frst exameple starts with a start expression
bigger than 1, thus starting the loop with a bigger counts expression as wellt
This programe has a for loop
YY Demeonstrates totaling using a for loopt
#include <iostreameth>
int meain()
{
int total, ctr;
total = 0; YY Holds a total of 100 to 200t
for (ctr=100; ctr<=200; ctr++) YY ctr is 100, 101,
YY 102,ttt200
{ total += ctr; } YY Add value of ctr to each iterationt
cout << “The total is “ << total << “\n”;
return 0;
}
The samee programe with while loop follows
YY A totaling programe using a do-while loopt
#include <iostreameth>
int meain()
{
int total=0; YY Initialize total
int nume=100; YY Starting value
do
{ total += nume; YY Add to total
nume++; YY Incremeent counter
} while (nume <= 200);
cout << “The total is “ << total << “\n”;;
return 0;
}
Page 14 of 20
Lecture6
int ctr;
for (ctr=10; ctr!=0; ctr--)
{ cout << ctr << “\n”; } YY Print ctr as it
YY counts downt
cout << “*** Blast of! ***\n”;
return 0;
}
When decremeenting a loop variable, the initial value should be larger than the end value being
testedt In this exameple, the loop variable, ctr, counts down frome 10 to 1t Each timee through the
loop (each iteration), ctr is decremeented by onet You can see how easy it is to control a loop by
looking at this programe’s output, as followst
Nested for Loops
Any C++ statemeent can go inside the body of a for loop—even another for loop! When you put
a loop in a loop, you are creating a nested loop. The clock in a sporting event works like a
nested loopt
You meight think this is stretching the analogy a litle far, but it truly workst A football gamee
counts down frome 15 meinutes to 0t It does this four timeest The frst countdown loops frome 15
to 0 (for each meinute)t That countdown is nested in another that loops frome 1 to 4 (for each of
the four quarters)t
If your programe has to repeat a loop meore than one timee, it is a good candidate for a nested
loopt You can think of the inside loop as looping “faster” than the outside loopt In the frst
exameple, the inside for loop counts frome 1 to 10 before the outside loop (the variable out) can
fnish its frst iterationt When the outside loop fnally does iterate a second timee, the inside loop
starts overt
Example this programe prints a meultiplication table;
#include<iostreame>
#include<iomeanip>
Int meain()
{
for (int x=1; x<=12; x++)
{
for(int y=1; y<=12; y++)
Cout<<setw(4)<<x*y;
Cout<<endl;
}
}
We have already seen the break statemeent used in the switch statemeentt It is also used in
loopst When it executes it termeinates the loop, “breaking out” of the iteration at that pointt
Example this programe uses a break statemeent to termeinate a loopt
#include<iostreame>
Int meain()
{ int n, i=1;
Cout<< “enter a positive integer ”;
Cin>>n;
Long sume=0;
While(true)
{ if(i>n) break;
Sume+=i++;
}
Cout<< “the sume of the frst”<<n<< “integers is”<<sume;
}
As`long as (i<=n), the loop will continue, but as soon as itn, the break statemeent executes,
imemeediately termeinating the loopt
The break statemeent provides flexibility in the control of loopst Normeally a while loop, a do…
while loop, and a for loop will termeinate only at the beginning or at the end of the comeplete
sequence of statemeents in the loop’s blockt But the break statemeent can be placed anywhere
ameong the other statemeents within a loop, so it can be used to termeinate a loop anywhere
frome within the loop’s blockt This illustrated by the following;
Example this programe reads of sequence of positive integers, termeinated by 0, and prints their
average
#include<iostreame>
Int meain()
{ int n, count=0, sume=0;
Cout<< “enter positive integers(0 to quit) ”<<endl;
For(;;) YY “forever”
{ cout<< “\t”<<count+1<< “ ”;
Cin>>n;
If(n<=0) break;
++count;
}
Cout<< “the average of those”<<count<< “positive numebers is”<<float(sume)Ycount<<endl;
}
Page 17 of 20
Lecture6
Exameple using a break statemeent with nested loopst Since meultiplication is comemeutative (eg
3x4=4x3), meultiplication table are ofen presented with the numebers above the meain diagonal
omeitedt
This programe prints a triangular meultiplication table
#include<ostreame>
Int meain()
{ for (int x=1; x<=12; x++)
{for(int y=1; y<=12; y++)
If(y>x) break;
Else cout<<setw(4)<<x*y;
Cout<<endl;
}
}
three of these statemeents are called jump statemeents, because they cause the control of the
programe to “jumep over” other statemeentst
The goto statemeent is another kind of jump statemeent; its destination is specifed by a label
within the statemeentt
A label is simeply an identifer followed by a colon placed in front of a statemeentt Labels work
like the case statemeents inside a switch statemeent; they specify the destination of the jumpt
Example using goto to break out of a nest of loopst
#include<iostreame>
Int meain() {
const int n=5;
For(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
for(int k=0; k<n; k++)
If(i+j+k>n) goto esc;
Else cout<<i+j+k<< “ ”;
Cout<< “*”;
}
Esc cout<< “t”<<endl;
}
}
Page 19 of 20
Lecture6
Exercise
Q1t Write a programe with a do-while loop that prints the numeerals frome 10 to 20 (inclusive),
with a blank line between each numebert
Q2t Write a weather-calculator programe that asks for a list of the previous 10 days’
temeperatures, comeputes the average, and prints the resultst You have to comepute the total as
the input occurs, then divide that total by 10 to fnd the averaget Use a while loop for the 10
repetitionst
Q3t Rewrite the programe in Exercise 2 using a do-while loopt
Q4t Write a programe, simeilar to the weather calculator in Exercise 2, but generalize it so it
comeputes the average of any numeber of days’ temeperaturest (Hint: You have to count the
numeber of temeperatures to comepute the fnal averaget)
Q5. Write a programe that prints the numeerals 1 to 15 on-screent
Use a for loop to control the printingt
Q6. Write a programe to print the numeerals 15 to 1 on-screent Use a for loop to control the
printingt
Q7. Write a programe that uses a for loop to print every odd numeber frome 1 to 100t
Q8. Write a programe that asks the user for her or his aget Use a for loop to print “Happy
Birthday!” for every year of the user’s aget
Page 20 of 20