You are on page 1of 20

Lecture6

Department of Mathematics & Computer Science

CSC2311

Computer Programming I

(C++ Programming Language)

ITERATION

Page 1 of 20
Lecture6

Contents

 The while loop

 The do...while loop

 The for loop

 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

The while Statement


The while statemeent is one of several C++ construct statements. Each construct (frome
constructon) is a programemeing language statemeent— or a series of statemeents—that controls
loopingt The while, like other such statemeents, is a looping statement that controls the
execution of a series of other statemeentst Looping statemeents cause parts of a programe to
execute repeatedly, as long as a certain condition is being meett
The formeat of the while statemeent is
while (test expression){
block of one or meore C++ statemeents;
}
The parentheses around test expression are requiredt As long as test expression is True
(nonzero), the block of one or meore C++ statemeents executes repeatedly until test expression
becomees False (evaluates to zero)t Braces are required before and afer the body of the while
loop, unless you want to execute only one statemeentt Each statemeent in the body of the while
loop requires an ending semeicolont The placeholder test expression usually contains relational
and possibly logical operatorst These operators provide the True - False condition checked in
test expression. If test expression is False when the programe reaches the while loop for the frst
timee, the body of the while loop does not execute at allt Regardless of whether the body of the
while loop executes no timees, one timee, or meany timees, the statemeents following the while
loop’s closing brace execute if test expression becomees Falset Because test expression
determeines when the loop fnishes, the body of the while loop meust change the variables used
in test expression. Otherwise, test expression never changes and the while loop repeats
forevert This is known as an infnite loop, and you should avoid itt

The Concept of Loops


You use the loop concept in everyday lifet Any timee you have to repeat the samee procedure,
you are performeing a loop—just as your comeputer does with the while statemeentt Suppose you
are wrapping holiday gifst The following statemeents represent the looping steps (in while
formeat) that you follow while gif-wrappingt
while (there are stll unwrapped gifss {
Get the next gift
Cut the wrapping papert

Page 3 of 20
Lecture6

Wrap the gift


Put a bow on the gift
Fill out a name card for the gift
Put the wrapped gif with the otherst
}
Whether you have 3, 15, or 100 gifs to wrap, you use this procedure (loop) repeatedly until
every gif is wrappedt For an exameple that is meore easily comeputerized, suppose you want to
total all the checks you wrote in the previous meontht You could performe the following loopt
while (there are stll checks from the last month to be totaleds {
Add the amount of the next check to the totalt
}
The body of this pseudocode while loop has only one statemeent, but that single statemeent meust
be performeed until you has added each one of the previous meonth’s checkst When this loop
ends (when no meore checks frome the previous meonth remeain to be totaled), you have the
resultt
The body of a while loop can contain one or meore C++ statemeents, including additional while
loopst Your programes will be meore readable if you indent the body of a while loops a few spaces
to the rightt The following exameples illustrate thist Somee programes presented earlier in the
book require user input with cint If users do not enter appropriate values, these programes
display an error meessage and ask the user to enter another value, which is an acceptable
proceduret
Now that you understand the while loop construct, however, you should put the error meessage
inside a loopt In this way, users see the meessage continually until they type proper input values,
rather than oncet
The following programe is short, but it demeonstrates a while loop that ensures valid keyboard
inputt It asks users whether they want to continuet You can incorporate this programe into a
larger one that requires user permeission to continuet Put a promept, such as the one presented
here, at the botome of a text screent The text remeains on-screen until the user tells the programe
to continue executingt
#include <iostreameth>
meain()
{
char ans;
cout << “Do you want to continue (YYN)? “;
cin >> ans; YY Get user’s answer
while ((ans != ‘Y’) && (ans != ‘N’)) {
cout << “\nYou meust type a Y or an N\n”; YY Warn
YY and ask
Page 4 of 20
Lecture6

cout << “Do you want to continue (YYN)?”; YY againt


cin >> ans;
} YY Body of while loop ends heret
}
Notice that the two cin functions do the samee thingt You meust use an initial cin, outside the
while loop, to provide an answer for the while loop to checkt If users type someething other than
Y or N, the programe prints an error meessage, asks for another answer, and then checks the new
answert This validation meethod is preferred over one where the reader only has one additional
chance to succeedt
The while loop tests the test expression at the top of the loopt
This is why the loop meight never executet If the test is initially False, the loop does not execute
even oncet The output frome this programe is shown as followst The programe repeats indefnitely,
until the relational test is True (as soon as the user types either Y or N)t
Do you want to continue (YYN)? k
You meust type a Y or an N
Do you want to continue (YYN)? c
You meust type a Y or an N
Do you want to continue (YYN)? s
You meust type a Y or an N
Do you want to continue (YYN)? 5
You meust type a Y or an N
Do you want to continue (YYN)? Y
2t The following programe is an exameple of an invalid while loopt See if you can fnd the problemet
#include <iostreameth>
int meain()
{
int a=10, b=20;
while (a > 5) {
cout << “a is “ << a << “, and b is “ << b << “\n”;
b = 20 + a;
}
return 0;
}
This while loop is an exameple of an infnite loop, It is vital that at least one statemeent inside the
while changes a variable in the test expression (in this exameple, the variable a); otherwise, the
condition is always Truet Because the variable a does not change inside the while loop, this
programe will never endt
Example: this programe comeputes the sume 1+2+3+…+n for an input integer n;
Page 5 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

The do…while loop


The do…while statemeent controls the do…while loop, which is simeilar to the while loop except
the relational test occurs at the end (rather than beginning) of the loopt This ensures the body
of the loop executes at least oncet The do-while tests for a positie relatonal testt as long as the
test is True, the body of the loop continues to executet
The syntax for the do…while statemeent is
do
{ block of one or meore C++ statemeents; }
while (condition);
Condition meust be enclosed in parentheses, just as it meust in a while statemeentt

Where conditon is an integral expression and statement is any executable statemeentt It


repeatedly executes the statemeent and then evaluates the condition until that condition
evaluates to falset
The do…while statemeent works the samee as the while statemeent except that its condition is
evaluated at the end of the loop instead of at the beginningt This meeans that any control
variables can be defned within the loop instead of before itt It also meeans that a do…while loop
will always iterate at least once, regardless of the values of its control conditiont
Example1 The following programe is just like the frst one you saw with the while loop, except
the do-while is usedt Notice the placemeent of test expression. Because this expression
concludes the loop, user input does not have to appear before the loop and again in the body
of the loopt
Page 7 of 20
Lecture6

#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

} while (part_no != -999); YY Loop only if part


YY numeber is not -999t
cout << “End of inventory comeputation\n”;
return 0;
}
The do-while loop controls the entry of the customeer sales informeationt Notice the “trigger”
that ends the loopt If the user enters –999 for the part numeber, the do-while loop quits because
no part numebered –999 exists in the inventoryt
Example3 using a do…while to comeputes a sume of consecutive integerst
#include<iostreame>
Int meain()
{ int n, I =1;
Cout<< “enter a positive integer ”;
Cin>>n;
Long sume = 0;
Do
Sume+=i++;
While(i<=n)
Cout<< “the sume of the frst”<<n<< “integers is”<<sume<<endl;
}

