• Nem Talált Eredményt

Iteration structures (loops)

4. Control program structures

4.3. Iteration structures (loops)

char op;

double a, b, c;

cout<<"expression :";

cin >>a>>op>>b;

cout <<a<<op<<b<<'='<<c<<endl;

return 0;

}

The next example demonstrates how to associate the same code part to more cases. In the source code, the case labels corresponding to cases 'y' and 'Y', as well as 'n' and 'N' were placed one after the other in the switch

cout<<"The response [Y/N]?";

char response=cin.get();

In programming, program structures ensuring automatic repetitions of statements are called iterations or loops.

In C++, loop statements repeat a given statement in the function of the repetition condition until the condition is true.

while (condition) statement

for (initialisationopt; conditionopt; increment_expressionopt) statement dostatementwhile (condition)

In the case of for statement, opt means that the corresponding expressions are optional.

Loops can be classified on the basis of the place where control conditions are processed. Loops in which the control condition is evaluated before statements are executed are called pre-test loops. Any statement in the loop is executed if and only if the condition is true. Pre-test loops of C++ are while and for.

On the contrary, the statements of do loops are always executed at least once since control condition is evaluated after the execution of the statement – post-test loops.

In all three cases, correctly organized loops terminate if the control condition becomes false (0). However, there are times we create intentionally loops the control condition of which never becomes false. These loops are called infinite loops :

for (;;) statement;

while (true) statement;

do statement while (true);

Loops (even infinite loops) can be exited before the control condition becomes false. For that purpose, C++

offers statements like break, return or goto, which points to a place outside the body of the loop. Certain statements of the body of the loop can be bypass by using continue. The continue makes the program continue with executing the next iteration of the loop.

I.10. ábra - Logical representation of while loops

4.3.1. while loops

while loops repeat statements belonging to them (the body of the loop), while the value of the examined condition is true (not 0). Evaluation of the condition always precedes the execution of the statement. The process of the functioning of while loops can be traced in I.10. ábra - Logical representation of while loops.

while (condition)

statement

The next example code determines the sum of the first n natural numbers:

#include <iostream>

using namespace std;

int main() {

int n = 2012;

cout<<"The sum of the first "<<n<<" natural number ";

unsigned long sum = 0;

while (n>0) { sum += n;

n--;

}

cout<<"is: "<<sum<<endl;

}

Of course, the while loop of the previous example can be simplified but this step decreases its readability:

while (n>0) { sum += n;

n--;

}

while (n>0) sum += n--;

while (sum += n--, n);

C++ makes it possible to place variable declarations anywhere in a program code. The only condition is that all variables have to be declared (defined) before they are used. In certain cases, variables can be defined in loop statement header in case they are immediately initialized, e.g. by random numbers.

The while loop of the following example code does not terminate until it reaches the first number, divisible by 10. In the code, statement

srand((unsigned)time(NULL));

initializes the random number generator with the actual time, therefore every execution result in a new number sequence. Random numbers are provided by function rand () in the value range between 0 and RAND_MAX (32767).

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main() {

srand((unsigned)time(NULL));

while (int n = rand()%10) cout<< n<< endl;

}

It should be noted that variable n defined in that way can be accessed within the while loop, thus it is local only with respect to the while loop.

4.3.2. for loops

In general, for statements are used if the statements within its body should be executed in a given number of times (I.11. ábra - Logical representation of for loops). In the general form of for statements, the role of each expression is also mentioned:

for (initialization; condition; increment) statement

In reality, for statements are the specialized versions of while statements, so the above for loop can perfectly be transformed into a while loop:

initialization;

while (condition) { statement;

increment;

}

I.11. ábra - Logical representation of for loops

The following program represents a for loop and does the same as the above one: determines the sum of natural numbers. It is obvious at first sight that this solution of the problem is much more readable and simpler:

#include <iostream>

using namespace std;

