• No results found

The for statement

In document Book on C++ (Page 113-117)

Suppose you want to print a table of ubes of the integers from 1 to 100. You would solve

this problem using the following pie e of ode.

int i = 1;

repeat(100){

out << i << `` `` << i*i*i << endl;

i = i + 1;

}

The variable i plays a entral role in this ode. All iterations of the repeat are identi al,

ex ept for the value of i. Further,i hanges from one iteration of the loopto anotherin a

very uniform manner, in the above ase it is in remented by 1 at the end of ea h iteration.

This general ode pattern: that there is a ertain variable whi h takes a di erent value in

ea h iteration and the value determines how the iteration will exe ute, is very ommon.

Be ause of this, the designers of C++ (and other programminglanguages) have provided a

me hanismforexpressingthispatternvery ompa tly. Thisme hanismistheforstatement.

Usingthe forstatement, we an express the above ode as follows.

for(int i=1; i <= 100; i = i + 1)

out << i << ` ` << i*i*i << endl;

This ode isequivalent tothe repeat loop above. Exa tly why this is the ase willbe ome

apparent when weunderstand the for statementin itsgeneral form:

for(initialization ; ondition ; update) body

Inthis,initializationandin rementarerequiredtobeexpressions,typi allyassignment

expressions. As you mightremember, an assignment expression is simplyassignments to a

variable without in luding the semi olon, e.g. i = i + 1. Further we may in lude the

de nition alongwiththe assignmente.g. int i = 0. Asyoumightexpe t onditionmust

bea booleanexpression. Thelastpart, bodymaybeanyC++ statement,in ludingablo k

statement. Inour exampleabove,the body onsisted ofthestatement out << i << `` ``

<< i*i*i << endl;.

The exe ution of a for statement starts with the exe ution of initialization. Then

ondition is evaluated. If ondition is false, then the statement terminates. If the

ondition is true, the statements in the body are exe uted followed by the update. We

repeatthispro essagainstartingfromevaluationof ondition. Thisisshownasa ow hart

in Figure6.4.

Notethatnone ofthe eldsinitialization, ondition, updateorbody anbeempty.

If the ondition isempty, thenit is taken as true.

The variable named in initialization and update is ustomarily alled the ontrol

variable of the loop. As you might expe t, initialization assigns an initialvalue to the

ontrolvariable,andtheupdatesayshowthevariablemust hangefromoneiterationtothe

next. As you an see, in our ube table example, the update indeed adds 1 to the ontrol

variable.

True

Next statement in the program

Condition

False

Body

Update

Initialization

Previous statement in the program

6.6.1 Variables de ned in initialization

As mentioned above, the initialization an ontain avariable de nition, asinour ube-

tableprogram. Thisvariableis reated duringinitialization, andisavailablethroughout

the exe ution of the forstatement, i.e. during allthe iterations. It isdestroyed only when

theexe utionofthe forstatementends. Thussu havariable annotreferredtooutsidethe

for. If the value of the variable is useful after the for exe ution is over, then the variable

should be de ned before the forstatement, and only initializedininitialization.

What if I de ne a variable i in initialization, but an i has already been de ned

earlier? So onsider the following ode.

int i=10;

for(int i=1; i<=100; i = i + 1) out << i*i*i << endl;

out << i << endl;

Inthis ase,wewillhaveshadowing,asdis ussedinSe tion3.8.3. Inparti ulartheide ned

inthe rst statementwillbe di erent fromthe one de ned inthe forstatement,but it will

be the same as the one in the last statement! Thus the for statement will print atable of

ubes asbefore. The laststatement will print 10, be ause the variable i referred to init is

the variablede ned instatement 1.

6.6.2 Break and ontinue

Ifabreak statement isen ountered duringthe exe utionof body,then the exe utionof the

forstatement nishes. This isexa tly asin the while statement.

If the ontinue statement is en ountered, then the exe ution of the urrent iterationis

terminated, as in the while statement. However, before pro eeding to the next iteration,

the update is exe uted. After that ontrol ontinues with the next iteration, starting with

he king ondition and soon.

6.6.3 Style issue

Youmay wellask: why should we learn a new statement if it is reallynot needed? Indeed,

anyprogramthatusesaforstatement anberewrittenusingawhile,withafewadditional

variables and assignments.

The reason on erns style. It is mu h the same as why we speak loudly on ertain

o asionsandsoftly onothers: oursoftness/loudness helpthe listenerunderstand ourintent

in addition to our words. Likewise, when I write a for statement, it is very lear to the

reader that I am using a ertain ommon programming idiom in whi h there is a ontrol

variablewhi hisinitializedatthebeginningandin rementedattheend ofea hiteration. If