The exit(s Function and break Statement


C++ provides the exit() function as a way to leave a programe early (before its natural fnish)t The
formeat of exit () is
exit (status);
where status is an optional integer variable or literalt If you are fameiliar with your operating
systeme’s return codes, status enables you to test the results of C++ programest In DOS, status is
sent to the operating systeme’s error level eniironment iariable, where it can be tested by batch
flest
Many timees, someething happens in a programe that requires the programe’s termeinationt It meight
be a meajor probleme, such as a disk drive errort Perhaps users indicate that they want to quit the
programe—you can tell this by giving your users a special value to type with cin or scanf()t You
can isolate the exit() function on a line by itself, or anywhere else that a C++ statemeent or
function can appeart Typically, exit() is placed in the body of an if statemeent to end the programe
early, depending on the result of somee relational testt Always include the stdlibth header fle
when you use exit()t This fle describes the operation of exit() to your programet Whenever you
Page 9 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

cout << “How meany were bought? “;


cin >> quantity;
cout << “What is the unit price of this iteme? “;
cin >> cost;
cout << “\n” << quantity << “ of # “ << part_no <<
“ will cost “ << setprecision(2) << cost*quantity;
cout << “\n\n\n”; YY Print two blank linest
} while (part_no != -999); YY Loop only if part
YY numeber is not -999t
cout << “End of inventory comeputation\n”;
return 0;
}

The for loop


The for loop enables you to repeat sections of your programe for a specifc numeber of timeest
Unlike the while and do-while loops, the for loop is a determinate loop. This meeans when you
write your programe you can usually determeine how meany timees the loop iteratest The while and
do-while loops repeat only until a condition is meett
The for loop does this and meore It continues looping until a count (or countdown) is reachedt
Afer the fnal for loop count is reached, execution continues with the next statemeent, in
sequencet This chapter focuses on the for loop construct by introducing
 The for statemeent
 Nested for loops