int main() {

unsigned long sum;

int i, n = 2012;

cout<<"The sum of the first "<<n<<" natural number ";

for (i=1, sum=0 ; i<=n ; i++) sum += i;

cout<<"is: "<<sum<<endl;

}

There is only one expression-statement in the body of the loop in the example, so the for loop can be condensed in the following way:

for (i=1, sum=0 ; i<=n ; sum += i, i++) ; or

for (i=1, sum=0 ; i<=n ; sum += i++) ;

Loops can be nested in one another, since their body can contain other loop statements. The following example uses nested loops to print a pyramid of a given size. In all three loops, loop variable is made local:

#include <iostream>

using namespace std;

int main () {

const int maxn = 12;

for (int i=0; i<maxn; i++) { for (int j=0; j<maxn-i; j++) { cout <<" ";

}

for (int j=0; j<i; j++) { cout <<"* ";

} cout << endl;

} }

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

4.3.3. do-while loops

In do-while loops, evaluation of the condition takes place after the first execution of the body of the loop (I.12.

ábra - Logical representation of do-while loops), so the loop body is always executed at least once.

I.12. ábra - Logical representation of do-while loops

do

statement while (condition);

As a first step, let's create the version of the program computing the sum of natural numbers with a do-while loop.

#include <iostream>

using namespace std;

int main() {

int n = 2012;

cout<<"The sum of the first "<<n<<" natural number ";

unsigned long sum = 0;

do {

sum += n;

n--;

} while (n>0);

cout<<"is: "<<sum<<endl;

}

With the help of the following loop, let's read an integer number between 2 and 100 from the input and verify it:

int m =0;

do {

cout<<"Enter an integer number betwwen 2 and 100: ";

cin >> m;

} while (m < 2 || m > 100);

The last example calculates the power of a number with an integer exponent:

#include <iostream>

#include <cstdlib>

A frequent programming error is to terminate loop headers with a semicolon. Let's see some attempts to print odd integer numbers between 1 and 10.

int i = 1;

There are cases when the regular functioning of a loop has to be directly intervened into. For example, if a loop has to be exited if a given condition is fulfilled. A simple solution for that is the break statement, which interrupts the execution of the nearest while, for and do-while statements and control passes to the first statement following the interrupted loop.

The following while loop is interrupted if the lowest common multiple of two integer numbers is found:

#include <iostream>

}

cout << "The lowest common multiple is: " << lcm << endl;

}

The usage of break can be avoided if the condition of the if statement corresponding to it can be integrated into the condition of the loop, that will become more complicated by that step:

while (lcm<=a*b && !(lcm % a == 0 && lcm % b == 0)) { lcm++;

}

If break statement is used in nested loops in an inner loop, it is only that inner loop that is exited. The following example prints prime numbers between 2 and maxn. The reason for exiting the loop is provided by a logical flag, by the variable (prime), to the outer loop:

#include <iostream>

cout << num << " is a prime number" << endl;

} }

If the task is to find the first Pythagorean triple in a given interval, two for loops have to be exited if a match is found. Then the simplest solution is to use the flag (found):

#include <iostream> statements placed after continue are not executed.

In the case of while and do-while loops, the next iteration begins with evaluating again the condition. However, in for loops, the processing of the condition is preceded by the increment.

In the following example, with the help of continue, it was realized that only the numbers divisible by 7 or 12 are printed out in the loop incrementing from 1 to maxn by one:

#include <iostream>

using namespace std;

int main(){

const int maxn = 123;

for (int i = 1; i <= maxn; i++) { if ((i % 7 != 0) && (i % 12 != 0)) continue;

cout<<i<<endl;

} }

It is a bad practice in programming to use often break and continue statements. It has to be always rethought if given program structures can be solved without jump statements. In the preceding example, this can easily be done by inverting the condition of the if statement:

for (int i = 1; i <= maxn; i++) { if ((i % 7 == 0) || (i % 12 == 0)) cout<<i<<endl;

}