• No results found

Building C++ Solutions with IDEs: Microsoft Visual C++

Data Collection

Section 4.4 break and continue Statements 157

4.7 Building C++ Solutions with IDEs: Microsoft Visual C++

In this section we develop a C++ solution using Microsoft Visual C++ to illustrate the use of nested control structures. Our program implements the divide-and-conquer algorithm to guess a number between 1 and 20. The divide-and-conquer algorithm divides the range of possible guesses by two at each iteration by adjusting either the high or low value that defines the range. The guess is always the midpoint of the range.

Our program terminates when the number is guessed or the high value in the range becomes less than the low value. The second case will happen if the user does not answer each question correctly. The pseudocode for our number-guessing algorithm is given below:

Pseudocode

main: print greeting to user while(!done && high > = low)

guess = (high + low)/2 print guess

if guess equals number

print number of trys required to guess number done = true

else if guess is larger than number increment number of tries

high = guess - 1

else if guess is smaller than number increment number of tries

low = guess + 1 end while

Section 4.7 Building C++ Solutions with IDEs: Microsoft Visual C++ 169 The steps in the pseudocode are detailed enough to convert into C++. We use the ceil() function and the natural log function, log(), to predict how many tries it should take to guess the number, using our divide-and-conquer algorithm.

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

/* Program chapter4_9 */

/* This program guesses a number between 1 and 20 inclusive. */

#include<iostream> //Required for cout, cin

#include<cmath> //Required for ceil, log using namespace std;

int main() {

// Declare and initialize objects

int high(20), low(1), guess, count(1), ceiling;

bool done(false);

char answer;

const char YES('Y'), NO('N');

// Print greeting to user

ceiling = ( ceil(log( (double)high ) ) + 1 );

cout << "Think of a number between " << low << "and" << high

<< "and I will guess it in\n" << ceiling

<< "or fewer trys. Just answer y(es) or n(o) to my questions.\n"

<< "Are you thinking of a number? " << endl;

cin >> answer;

switch(toupper(answer)) {

case YES:

// While number has not been guessed while(!done && high >= low)

{

guess = (high + low)/2;

cout << " Are you thinking of " << guess << '?' << endl;

cin >> answer;

switch(toupper(answer)) {

case YES:

cout << " I guessed it in " << count << " trys." << endl;

if(count > ceiling) cout << " Good pick.." << endl;

done = true;

break;

case NO:

//Must guess again.

++count;

cout << " Is " << guess << " larger?" << endl;

cin >> answer;

170 Chapter 4 Control Structures: Repetition

if(toupper(answer) == YES) high = guess - 1;

else low = guess + 1;

break; //case NO default:

cout << " Don't support " << answer << endl;

done = true;

} //end switch } //end while break;

case NO:

cout << " OK..Goodbye. " << endl;

break;

default:

cout << " Dont support " << answer << endl;

}

return 0;

}//end main

Microsoft Visual C++

Visual C++ is an IDE developed by Microsoft for the design and development of C and C++

program solutions. When the Visual C++ application is launched, a Start page appears, similar to what is shown below:

To create a new project, select New Project. . . from the File menu at the top of the window, or select Create: Project . . . from the Recent Projects window. A new project screen will appear, similar to the one shown below.

Section 4.7 Building C++ Solutions with IDEs: Microsoft Visual C++ 171

For this example we will select Win32 Console Application. We name the file chap-ter4_8and click the OK. . . button at the bottom of the window. A new Win32 Application Wizard window will appear, as shown below.

If the Finish button is selected at this time, a new project will be created with a pre-compiled header. For simplicity, in this example we want to create an empty project with no added header files, so we click the Next> button at the bottom of the window. The following Finish screen will appear.

172 Chapter 4 Control Structures: Repetition

From this screen we select Console application and Empty project, then click the Finish button. A new empty project named chapter4_8 is created, as shown below in the left window of the chapter4_8 Visual C++ project screen.

Section 4.7 Building C++ Solutions with IDEs: Microsoft Visual C++ 173 To add a new file to a project, select Add New Item from the Project menu at the top of the window. The following Add New Item window will appear.

Select Code from the left window and C++ file (.cpp) from the right window. Name the file main and click the Add button. The Editor window will open. Enter the code for program chapter4_9, as shown below.

174 Chapter 4 Control Structures: Repetition

Select Build Solution from the Build menu. If the build is successful, choose Start without Debugging from the Debug menu to execute the program. A Console window will appear, and all standard I/O can be viewed from this window. Results from a run of our program are provided in the screen image below. The number 7 was guessed in only three tries. Are there any numbers that require more than three tries to guess?

Visual C++ and Visual Studio are powerful IDEs with many tools that facilitate the development of large software projects. If you will be working in a Windows environment, we recommend that you view the help materials and tutorials that are provided as part of the Microsoft Visual environment.

Modify!

These problems relate to the program chapter4_9 developed in this section.

1. Modify the program by replacing all switch statements with if statements.

2. Modify the program by replacing the while loop with a do/while loop.

3. Modify the program by having it guess a number between 1 and 100.

SUMMARY

In this chapter, we have presented techniques for repeating sets of statements that used loops.

These loops can be implemented as while loops do/while loops or as for loops. These repetition structures are used in most programs.

Summary 175

cout << degrees << '\t' << radians << endl;

degrees += 10;

cout << degrees << '\t' << radians << endl;

degrees += 10;

} while (degrees <= 360);