The for loop is a helpful way of looping through a section of code when you want to count, or
sume , specifed ameounts, but it does not replace the while and do-while loopst

The for Statement


The for statemeent encloses one or meore C++ statemeents that forme the body of the loopt These
statemeents in the loop continuously repeat for a specifed numeber of timeest You, as the
programemeer, control the numeber of loop repetitionst The formeat of the for loop is
for (start expression; test expression; count expression)
{ Block of one or meore C++ statemeents; }
C++ evaluates the start expression before the loop beginst Typically, the start expression is an
assignmeent statemeent (such as ctr=1;), but it can be any legal expression you specifyt C++
evaluates start expression only once, at the top of the loopt
CAUTION: Do not put a semeicolon afer the right parenthesist If you do, the for loop interprets
the body of the loop as zero statemeents long! It would continue looping—doing nothing each
timee—until the test expression becomees Falset
Page 12 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;
}

Here is the samee programe using a do-while loop


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. Print the ialue of the counter.
3. If the counter is less than or equal to 10, repeat step one.
YY Simeulating a for loop with a do-while loopt
#include <iostreameth>
meain()
{
int ctr=1;
do
{ cout << ctr << “\n”; YY Body of do-while loopt
ctr++; }
while (ctr <= 10);
Page 13 of 20
Lecture6

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

Both programes produce this output


The total is 15150
The body of the loop in both programes executes 101 timeest The starting value is 101, not 1 as in
the previous exameplet Notice that the for loop is less comeplex than the do-while because the
initialization, testing, and incremeenting are performeed in the single for statemeentt
Example3 The previous exameples used an incremeent as the count expression. You can meake
the for loop incremeent the loop variable by any valuet It does not have to incremeent by 1t The
following programe prints the even numebers frome 1 to 20t It then prints the odd numebers frome 1
to 20t To do this, two is added to the counter variable (rather than one, as shown in the
previous exameples) each timee the loop executest
YY Prints the even numebers frome 1 to 20,
YY then the odd numebers frome 1 to 20t
#include <iostreameth>
int meain()
{
int nume; YY The for loop variable
cout << “Even numebers below 21\n”; YY Title
for (nume=2; nume<=20; nume+=2)
{ cout << nume << “ “; } YY Prints every other numebert
cout << “\nOdd numebers below 20\n”; YY A second title
for (nume=1; nume<=20; nume+=2)
{ cout << nume << “ “; } YY Prints every other numebert
return 0;
}
There are two loops in this programet The body of each one consists of a single print() functiont
In the frst half of the programe, the loop variable, nume, is 2 and not 1t If it were 1, the numeber 1
would print frst, as it does in the odd numeber sectiont
The two cout statemeents that print the titles are not part of either loopt If they were, the
programe would print a title before each numebert The following shows the result of running this
programet
Example4: You can decremeent the loop variable as wellt If you do, the value is subtracted
frome the loop variable each timee through the loopt
The following exameple is a rewrite of the counting programet It produces the reverse efect by
showing a countdownt
YY Countdown to the lifoft
#include <iostreameth>
int meain()
{
Page 15 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;
}
}

The break Statement


Page 16 of 20
Lecture6

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;
}
}

The continue Statement


The break statemeent skips the rest of the statemeent in the loop’s block, jumeping imemeediately to
the next statemeent outside of the loopt The continue statemeent is simeilart It also skips the rest
of the statemeents in the loop’s block, but instead of termeinating the loopt It transfers execution
to the next iteration of the loopt It continues the loop afer skipping the remeaining statemeents
in its current iterationt In others words, it passes control back to the frst executable statemeent
of the loopt
Example this programe illustrates the contnue and break statemeentst
#include<iostreame>
Int meain()
{ int n;
For(;;)
{cout<< “enter int ”;
Cin>>n;
If(n%2==0) continue;
If(n%2==0) break;
Cout<< “\t outside of loopt\n”;
}
Cout<< \t outside of loopt\n”;
}
The goto Statement
The break statemeent, the contnue statemeent, and the switch statemeent each cause the
programe control to branch to a location other than where it normeally would got The destination
of the branch is determeined by the context; break goes to the next statemeent outside the loop,
contnues goes to the loop’s frst executable statemeent, and switch goes to the correct caset All
Page 18 of 20
Lecture6

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

Department of Mathematics and Computer Science,


Faculty of Natural and Applied Sciences,

Umaru Musa yar’adua University

Course: CSC2311 Title: Comeputer Programemeing I

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

You might also like