• No results found

Data Collection

4.2 Repetition Structures

Figure 4.1 Flowchart for repetition structure.

Loops are used to implement repetition structures. C++ contains three different loop structures: the while loop, the do/while loop, and the for loop. C++ also supports the use of two additional statements with loops to modify their performance: the break statement (which we used with the switch statement) and the continue statement. In the remaining sections of this chapter, we present these loop structures and develop example programs that illustrate the use of each of these repetition structures.

4.2 Repetition Structures

The most general looping structure in C++ is the while loop.

Section 4.2 Repetition Structures 141

whileLoop

The general form of a while loop follows:

while (condition) statement;

whileStatement: The while statement allows a program to repeatedly execute a block of statements while the specified condition is true.

Syntax:

while(condition) while(condition)

statement; {

statement block }

Example:

while(!isspace(ch)) while(x > y)

{ {

cin.get(ch); ++c1;

} --x;

}

The condition is evaluated before the statements within the loop are executed. If the condition is false, the statement block is skipped, and execution continues with the statement following the while loop. If the condition is true, then the statement block is executed, and the condi-tion is evaluated again. This repeticondi-tion continues until the condicondi-tion is false as indicated in the flowchart in Figure 4.2.

Statement Block

Statement

Condition False

True

Figure 4.2 Flowchart for while statement.

142 Chapter 4 Control Structures: Repetition

Program chapter4_1 uses a while loop to implement the flowchart in Figure 4.1.

The program, and the output generated by the program, is provided below.

/*****************************************************/

/* Program chapter4_1 */

/* This program computes ands prints a velocity */

/* for time values in the range of: 0 <= time <= 10 */

#include<iostream> //required for cout using namespace std;