forloop:

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

radians = degrees*PI/180;

cout << degrees << '\t' << radians << endl;

}

1. Indent the statements within a statement block or inside a loop. If loops or com-pound statements are nested, indent each nested set of statements from the previous statement.

2. Use braces to identify the body of every loop; put each brace on a line by itself so that the body of the loop is easily identified.

176 Chapter 4 Control Structures: Repetition

Debugging Notes

1. Use cout statements to give memory snapshots of the values of key objects when debugging loops. Remember to use the endl manipulator instead of ‘\n’ to ensure that the values are printed immediately after the statement is executed.

2. It is easier than you think to generate an infinite loop; be sure you know the special characters needed to abort the execution of a program on your system if it goes into an infinite loop.

Problems Exam Practice!

True/False Problems

Indicate whether the following statements are true (T) or false (F).

1. A break statement is used to immediately exit from a loop. T F 2. The continue statement forces the next iteration of a loop. T F 3. A break statement is required in a sentinel-controlled loop. T F 4. The end-of-data loop is easily implemented using a while loop. T F

5. A counter-controlled loop is often used to count the number of lines of data received from standard input. T F

6. To debug a loop, we can use cout statements in the loop to provide memory snap-shots of objects. T F

Syntax Problems

Identify any syntax errors in the following statements. Assume that the objects have all been defined as integers.

cout << count << endl;

++count;

}; while(count < 10) Multiple-Choice Problems

Circle the letter for the best answer to complete each statement or for the correct answer to each question.

10. Consider the following statement:

int i=100, j=0;

Which of the following statements are true?

(a) i<3 (b) !(j<1)

(c) (i>0) || (j>50) (d) (j<i) && (i <= 10)

Summary 177 11. If a1 is true and a2 is false, then which of the following expressions are true?

(a) a1 && a2 (b) a1 || a2 (c) !(a1 || a2) (d) !a1 && a2

12. Which of the following are unary operators?

(a) !

(d) none of the above.

Problems 14 through 16 refer to the following statements:

int sum(0), count;

for (count=0; count<=4; count++) sum += count;

cout << "sum = " << sum << endl;

14. What would you see on the screen if these statements were executed?

(a) sum = 1 (b) sum = 6 (c) sum = 10

(d) four lines of output (e) error message

15. What is the value of count after execution of the for loop?

(a) 0 (b) 4 (c) 5

(d) an unpredictable integer

16. How many times is the for loop executed?

(a) 0 (b) 4 (c) 5 (d) 6

Programming Problems

Unit Conversions. Problems 19 through 23 generate tables of unit conversions. In-clude a table heading and column headings for the tables. Choose the number of decimal places based on the values to be printed.

17. Generate a table of conversions from radians to degrees. Start the radian column at 0.0, and increment byπ/10 until the radian amount is 2π.