I useeitherawhilestatementorarepeatstatement,thenthe readerdoesnot immediately

6.6.4 Primality

Our primality programof Se tion 6.1.2 does indeed have a ontrol variable: the andidate

divisor i. Hen e it isni ely writtenas afor loop.

main_program{

int x; in >> x;

bool found = false;

for(int i=2; (i < x) && !found; i++)

found = found || (x % i) == 0;

if(found) out << "Composite.\n";

else out << "Prime.\n";

}

6.6.5 Natural log by numeri al integration

For any real x > 0, its natural logarithm lnx is de ned as the number y su h that e y

= x

where e is Euler's number (e2:71828). We onsider howto ompute lnx given x. There

are many ways of doingthis, we onsider amethodbased onthe following relationship:

lnx= Z x 1 1 u du

In other words, lnx is the area under the urve y =1=u between u =1 and u = x. So we

an nd lnx if we an nd the area!

Well,we annot ompute theareaexa tly,but we anapproximateit. Ingeneralsuppose

we wish to approximate the area undera urve f(u)=1=u fromsome p toq. Then we an

getanoverestimatetothisareaby onsideringtheareaofthesmallestaxesparallelre tangle

that overs it. The height of this re tangle is f(p) (be ause f is non-in reasing) and the

width is q p. Thus our required approximation (over estimate) is (q p)f(p). This is

the strategy we will use, after dividing the required area into n verti al strips. Sin e the

urve goesfrom1 tox the width ofea h strip isw=(x 1)=n. Theith strip extendsfrom

u=1+iwtou=1+(i+1)w, wherewe will onsideri toberangingbetween 0andn 1as

is ustomary, rather than between 1 and n. The height of the re tangle overing this strip

is f(1+iw)and hen e the area is wf(1+iw). Thus the total area of the re tangles is:

n 1 X i=0 wf(1+iw)= n 1 X i=0 w 1 1+iw

But evaluation of this formula is easily translated into a program! In fa t i will naturally

serve as a ontrolvariable for our forloop. We willtake ea h su essive term of the series

andadditintoavariableareawhi hwe rstsetto0. Thefollowingisthe ompleteprogram.

int n; in >> n; // number of re tangles to use

float w = (x-1)/n; // width of ea h re tangle

float area = 0; // will ontain ln(x) at the end.

for(int i=0; i < n; i++)

area = area + w /(1+i*w);

out << "Natural log, from integral: "<< area << endl;

}

We note that C++ already provides you a single ommand log whi h an be invoked as

log(x) and it returns the value of the natural logarithm. This ommand uses some ode

probably more sophisti ated than what we have written above, and it guarantees that the

answeritreturnswillbe orre ttoasmany bitsasyourrepresentation(say24bits in luding

sign for float and 53 bits in ludingsign for double). Sowe an use the ommand log to

he k how good our answer is. To dothis simplyadd the line

out << "Natural log, from built-in fun tion: "<< log(x) << endl;

beforethe end of the programgiven above. This will auseour answerto beprinted aswell

as the true answer, and so we an ompare.

It isworth pointing out that there are two kinds of errors in a omputation su h as the

one above. The rst is the error produ ed by the mathemati al approximation we use to

al ulate a ertain quantity. For the natural log, this orresponds to the error that arises

be ause ofapproximatingthe area underthe urve by the area ofthe re tangles. This error

will redu e as we in rease n, the number of re tangles. The se ond kind of error arises

be auseona omputernumbersarerepresented onlytoa xed pre ision. Thus, wewillhave

error be ause our al ulation of the area of ea hre tangle willitself not be exa t. If we use

float representation then every number is orre t only to a pre ision of about 7 digits. If

youadd n numbers ea h ontainingan (additive)error of, then the errorinthe sum ould

be ome n, assuming all errors were in the same dire tion. Even assuming that the errors

arerandom,itispossibletoshowthattheerrorwillbeproportionalto p

n. Inotherwords,

ifyouadd10000numbers, ea hwithanerrorofabout10 7

,yourtotalerrorislikelytohave

risen toabout10 5

(if not to10 3

). Thus, weshould hoose n large,but not toolarge. The

exer ises askyou toexperiment to nd a good hoi e. Note that you an redu ethe se ond

kindof errorby representing the numbers indouble ratherthan float.

Anothervariationonthemethodistoapproximatetheareaunderthe urvebyasequen e

of trapeziums. This indeed helps. This method, and the more intriguing method based on

Simpson's rule are leftto the exer ises.

Later we will see other methods of omputing mathemati al fun tions (in luding the

naturallog)whi hwillbebasedon ompletelydi erentideas. TheC++supplied ommand

loglikely uses one of these other methods.

In document Book on C++ (Page 113-117)

Related documents