03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

36 CHAPTER 2. <strong>C++</strong> BASICS<br />

eps/= 2.0;<br />

} while (eps > 0.0001);<br />

The loop is per<strong>for</strong>med at least one time — even with an extremely small value <strong>for</strong> eps in our<br />

example. The difference between a while-loop and a do-while-loop is irrelevant to most scientific<br />

software. Only loops with very few iterations and with extremely strong impact on the overall<br />

per<strong>for</strong>mance might matter because a do-while-loop per<strong>for</strong>ms one comparison and one jump less.<br />

2.5.4 For Loop<br />

The most common loop in C ++ is the <strong>for</strong>-loop. As simple example we like to add two vectors 15<br />

and print the result afterward:<br />

double v[3], w[]= {2., 4., 6.}, x[]= {6., 5., 4};<br />

<strong>for</strong> (int i= 0; i < 3; i++)<br />

v[i] = w[i] + x[i];<br />

<strong>for</strong> (int i= 0; i < 3; i++)<br />

cout ≪ ”v[” ≪ i ≪ ”] = ” ≪ v[i] ≪ ’\n’;<br />

The loop head consists of three components:<br />

• The initialization;<br />

• A Continuation criterion; and<br />

• A step operation.<br />

The example above is typical <strong>for</strong> a <strong>for</strong>-loop. In the initialization, one typically declares a new<br />

variable and initializes it to 0 because this is the start index of most indexed data structures.<br />

The condition usually tests if the loop index is smaller than a certain size and the last operation<br />

typically increments the loop index.<br />

It is a very popular beginners’ mistake to write conditions like “i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!