int main() {

// Declare and initialize objects

const double V0(0.0); //initial velocity m/s

const double A(2.537); //constant acceleration m/s*s double time, velocity;

//print heading

cout << " Time, s\t\tVelocity, m/s\n" ; time = 0;

while(time <= 10.0) {

velocity = A*time + V0;

cout << time << "\t\t" << velocity << endl;

++time;

The statements that form a loop must modify objects that are used in the condition;

otherwise, the value of the condition will never change, and we will either never execute the

Section 4.2 Repetition Structures 143 statements in the loop or we will never be able to exit the loop. An infinite loop is generated if the condition in a while loop is always true.

infinite loop

Most systems have a defined limit on the amount of time that can be used by a program, and will generate an execution error when this limit is exceeded. Other systems require that the user enter a special sequence of characters, such as the control key followed by the character c (abbreviated as <cntrl> c) to stop or abort the execution of a program. Nearly everyone eventually writes a program that inadvertently contains an infinite loop, so be sure you know the special characters to abort the execution of a program for your system.

Here, we would like to present two debugging suggestions that are useful when trying to find errors in programs that contain loops. When compiling longer programs, it is not uncommon to have a large number of compiler errors.Rather than trying to correct all errors after compiling, we suggest that you recompile your program after correcting one or two obvious syntax errors.One error will often generate several error messages. Some of these error messages may describe errors that are not in your program, but were printed because the original error confused the compiler.

The second debugging suggestion relates to errors inside a loop. When you want to determine whether the steps in a loop are working the way that you want, include cout statements in the loop to provide a memory snapshot of key objects each time the loop is executed. Then, if there is an error, you have much of the information that you need to de-termine what is causing the error. Remember to use the endl manipulator in your cout statements to be sure that the output buffer is printed to the screen after each debugging statement.

The following pseudocode and program use a while loop to generate a conversion table for converting degrees to radians. The degree values start at 0 degrees, increment by 10 degrees, and go through 360 degrees.

Refinement in Pseudocode main: set degrees to zero

while degrees <= 360

/* This program prints a degree-to-radian table */

/* using a while loop structure. */

#include<iostream> //Required for cout

#include<iomanip> //Required for setw() using namespace std;

const double PI = 3.141593;

144 Chapter 4 Control Structures: Repetition int main()

{

// Declare and initialize objects.

int degrees(0);

double radians;

// Set formats.

cout.setf(ios::fixed);

cout.precision(6);

// Print radians and degrees in a loop.

cout << "Degrees to Radians \n";

while (degrees <= 360) {

radians = degrees*PI/180;

cout << setw(6) << degrees << setw(10) << radians << endl;

degrees += 10;

The first few lines of output from the program follow:

Degrees to Radians 0 0.000000 10 0.174533 20 0.349066

. ...

To further illustrate the while loop, we provide a program trace and memory snapshot for the first three iterations of the loop. Notice that the value of degrees is printed inside the while loop before the value is incremented by 10.

Program Trace main()

Step 1: int degrees(0);

Step 2: double radians;

Step 3: while(degrees <= 360) {

radians = degrees*PI/180;

cout << setw(6) << degrees << setw(10)

<< radians << endl;

degrees += 10;

}

Section 4.2 Repetition Structures 145 Memory Snapshot

main()

Step 1: integer degrees 0

Step 2: double radians ?

Step 3:

End first iteration

integer degrees 10 double radians 0.0 End second iteration

integer degrees 20 double radians 0.174533 End third iteration

integer degrees 30

· · · double radians 0.349066

We see that degrees is initialized to zero in the type declaration statement, thus the condition degrees <= 360 is true the first time it is tested and the statement block that defines the whileloop is executed. Inside the statement block the first line of the conversion table is printed, and degrees is incremented by 10. When the end of the statement block is encoun-tered, control branches back to the condition and it is tested a second time. Again the condition is true and the statement block is executed, this time with a value of 10 for degrees. This repetition continues until the value of degrees reaches 370. Since 370 is greater than 360, the condition is false and the while loop terminates. Termination of the while loop results in control branching down to the first statement following the statement block, the return 0; statement in this case. Note that the directed arrows in the flowchart in Figure 4.2; illustrate the branching associated with the while loop.

do/whileLoop

The do/while loop is similar to the while loop, except that the condition is tested at the end of the loop instead of at the beginning of the loop, as illustrated in Figure 4.3. Testing the condition at the end of the loop ensures that the do/while loop is always executed at least once; a while loop will not be executed at all if the condition is initially false. The general form of the do/while loop is as follows:

do {

statements;

} while (condition);

146 Chapter 4 Control Structures: Repetition

Statement Block

Statement Condition True

False

Figure 4.3 Flowchart for do/while.

do/while Statement: The do/while statement allows a program to execute a block of statements repeatedly while the specified condition is true. The statement or statement block in a do/while statement will always be executed at least once.

Syntax:

do do

statement; {

while (condition); statement block } while(condition);

Example:

do do

cin.get(ch); {

while (ch != '\n') v = a*t + v0;

cout << t << " " << v << endl;

t += 0.5;

} while(t<10);

The following pseudocode and program print the degree-to-radian conversion table us-ing a do/while loop instead of a while loop:

Refinement in Pseudocode main: set degrees to zero

do

convert degrees to radians print degrees, radians add 10 to degrees while degrees <= 360

Section 4.2 Repetition Structures 147

/*---*/

/* Program chapter4_3 */

/* */

/* This program prints a degree-to-radian table */

/* using a do-while loop structure. */

#include<iostream> //Required for cout

#include<iomanip> //Required for setw() const double PI = 3.141593;

int main() {

// Declare and initialize objects.

int degrees(0);

double radians;

// Set formats.

cout.setf(ios::fixed);

cout.precision(6);

// Print degrees and radians in a loop.

cout << "Degrees to Radians \n";

do {

radians = degrees*PI/180;

cout << setw(6) << degrees << setw(10) << radians << endl;

degrees += 10;

} while (degrees <= 360);

// Exit program.

return 0;

}

/*---*/

Practice!

For problems 1 through 4, show what is printed to standard output. If the cout statement is not executed, please explain why.

1. int count(1); 2. int count(1);

while(count < 5) while(count < 5)

{ {

++count; -count;

} }

cout << count << endl; cout << count << endl;

148 Chapter 4 Control Structures: Repetition

Practice!

3. int count(10); 4. int count(0);

while(count >= 0) do

{ {

count -= 2; count = count +3;

} } while (count >=10)

cout << count << endl; cout << count << endl;

Modify!

1. Modify program chapter4_1 by replacing the while loop with a do/while loop. Verify that the output is the same.

2. Modify program chapter4_1 by adding the necessary C++ statements to prompt the user to enter the values for initial velocity and constant acceleration. Use these values to compute and print velocity.

3. Modify program chapter4_1 by adding the necessary C++ statements to prompt the user to enter the initial and final values for time. Use these values to compute and print velocity.

forLoop

Many programs require loops that are based on the value of a counter that increments (or decrements) by the same amount each time through the loop. When the counter reaches a specified value, we then want to exit the loop. This type of loop can be implemented as a whileloop, but it can also be easily implemented with the for loop. The general form of the for loop is as follows:

for (expression_1; expression_2; expression_3) {

statements;

}

The first expression is used to initialize the loop-control variable, expression_2 specifies loop-control

variable the condition that must be true to continue the loop repetition, and expression_3 spec-ifies the modification to the loop-control object that follows the execution of the statement block.

Note that expression_1 is executed one time only. The condition, expression_2 is tested 1 to (n+ 1) times and expression_3 is executed 0 to n times, where n is the number of times the statement block is executed. The syntax box is provided below, and a flowchart is provided in Figure 4.4.

Section 4.2 Repetition Structures 149

Condition

True

Statement Block

False Initialize

loop variable Modify loop

variable

Figure 4.4 Flowchart for simple for statement.

forStatement: The for statement allows a program to execute a block of statements repeatedly based on the value of a counter that is modified by the same amount each time through the loop.

Syntax:

for (initialization; condition;) for (initialization; condition;)

modification) modification)

statement; {

statement block }

Example:

for (int count=1; count<=10; for(int i=counter; i>0; --i)

++count) {

sum = sum + count; cin >> degrees;

radians = degrees * PI/180 cout << degress_<< " "

<<_radians << endl;

}

If, for example, we want to execute a loop 10 times, with the value of the variable k going from 1 to 10 in increments of 1, we could use the following for loop structure:

for (int k=1; k<=10; ++k) {

statements;

}

150 Chapter 4 Control Structures: Repetition

In this example, the variable k is declared and initialized in the the first expression and can be referenced inside the statement block of the for loop.

If we want to execute a loop with the value of the object n going from 20 to 0 in increments of−2, we could use this loop structure:

for (n=20; n>=0; n-=2) {

statements;

}

In this form, the variable n is assigned an initial value in the first expression, but must be declared before the for statement. The for loop could also have been written in the form for (n=20; n>=0; n=n-2)

{

statements;

}

Both forms are valid, but the abbreviated form for expression_3 is commonly used be-cause it is shorter.

The following expression computes the number of times that a for loop will be executed:

floor

final value− initial value increment

+ 1.

If this value is negative, the loop is not executed. Thus, if a for statement has the structure for (int k=5; k<=83; k+=4)

{

statements;

}

then it would be executed the following number of times:

floor be executed with the value of 85 because the loop condition is not true when k is equal to 85.

Consider the following set of nested for statements:

nested for

The outer for loop will be executed three times. The inner for loop will be executed twice each time the outer for loop is executed. Thus, the variable count will be incremented six times.

Section 4.2 Repetition Structures 151 The following pseudocode and program print the degree-to-radian conversion table shown earlier with a while loop, now modified to use a for loop. Note that the pseudocode for the while loop solution to this problem and the pseudocode for the for loop solution to this problem are identical.

Refinement in Pseudocode main: set degrees to zero

while degrees <= 360

/* This program prints a degree-to-radian table */

/* using a for loop structure. */

#include<iostream> // Required for setw()

#include<iomanip> // Required for cout using namespace std;

const double PI = 3.141593;

int main()

// Print degrees and radians in a loop.

cout << "Degrees to Radians \n";

for (int degrees=0; degrees<=360; degrees+=10) {

radians = degrees*PI/180;

cout << setw(6) << degrees << setw(10) << radians << endl;

}

// Exit program.

return 0;

}

/*---*/

The initialization and modification expressions in a for loop can contain more than one statement, as shown in this for statement that initializes and updates two objects in the loop:

152 Chapter 4 Control Structures: Repetition

for (int k=1, j=5; k<=10; k++, j++) {

sum_1 += k;

sum_2 += j;

}

When more than one statement is used, they are separated by commas, and are executed from left to right. This comma operator is executed last in operator precedence.

comma operator

Practice!

For problems 1 through 5, determine the number of times that the for loop is executed.

1. for (int k=3; k<=20; k++) {

statements;

}

2. for (int k=3; k<=20; ++k) {

statements;

}

3. for (int count=-2; count<=14; count++) {

statements;

}

4. for (int k=2; k>=10; k) {

statements;

}

5. for (int time=10; time>=5; time++) {

statements;

}

6. What is the value of count after the nested for loops are executed?

int count(0);

for(int k=-1; k<4; k++) {

for(int j=3; j>0; j--) {

count++;

} }

Section 4.3 Problem Solving Applied: GPS 153