Basic structures: Loops
- while-statements:
Check this to see how it works:
...
int n = 0;
int sum = 0;
while (n<101) {
sum += n*n;
cout<<"For n = "<<n<<" the sum of all squares
equals : "<<sum<<endl;
n++;
}
...
|
I guess it is obvious, what this aims at: As long as the
statement within the round brackets is true (i.e. as long as n
did not reach 101), the body will be executed.
You could do that interactivley as well, via
...
double x;
double sum = 0.;
while (cin>>x) {
sum += x;
}
cout<<"Sum = "<<sum<<endl;
...
|
This loop terminates only, when the end-of-file statement,
<CTRL-D> is entered.
- do-while-statements:
They are used, if you want to execute the body at least once.
Check this to see how it works:
...
double x = 5.;
double sum = 0.;
do {
sum += x;
} while (cin>> x);
cout<<"Sum = "<<sum<<endl;
...
|
- for-statements:
Check this to see how it works:
...
int sum = 0;
for (int n=0;n<101;n++) {
sum += n*n;
cout<<"For n = "<<n<<" the sum of all squares
equals : "<<sum<<endl;
}
...
|
It does basically the same as the example above, adding up
squares of integers between 0 and 100. The only difference is the
loop. The syntax for the for-loop is
for (counter initialization ; loop-termination ; counter modification)
{ body } |
I would like to stress here that the counter declared in the
statement will be deleted after termination of the loop. You'll
keep the counter only, if you declared it outside (before) the
loop.
- Infinite loops:
The simplest way to ralize infinite loops is via
with no initialization whatsoever.
- Some steering inside loops can be done with two commands:
The break-statement causes an immediate leave
at the very same place, i.e. the rest of the body won't be
executed.
...
for (;;) {
body;
if (statement==true) break;
more body;
}
...
|
[prev]
[top]
[next]
|