178 Chapter 4 Control Structures: Repetition

18. Generate a table of conversions from degrees, to radians. The first line should con-tain the value for 0 degrees, and the last line should concon-tain the value for 360 de-grees. Allow the user to enter the increment to use between lines in the table.

19. Generate a table of conversions from inches to centimeters. Start the inches column at 0.0 and increment by 0.5 in. The last line should contain the value 20.0 in. (Recall that 1 in.= 2.54 cm.)

20. Generate a table of conversions from mph to ft/s. Start the mph column at 0 and increment by 5 mph. The last line should contain the value 65 mph. (Recall that 1 mi= 5,280 ft.)

21. Generate a table of conversions from ft/s to mph. Start the ft/s column at 0 and increment by 5 ft/s. The last line should contain the value 100 ft/s. (Recall that 1 mi= 5,280 ft.)

Currency Conversions. Problems 24 through 27 generate tables of currency conver-sions. Use title and column headings. Assume the following conversion rates or check the Web for current rates:

1 dollar ($) = 9.02 Mexican pesos 1 yen (Y) = $ 0.01 U.S. dollars

1 dollar ($) = 11.30 South African rand

22. Generate a table of conversions from pesos to dollars. Start the pesos column at 5 pesos and increment by 5 pesos. Print 25 lines in the table.

23. Generate a table of conversions from yen to pesos. Start the yen column at 1 Y and increment by 2 Y. Print 30 lines in the table.

24. Generate a table of conversions from yen to South African rand. Start the yen col-umn at 100 Y and print 25 lines, with the final line containing the value 10,000 Y.

25. Generate a table of conversions from dollars to pesos, South African rand, and yen.

Start the column with $1 and increment by $1. Print 50 lines in the table.

Temperature Conversions. Problems 28 through 30 generate temperature-conversion tables. Use the following equations that give relationships between temperatures in degrees Fahrenheit (TF), degrees Celsius (TC), degrees Kelvin (TK), and degrees Rankin (TR):

TF = TR - 459.67 degrees R TF = (9/5)TC + 32 degrees F TR = (9/5)TK

26. Write a program to generate a table of conversions from Fahrenheit to Celsius for values from 0 degrees F to 100 degrees F. Print a line in the table for each 5-degree change. Use a while loop in your solution.

27. Write a program to generate a table of conversions from Fahrenheit to Kelvin for values from 0 degrees F to 200 degrees F. Allow the user to enter the increment in degrees Fahrenheit between lines. Use a do/while loop in your solution.

28. Write a program to generate a table of conversions from Celcius to Rankin. Allow the user to enter the starting temperature and increment between lines. Print 25 lines in the table. Use a for loop in your solution.

Summary 179 Timber Regrowth. A problem in timber management is to determine how much of an area to leave uncut so that the harvested area is reforested in a certain period. It is assumed that reforestation takes place at a known rate per year, depending on climate and soil conditions.

A reforestation equation expresses this growth as a function of the amount of timber standing and the reforestation rate. For example, if 100 acres are left standing after harvesting and the reforestation rate is 0.05, then 100+ 0.05 ∗ 100, or 105 acres, are forested at the end of the first year. At the end of the second year, the number of acres forested is 105+ 0.05 ∗ 105, or 110.25 acres.

29. Assume that there are 14,000 acres total with 2,500 acres uncut and that the refor-estation rate is 0.02. Print a table showing the number of acres forested at the end of each year, for a total of 20 years.

30. Modify the program developed in problem 31 so that the user can enter the number of years to be used for the table.

31. Modify the program developed in problem 31 so that the user can enter a number of acres and the program will determine how many years are required for the number of acres to be completely reforested.

Loops These problems relate to program chapter3_1 developed in chapter 3 to gen-erate a truth table.

32. Rewrite program chapter 3_1, developed in Chapter 3, and use nested for loops.

33. Modify program chapter 4_5, developed in this chapter, by replacing the for loop with a do/while loop.

34. Modify program chapter 4_5, developed in this chapter, by replacing the for loop with a while loop.

5

ENGINEERING CHALLENGE: