158
1233 Appendix C Introduction to Flowcharting This appendix provides a brief introduction to flowcharting. It includes example flowcharts for programs that appear in Chapters 1–6. In addition, a complete lesson on flowcharting is included on the student disk. The lesson is stored in a PowerPoint file named Flowchart.ppt . A flowchart is a diagram that depicts the “flow” of a program. It contains symbols that repre- sent each step in the program. The figure shown here is a flowchart for Program 1-1, the pay-cal- culating program in Chapter 1. START END Display message ”How many hours did you work?” Display message ”How much do you get paid per hour?” Multiply hours by payRate. Store result in grossPay. Read hours Read payRate Display grossPay

Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

  • Upload
    voduong

  • View
    214

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1233

Appendix CIntroduction to Flowcharting

This appendix provides a brief introduction to flowcharting. It includes example flowcharts forprograms that appear in Chapters 1–6. In addition, a complete lesson on flowcharting is includedon the student disk. The lesson is stored in a PowerPoint file named

Flowchart.ppt

.A flowchart is a diagram that depicts the “flow” of a program. It contains symbols that repre-

sent each step in the program. The figure shown here is a flowchart for Program 1-1, the pay-cal-culating program in Chapter 1.

START

END

Display message”How many hours did

you work?”

Display message”How much

do you get paid per hour?”

Multiply hoursby payRate.

Store result in grossPay.

Read hours

Read payRate

DisplaygrossPay

Gaddis4.book Page 1233 Monday, January 6, 2003 5:16 PM

Page 2: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1234 Introduction to Flowcharting

Notice there are three types of symbols in this flowchart: rounded rectangles (representing termi-nal points), parallelograms (representing input/output operations), and a rectangle (representinga process).

The rounded rectangles, or terminal points, indicate the flowchart’s starting and ending points.The parallelograms designate input or output operations. The rectangle depicts a process such asa mathematical computation, or a variable assignment. Notice that the symbols are connectedwith arrows that indicate the direction of program flow.

Connectors

Sometimes a flowchart is broken into two or more smaller flowcharts. This is usually done when aflowchart does not fit on a single page, or must be divided into sections. A connector symbol,which is a small circle with a letter or number inside it, allows you to connect two flowcharts.

In the figure below, the A connector indicates that the second flowchart segment begins where thefirst flowchart segment ends.

Terminal ProcessesInput/OutputOperations

A

END

START A

A

Gaddis4.book Page 1234 Monday, January 6, 2003 5:16 PM

Page 3: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Flowcharting 1235

Flowchart Structures

There are four general flowchart structures:

Sequence

Decision

Repetition

Case

A sequence structure is a series of actions or steps, performed in order. The flowchart for the pay-calculating program is an example of a sequence structure. The following flowchart is also asequence structure. It depicts the steps performed in Program 2-20, from Chapter 2.

Flowchart for Program 2-20

The flowchart, which is another sequence structure, depicts the steps performed in Program 3-14(from Chapter 3). Notice the use of connector symbols to link the two flowchart segments.

END

START

DisplayTotal Pay

Calculate TotalWages as Regular

Wages plusOvertime Wages.

Calculate RegularWages as Base

Pay times Regular Hours.

Calculate OvertimeWages as

Overtime Paytimes Overtime

Hours.

Gaddis4.book Page 1235 Monday, January 6, 2003 5:16 PM

Page 4: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1236 Introduction to Flowcharting

Flowchart for Program 3–14

The Decision Structure

In a decision structure, one of two possible actions is performed, depending on a condition. Ina decision structure, a new symbol, the diamond, represents a yes/no question. If the answer to

START

END

Ask user to enterbeginning

inventory value for all three stores.

Store BegInvin store1,

store2, and store3.

Subtract Soldfrom store1.

Read begInv.

Read sold.

Ask user to enternumber of widgets sold at Store 1.

A

A

Ask user to enternumber of widgets sold at Store 2.

Subtract Soldfrom Sold2.

Subtract soldfrom store3.

Read sold.

Read sold.

Ask user to enternumber of widgets sold at Store 3.

Display inventory values for all three stores.

Gaddis4.book Page 1236 Monday, January 6, 2003 5:16 PM

Page 5: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Flowcharting 1237

the question is “yes,” the program flow follows one path. If the answer to the question is “no,”the program flow follows another path. The following figure shows the general form of a deci-sion structure.

In the following flowchart segment, the question “is x < y?” is asked. If the answer is no, then pro-cess A is performed. If the answer is yes, then process B is performed.

The following flowchart depicts the logic of Program 4–9, from Chapter 4. The decision structureshows that one of two possible messages is displayed on the screen, depending on the value of theexpression

number % 2

.

NO YES

NO

Process A Process B

YES

x < y?

Gaddis4.book Page 1237 Monday, January 6, 2003 5:16 PM

Page 6: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1238 Introduction to Flowcharting

Flowchart for Program 4–9

The Case Structure

In a case structure, one of several possible actions is taken, depending on the contents of a vari-able. The following flowchart segment shows the general form of a case structure.

The following flowchart depicts the logic of Program 4–33, which is also from Chapter 4. One of5 possible paths is followed, depending on the value stored in the variable

choice

.

NO

Display”Number is

odd.”

number % 2equal to 0?

Read number.

Ask user to enter an integer.

Display”Number is

even.”

YES

START

END

Gaddis4.book Page 1238 Monday, January 6, 2003 5:16 PM

Page 7: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Flowcharting 1239

Flowchart for Program 4–33

Repetition Structures

A repetition structure represents part of the program that repeats. This type of structure is com-monly known as a loop. The following figure shows an example of a repetition structure.

Notice the use of the diamond symbol. A repetition structure tests a condition, and if the condi-tion exists, it performs an action. Then it tests the condition again. If the condition still exists, the

START

Display HealthClub membership

Menu.

Read menuselection into

choice.

Read months.

CASEchoice

Ask user to enterthe number of months

of membership.

DisplayGoodbyeMessage

DisplayError

Message

charges =months times 40

Displaycharges.

Displaycharges.

Displaycharges.

Other1 2 3 4

charges =months times 20

charges =months times 30

END

YESProcess Ax < y?

Gaddis4.book Page 1239 Monday, January 6, 2003 5:16 PM

Page 8: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1240 Introduction to Flowcharting

action is repeated. This continues until the condition no longer exists. In the flowchart segmentabove, the question “is x < y?” is asked. If the answer is yes, then Process A is performed. Thequestion “is x < y?” is asked again. Process A is repeated as long as x is less than y. When x is nolonger less than y, the repetition stops and the structure is exited.

There are two forms of repetition structure: pre-test and post-test. A pre-test repetitionstructure tests its condition

before

it performs an action. The flowchart segment above shows apre-test structure. Notice that Process A does not execute at all if the condition “x < y” is not true.The pre-test repetition structure is coded in C++ as a

while

loop.A post-test repetition structure tests its condition

after

it performs an action. This type ofloop always performs its action at least once. The following flowchart segment shows an example.

The post-test repetition structure is coded in C++ as a

do-while

loop.The following flowchart depicts the logic of Program 5-4, which appears in Chapter 5.

Flowchart for Program 5-4

YES

NO

Process A

x < y?

START

number = 1.

Display TableHeadings.

Display numberand number

Squared.

number <=10?

YES

NO

Add 1 to number.

END

Gaddis4.book Page 1240 Monday, January 6, 2003 5:16 PM

Page 9: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Flowcharting 1241

Modules

A program module (such as a function in C++) is represented by the special symbol shown below:

The position of the module symbol indicates the point the module is executed, as shown in thefollowing figure:

A separate flowchart can then be constructed for the module. The following figure shows a flow-chart for Program 6-10 from Chapter 6. The Adult, Child, and Senior modules appear as separateflowcharts.

START

END

Read Input.

Call calc_payfunction.

Display results.

Gaddis4.book Page 1241 Monday, January 6, 2003 5:16 PM

Page 10: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1242 Introduction to Flowcharting

Flowchart for Program 6-10

START

Display Health ClubMembership Menu.

Read menu selectioninto choice

Ask user to enterthe number of

months of membership.

Display goodbyemessage.

Display errormessage.

Call seniorModule.

Call childModule.

Call adultModule.

CASEChoice

Read months.

END

YES

NO

choice! = 4?

Default1 2 3 4

START ofadult Module

END ofadult Module

Display chargesas months times 40.

START ofchild Module

END ofchild Module

Display chargesas months times 20.

START ofsenior Module

END ofsenior Module

Display chargesas months times 30.

Gaddis4.book Page 1242 Monday, January 6, 2003 5:16 PM

Page 11: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1243

Appendix DEnumerated Data Types

An enumerated data type in C++ is one that allows you to create symbols that represent integerconstants. Here is an example of an enumerated type declaration.

enum Roster { Tom, Sharon, Bill, Teresa, John };

This declaration creates an enumerated data type named

Roster

. The values in the braces are allof the possible values that a variable of the

Roster

type may have. The following statementdefines a variable named

student

. The

student

variable is of the

Roster

data type.

Roster student;

Because

student

is a variable of the

Roster

data type, we may store any of the values

Tom

,

Sharon

,

Bill

,

Teresa

, or

John

in it. An assignment operation would look like this:

student = Sharon;

The statement above assigns the value

Sharon

to the variable. The value of the variable can betested like this:

if (student == Sharon)

>

Note:

This statement is not the same as

if (student == "Sharon")

. An enumerated type's values are not strings.

So just what are these values? These are symbolic values that are stored in memory as integers.The symbol

Tom

is stored as the number 0.

Sharon

is stored as the number 1.

Bill

is stored as thenumber 2, and so forth.

Even though the values in an enumerated data type are stored as integers, you cannot substi-tute their integer values for their symbolic values. For example, assuming that student is a variableof the

Roster

data type, the following assignment statement is illegal.

student = 2; // Error!

You can, however, test an enumerated variable for the integer values instead of the constants. Forexample, the following two

if

statements are equivalent.

if (student == Bill)

Gaddis4.book Page 1243 Monday, January 6, 2003 5:16 PM

Page 12: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1244 The Enumerated Data Type

if (student == 2)

You can also use relational operators to test two enumerated variables. For example, the followingif statement determines if the enumerated value in

student1

is less than the value in

student2

:

if (student1 < student2)

By default, the symbols in the enumeration list are assigned the integer values 0, 1, 2, and so forth.If this is not appropriate, you can specify the values to be assigned, as in the following example.

enum Score { F = 60, D = 70, C = 80, B = 90, A = 100 };

If you leave out the value assignment for one or more of the symbols, it will be assigned a defaultvalue. Here is an example:

enum Colors { red, orange, yellow = 9, green, blue };

red

will be assigned the value 0,

orange

will be 1,

yellow

will be 9,

green

will be 10, and

blue

will be 11.Program D-1 shows the values of an enumerated data type being used in a switch construct’s

case statements, and as subscripts for an array. The enumerated type’s symbolic values make theprogram more self-documenting.

Program D-1

// This program demonstrates an enumerated type.#include <iostream>using namespace std;

// Declare the enumerated typeenum Roster { Tom, Sharon, Bill, Teresa, John };

float grade[5];// Array to hold student grades

int main(){

float score;int who;

cout << "Enter a student's test score: ";cin >> score;cout << "Which student made that score?\n";cout << "0 = Tom\n";cout << "1 = Sharon\n";cout << "2 = Bill\n";cout << "3 = Teresa\n";cout << "4 = John\n";cin >> who;

(program continues)

Gaddis4.book Page 1244 Monday, January 6, 2003 5:16 PM

Page 13: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

The Enumerated Data Type 1245

Although you can use an enumerated type’s symbolic values to subscript an array, it is not a sim-ple matter to use the symbolic values in a loop to step through an array. For example, the follow-ing code will not work:

Roster student;for (student = Tom; student < John; student++)

cout<< grade[student];

The loop will not work because you cannot use the increment operator on an enumerated vari-able. You can, however, use an expression such as the one below to get the integer value of the nextsymbolic value:

student + 1

But you cannot construct a statement such as

student = student + 1

because you cannotassign an integer to an enumerated variable. Instead, you must use a typecast operator to convertthe integer to the enumerated type:

student = static_cast<Roster>(student + 1);

switch (who){

case Tom: grade[Tom] = score;break;

case Sharon: grade[Sharon] = score;break;

case Bill: grade[Bill] = score;break;

case Teresa: grade[Teresa] = score;break;

case John: grade[John] = score;break;

default:cout << "Invalid selection\n";}return 0;

}

Program Output with Example Input Shown in Bold

Enter a student's test score: 92 [Enter]Which student made that score?0 = Tom1 = Sharon2 = Bill3 = Teresa4 = John2 [Enter]

Program D-1 (continued)

Gaddis4.book Page 1245 Monday, January 6, 2003 5:16 PM

Page 14: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1246 The Enumerated Data Type

So, a loop that uses an enumerated variable to step through an array can be written like this:

for(student = Tom; student <= Duane; student = static_cast<Roster>(student + 1)){

cout << student << endl;}

Program D-2 demonstrates this technique.

Program D-2

// This program demonstrates an enumerated type.#include <iostream>using namespace std;

// Declare the enumerated typeenum Roster { Tom, Sharon, Bill, Teresa, John };

// Array to hold student gradesfloat grade[5] = { 89, 100, 97, 84, 89 };

int main(){

Roster student;

cout << "Here are the student grades:\n";for (student = Tom; student <= John; student = static_cast<Roster>(student + 1)){

cout << grade[student] << endl;}

return 0;}

Program OutputHere are the student grades:89100978489

Gaddis4.book Page 1246 Monday, January 6, 2003 5:16 PM

Page 15: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1247

Appendix ENamespaces

IntroductionNamespaces are an ANSI C++ feature that allows programmers to create a scope for global identifi-ers. They are useful in preventing errors when two or more global declarations use the same name.

For example, assume you are a programmer in the accounting department of a business.Your company has purchased two libraries of C++ class objects from a software vendor. One ofthe libraries is designed to handle customer accounts, and contains a class object named payable.The other library is designed to handle company payroll, and also has a class object named pay-able. You are writing a program that integrates both sets of classes, but the compiler generates anerror because the two class objects have the same name. You cannot modify the class librariesbecause the software vendor does not sell the source code, only libraries of object code.

This problem can be solved when the software vendor places each set of classes in its ownnamespace. Each namespace has its own name, which must be used to qualify the name of itsmembers. For instance, the payable object that is part of the customer accounts library mightexist in a namespace named customer, while the object that is part of the employee payrolllibrary might exist in a namespace named payroll. When you, the application programmer,work with the objects, you must specify the namespace that the object is a member of. One way ofaccomplishing this is by extending the name of the object with the namespace name, using thescope resolution operator. For example, the payable object that is a member of the customernamespace is specified as customer::payable, and the object that is a member of the payrollnamespace is specified as payroll::payable. Another way to specify the namespace is by plac-ing a using namespace statement in the source file that references the namespace’s memberobject. For example, the following statement (placed near the beginning of a source file) instructsthe compiler that the file uses members of the customer namespace.

using namespace customer;

Likewise, the following statement instructs the compiler that the source file uses members of thepayroll namespace:

using namespace payroll;

When a using namespace statement has been placed in a source file, it is no longer necessary forstatements in that source file to qualify the names of the namespace’s members with thenamespace name and the scope resolution operator.

Gaddis4.book Page 1247 Monday, January 6, 2003 5:16 PM

Page 16: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1248 Namespaces

Defining a NamespaceA namespace is defined in the following manner.

namespace namespace_name{

declarations…}

For example, look at Program E-1. It defines the test namespace, which has three members: x, y,and z.

In Program E-1, the variables x, y, and z are defined in the test namespace’s scope. Each time theprogram accesses one of these variables, test:: must precede the variable name. Otherwise, acompiler error will occur.

Program E-2 demonstrates how programmers can use namespaces to resolve naming con-flicts. The program defines two namespaces, test1 and test2. Both namespaces have variablesnamed x, y, and z as members.

Program E-1

// Demonstrates a simple namespace#include <iostream>using namespace std;

namespace test{

int x, y, z;}

int main(){

test::x = 10;test::y = 20;test::z = 30;cout << "The values are:\n";cout << test::x << " " << test::y

<< " " << test::z << endl;return 0;

}

Program OutputThe values are:10 20 30

Gaddis4.book Page 1248 Monday, January 6, 2003 5:16 PM

Page 17: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Namespaces 1249

An alternative approach to qualifying the names of namespace members is to use the usingnamespace statement. This statement tells the compiler which namespace to search for an identi-fier, when the identifier cannot be found in the current scope. Program E-3 demonstrates thestatement.

Program E-2

// Demonstrates two namespaces#include <iostream>using namespace std;

namespace test1{

int x, y, z;}

namespace test2{

int x, y, z;}

int main(){

test1::x = 10;test1::y = 20;test1::z = 30;cout << "The test1 values are:\n";cout << test1::x << " " << test1::y

<< " " << test1::z << endl;test2::x = 1;test2::y = 2;test2::z = 3;cout << "The test2 values are:\n";cout << test2::x << " " << test2::y

<< " " << test2::z << endl;return 0;

}

Program OutputThe test1 values are:10 20 30The test2 values are:1 2 3

Gaddis4.book Page 1249 Monday, January 6, 2003 5:16 PM

Page 18: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1250 Namespaces

The using namespace demo; statement eliminates the need to precede testObject withdemo::. The compiler automatically uses the namespace demo to find the identifier.

Program E-3

Contents of nsdemo.h// This file defines a namespace// named demo. In the demo namespace// a class named NsDemo is declared,// and an instance of the class named// testObject is defined.

namespace demo{

class NsDemo{public:

int x, y, z;};

NsDemo testObject;}

Contents of Main File, PrE-3.cpp// This program demonstrates the // using namespace statement.#include <iostream>#include "nsdemo.h"using namespace std;

using namespace demo;

int main(){

testObject.x = 10;testObject.y = 20;testObject.z = 30;cout << "The values are:\n" << testObject.x << " " << testObject.y << " " << testObject.z << endl;return 0;

}

Program OutputThe values are:10 20 30

Gaddis4.book Page 1250 Monday, January 6, 2003 5:16 PM

Page 19: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Namespaces 1251

ANSI C++ and the std NamespaceAll the identifiers in the ANSI standard header files are part of the std namespace. In ANSI C++,cin and cout are written as std::cin and std::cout. If you do not wish to specify std:: withcin or cout (or any of the ANSI standard identifiers), you must write the following statement inyour program:

using namespace std;

Gaddis4.book Page 1251 Monday, January 6, 2003 5:16 PM

Page 20: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1252

Appendix FCreating a Boolean Data Type

Standard C++ has a bool data type that is discussed in this book. If you are using a pre-standardC++ compiler, however, you may not be able to run any programs that use the bool data type.You can take the steps shown in this appendix to create a bool data type that works like standardC++’s built-in bool data type.

To create a bool data type, you will use a typedef statement. typedef stands for “type defi-nition,” and allows you to create a new name for an existing data type*. Here is the statement youwill use to create the bool data type:

typedef int bool;

This statement, which should be placed near the top of your program, declares bool as thename of a data type. It also establishes that bool variables are actually ints. (The reason we aremaking bool an int data type is that true and false values are stored in memory as 1 and 0.)

After you have created the bool data type, the next step is to create the true and false con-stants:

const bool true = 1;const bool false = 0;

These statements create the constants true and false with the values 1 and 0 respectively. Nowyou are ready to use your bool data type, and your pre-standard C++ compiler will understandit. Program F-1 shows an example.

* The typedef statement was commonly used in the C programming language to create user-defined data types. It is rarely used in C++ because of newer language conventions.

Gaddis4.book Page 1252 Monday, January 6, 2003 5:16 PM

Page 21: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Creating a Boolean Data Type 1253

Program F-1

// This program demonstrates creating a bool data type// for use with a pre-standard C++ compiler.#include <iostream>using namespace std;

typedef int bool;const bool true = 1;const bool false = 0;

int main(){

bool boolValue;

boolValue = true;cout << boolValue << endl;boolValue = false;cout << boolValue << endl;return 0;

}

Program Output10

Gaddis4.book Page 1253 Monday, January 6, 2003 5:16 PM

Page 22: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1254

Appendix GPassing Command Line Arguments

If you are working in a command line environment such as UNIX, Linux, or the DOS prompt, itmight be helpful to write programs that take arguments from the command line. For example,suppose we have a program called sum, which takes two numbers as command line argumentsand displays their sum. We could enter the following command at the operating system prompt:

sum 12 16

The arguments, which are separated by a space, are 12 and 16. Because a C++ program starts itsexecution with function main, command line arguments are passed to main. Function main canbe optionally written with two special parameters. These parameters are traditionally namedargc and argv. The argc parameter is an int, and the argv parameter is an array of char point-ers. Here is an example function header for main, using these two parameters:

int main(int argc, char *argv[])

The argc parameter contains the number of items that were typed on the command line, includ-ing the name of the program. For example, if the sum program described above is executed withthe command sum 12 16, the argc parameter will contain 3.

As previously mentioned, the argv parameter is an array of char pointers. In the functionheader, the brackets are empty because argv is an external array of unknown size. The numberthat is stored in argc, however, will be the number of elements in the argv array. Each pointer inthe argv array points to a C-string holding a command line argument. Once again, assume thesum program is executed with the command sum 12 16. The elements of the argv array will refer-ence the items on the command line in the following manner:

argv[0] = "sum"argv[1] = "12"argv[2] = "16"

Before we look at the code for the sum program, let’s look at Program G-1. It is a simple programthat simply displays its command line arguments. (The program is named argdemo.cpp.)

Gaddis4.book Page 1254 Monday, January 6, 2003 5:16 PM

Page 23: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Passing Command Line Arguments 1255

Now, let’s look at the code for the sum program.

Program G-1 (argdemo.cpp)

// This program demonstrates how to read// command line arguments.#include <iostream>using namespace std;

int main(int argc, char *argv[]){

cout << "You entered " << (argc - 1) cout << " command line arguments.\n";if (argc > 1){

cout << "Here they are:\n";for (int count = 1; count < argc; count++)

cout << argv[count] << endl;}return 0;

}

Example Session on a UNIX System$ argdemo Hello World [Enter]You entered 2 command line arguments.Here they are:HelloWorld$

Program G-2 (sum.cpp)

// This program takes two command line arguments,// assumed to be numbers, and displays their sum.#include <iostream>#include <cmath> // Needed for atofusing namespace std;

int main(int argc, char *argv[]){

double total = 0;

if (argc > 1){

for (int count = 1; count < argc; count++)total += atof(argv[count]);

cout << total << endl;}return 0;

}

Gaddis4.book Page 1255 Monday, January 6, 2003 5:16 PM

Page 24: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1256 Passing Command Line Arguments

Example Session on a UNIX System$ sum 12 16 [Enter]28$ sum 1 2 3 4 5 [Enter]15$

Program G-2 (sum.cpp)

Gaddis4.book Page 1256 Monday, January 6, 2003 5:16 PM

Page 25: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1257

Appendix HHeader File and Library Function Reference

This appendix provides a reference for the C++ library functions discussed in the book. The fol-lowing table gives an alphabetical list of functions. Tables of functions that are organized by theirheader files follow it.

Alphabetical Listing of Selected Library Functions

Function Details

abs(m) Header File: cmathDescription:Accepts an integer argument. Returns the absolute value of the argument as an integer.Example:a = abs(m);

atof(str) Header File: cstdlibDescription:Accepts a C-string as an argument. The function converts the string to a double and returns that value.Example:num = atof("3.14159");

atoi(str) Header File: cstdlibDescription:Accepts a C-string as an argument. The function converts the string to an int and returns that value.Example:num = atoi("4569");

Gaddis4.book Page 1257 Monday, January 6, 2003 5:16 PM

Page 26: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1258 Header File and Library Function Reference

atol(str) Header File: cstdlibDescription:Accepts a C-string as an argument. The function converts the string to a long and returns that value.Example:num = atol("5000000");

cos(m) Header File: cmathDescription:Accepts a double argument. Returns the cosine of the argument. The argument should be an angle expressed in radians. The return type is double.Example:a = cos(m);

exit(status) Header File: cstdlibDescription:Accepts an int argument. Terminates the program and passes the value of the argument to the operating system.Example:exit(0);

exp(m) Header File: cmathDescription:Accepts a double argument. Computes the exponential function of the argument, which is ex. The return type is double.Example:a = exp(m);

fmod(m, n) Header File: cmathDescription:Accepts two double arguments. Returns, as a double, the remainder of the first argument divided by the second argument. Works like the modulus operator, but the arguments are doubles. (The modulus operator only works with integers.) Take care not to pass zero as the second argument. Doing so would cause division by zero.Example:a = fmod(m, n);

isalnum(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a letter of the alphabet or a digit. Otherwise, it returns false.Example:if (isalnum(ch)) cout << ch << " is alphanumeric.\n";

Alphabetical Listing of Selected Library Functions (continued)

Function Details

Gaddis4.book Page 1258 Monday, January 6, 2003 5:16 PM

Page 27: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Header File and Library Function Reference 1259

isdigit(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a digit 0 - 9. Otherwise, it returns false.Example:if (isdigit(ch)) cout << ch << " is a digit.\n";

islower(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a lowercase letter. Otherwise, it returns false.Example:if (islower(ch)) cout << ch << " is lowercase.\n";

isprint(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a printable character (including a space). Returns false otherwise.Example:if (isprint(ch)) cout << ch << " is printable.\n";

ispunct(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a printable character other than a digit, letter, or space. Returns false otherwise.Example:if (ispunct(ch)) cout << ch << " is punctuation.\n";

isspace(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a whitespace character. Whitespace characters are any of the following:• space................ ‘ ’• newline.............. ‘\n’• tab.................. ‘\t’• vertical tab......... ‘\v’Otherwise, it returns false.Example:if (isspace(ch)) cout << ch << " is whitespace.\n";

Alphabetical Listing of Selected Library Functions (continued)

Function Details

Gaddis4.book Page 1259 Monday, January 6, 2003 5:16 PM

Page 28: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1260 Header File and Library Function Reference

isupper(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is an uppercase letter. Otherwise, it returns false.Example:if (isupper(ch)) cout << ch << " is uppercase.\n";

log(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the natural logarithm of the argument.Example:a = log(m);

log10(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the base-10 logarithm of the argument.Example:a = log10(m);

pow(m, n) Header File: cmathDescription:Accepts two double arguments. Returns the value of argument 1 raised to the power of argument 2.Example:a = pow(m, n);

rand() Header File: cstdlibDescription:Generates a pseudorandom number.Example:x = rand();

sin(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the sine of the argument. The argument should be an angle expressed in radians.Example:a = sin(m);

Alphabetical Listing of Selected Library Functions (continued)

Function Details

Gaddis4.book Page 1260 Monday, January 6, 2003 5:16 PM

Page 29: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Header File and Library Function Reference 1261

sqrt(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the square root of the argument.Example:a = sqrt(m);

srand(m) Header File: cstdlibDescription:Accepts an unsigned int argument. The argument is used as a seed value to randomize the results of the rand() function.Example:srand(m);

strcat(str1, str2) Header File: cstringDescription:Accepts two C-strings as arguments. The function appends the contents of the second string to the first string. (The first string is altered; the second string is left unchanged.)Example:strcat(string1, string2);

strcmp(str1, str2) Header File: cstringDescription:Accepts pointers to two string arguments. If string1 and string2 are the same, this function returns 0. If string2 is alphabetically greater than string1, it returns a positive number. If string2 is alphabetically less than string1, it returns a negative number.Example:if (strcmp(string1, string2) == 0) cout << "The strings are equal.\n";

strcpy(str1, str2) Header File: cstringDescription:Accepts two C-strings as arguments. The function copies the second string to the first string. The second string is left unchanged.Example:strcpy(string1, string2);

Alphabetical Listing of Selected Library Functions (continued)

Function Details

Gaddis4.book Page 1261 Monday, January 6, 2003 5:16 PM

Page 30: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1262 Header File and Library Function Reference

strlen(str) Header File: cstringDescription:Accepts a C-string as an argument. Returns the length of the string (not including the null terminator)Example:len = strlen(name);

strncpy(str1, str2, n)

Header File: cstringDescription:Accepts two C-strings and an integer argument. The third argument, an integer, indicates how many characters to copy from the second string to the first string. If string2 has fewer than n characters, string1 is padded with ‘\0’ characters.Example:strncpy(string1, string2, n);

strstr(str1, str2) Header File: cstringDescription:Searches for the first occurrence of string2 in string1. If an occurrence of string2 is found, the function returns a pointer to it. Otherwise, it returns a NULL pointer (address 0).Example:cout << strstr(string1, string2);

tan(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the tangent of the argument. The argument should be an angle expressed in radians. Example:a = tan(m);

tolower(ch) Header File: cctypeDescription:Accepts a char argument. Returns the lowercase equivalent of its argument.Example:ch = tolower(ch);

toupper(ch) Header File: cctypeDescription:Accepts a char argument. Returns the uppercase equivalent of its argument.Example:ch = toupper(ch);

Alphabetical Listing of Selected Library Functions (continued)

Function Details

Gaddis4.book Page 1262 Monday, January 6, 2003 5:16 PM

Page 31: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Header File and Library Function Reference 1263

Selected cstdlib functions

Function Details

atof(str) Header File: cstdlibDescription:Accepts a C-string as an argument. The function converts the string to a double and returns that value.Example:num = atof("3.14159");

atoi(str) Header File: cstdlibDescription:Accepts a C-string as an argument. The function converts the string to an int and returns that value.Example:num = atoi("4569");

atol(str) Header File: cstdlibDescription:Accepts a C-string as an argument. The function converts the string to a long and returns that value.Example:num = atol("5000000");

exit(status) Header File: cstdlibDescription:Accepts an int argument. Terminates the program and passes the value of the argument to the operating system.Example:exit(0);

rand() Header File: cstdlibDescription:Generates a pseudorandom number.Example:x = rand();

srand(m) Header File: cstdlibDescription:Accepts an unsigned int argument. The argument is used as a seed value to randomize the results of the rand() function.Example:srand(m);

Gaddis4.book Page 1263 Monday, January 6, 2003 5:16 PM

Page 32: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1264 Header File and Library Function Reference

Selected cmath Functions

Function Details

abs(m) Header File: cmathDescription:Accepts an integer argument. Returns the absolute value of the argument as an integer.Example:a = abs(m);

cos(m) Header File: cmathDescription:Accepts a double argument. Returns the cosine of the argument. The argument should be an angle expressed in radians. The return type is double.Example:a = cos(m);

exp(m) Header File: cmathDescription:Accepts a double argument. Computes the exponential function of the argument, which is ex. The return type is double.Example:a = exp(m);

fmod(m, n) Header File: cmathDescription:Accepts two double arguments. Returns, as a double, the remainder of the first argument divided by the second argument. Works like the modulus operator, but the arguments are doubles. (The modulus operator only works with integers.) Take care not to pass zero as the second argument. Doing so would cause division by zero.Example:a = fmod(m, n);

log(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the natural logarithm of the argument.Example:a = log(m);

Gaddis4.book Page 1264 Monday, January 6, 2003 5:16 PM

Page 33: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Header File and Library Function Reference 1265

log10(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the base-10 logarithm of the argument.Example:a = log10(m);

pow(m, n) Header File: cmathDescription:Accepts two double arguments. Returns the value of argument 1 raised to the power of argument 2.Example:a = pow(m, n);

sin(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the sine of the argument. The argument should be an angle expressed in radians.Example:a = sin(m);

sqrt(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the square root of the argument.Example:a = sqrt(m);

tan(m) Header File: cmathDescription:Accepts a double argument. Returns, as a double, the tangent of the argument. The argument should be an angle expressed in radians. Example:a = tan(m);

Selected cmath Functions

Function Details

Gaddis4.book Page 1265 Monday, January 6, 2003 5:16 PM

Page 34: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1266 Header File and Library Function Reference

Selected cstring Functions

Function Details

strcat(str1, str2) Header File: cstringDescription:Accepts two C-strings as arguments. The function appends the contents of the second string to the first string. (The first string is altered; the second string is left unchanged.)Example:strcat(string1, string2);

strcmp(str1, str2) Header File: cstringDescription:Accepts pointers to two string arguments. If string1 and string2 are the same, this function returns 0. If string2 is alphabetically greater than string1, it returns a positive number. If string2 is alphabetically less than string1, it returns a negative number.Example:if (strcmp(string1, string2) == 0) cout << "The strings are equal.\n";

strcpy(str1, str2) Header File: cstringDescription:Accepts two C-strings as arguments. The function copies the second string to the first string. The second string is left unchanged.Example:strcpy(string1, string2);

strlen(str) Header File: cstringDescription:Accepts a C-string as an argument. Returns the length of the string (not including the null terminator)Example:len = strlen(name);

strncpy(str1, str2, n)

Header File: cstringDescription:Accepts two C-strings and an integer argument. The third argument, an integer, indicates how many characters to copy from the second string to the first string. If string2 has fewer than n characters, string1 is padded with ‘\0’ characters.Example:strncpy(string1, string2, n);

Gaddis4.book Page 1266 Monday, January 6, 2003 5:16 PM

Page 35: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Header File and Library Function Reference 1267

strstr(str1, str2) Header File: cstringDescription:Searches for the first occurrence of string2 in string1. If an occurrence of string2 is found, the function returns a pointer to it. Otherwise, it returns a NULL pointer (address 0).Example:cout << strstr(string1, string2);

Selected cctype Functions

Function Details

isalnum(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a letter of the alphabet or a digit. Otherwise, it returns false.Example:if (isalnum(ch)) cout << ch << " is alphanumeric.\n";

isdigit(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a digit 0 - 9. Otherwise, it returns false.Example:if (isdigit(ch)) cout << ch << " is a digit.\n";

islower(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a lowercase letter. Otherwise, it returns false.Example:if (islower(ch)) cout << ch << " is lowercase.\n";

Selected cstring Functions (continued)

Function Details

Gaddis4.book Page 1267 Monday, January 6, 2003 5:16 PM

Page 36: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1268 Header File and Library Function Reference

isprint(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a printable character (including a space). Returns false otherwise.Example:if (isprint(ch)) cout << ch << " is printable.\n";

ispunct(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a printable character other than a digit, letter, or space. Returns false otherwise.Example:if (ispunct(ch)) cout << ch << " is punctuation.\n";

isspace(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is a whitespace character. Whitespace characters are any of the following:• space................ ‘ ’• newline.............. ‘\n’• tab.................. ‘\t’• vertical tab......... ‘\v’Otherwise, it returns false.Example:if (isspace(ch)) cout << ch << " is whitespace.\n";

isupper(ch) Header File: cctypeDescription:Accepts a char argument. Returns true if the argument is an uppercase letter. Otherwise, it returns false.Example:if (isupper(ch)) cout << ch << " is uppercase.\n";

Selected cctype Functions

Function Details

Gaddis4.book Page 1268 Monday, January 6, 2003 5:16 PM

Page 37: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Header File and Library Function Reference 1269

tolower(ch) Header File: cctypeDescription:Accepts a char argument. Returns the lowercase equivalent of its argument.Example:ch = tolower(ch);

toupper(ch) Header File: cctypeDescription:Accepts a char argument. Returns the uppercase equivalent of its argument.Example:ch = toupper(ch);

Selected cctype Functions

Function Details

Gaddis4.book Page 1269 Monday, January 6, 2003 5:16 PM

Page 38: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1270

Appendix IBinary Numbers and Bitwise Operations

One of the many powers that C++ gives the programmer is the ability to work with the individualbits of an integer field. The purpose of this appendix is to give an overview of how integer datatypes are stored in binary and explain the bitwise operators that the C++ offers. Finally, we willlook at bit fields, which allow us to treat the individual bits of a variable as separate entities.

Integer FormsThe integer types that C++ offers are as follows:

charintshortlongunsigned charunsigned (same as unsigned int)unsigned shortunsigned long

When you assign constant values to integers in C++, you may use decimal, octal, or hexadecimal.Placing a zero in the first digit creates an octal constant. For example, 0377 would be interpretedas an octal number. Hexadecimal constants are created by placing 0x or 0X (zero-x, not O-x) infront of the number. The number 0X4B would be interpreted as a hex number.

Binary RepresentationRegardless of how you express constants, integer values are all stored the same way internally—inbinary format. Let’s take a quick review of binary number representation.

Let’s assume we have a one-byte field. The following diagram shows our field broken into itsindividual bits.

Gaddis4.book Page 1270 Monday, January 6, 2003 5:16 PM

Page 39: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Bitwise Operations and Binary Integer Forms 1271

The leftmost bits are called the high order bits and the rightmost bits are called the low order bits.Bit number 7 is the highest order bit, so it is called the most significant bit.

Each of these bits has a value assigned to it. The following diagram shows the values of each bit.

These values are actually powers of two. The value of bit 0 is 20 which is 1. The value of bit 1 is 21,which is 2. Bit 2 has the value 22, which is 4. It progresses to the last bit.

When a number is stored in this field, the bits may be set to either 1 or 0. Here is an example.

Here, bits 1, 2, 5, and 6 are set to 1. To calculate the overall value of this bit pattern, we add up allof the bit values of the bits that are set to 1.

Bit 1’s value 2Bit 2’s value 4Bit 5’s value 32Bit 6’s value 64

-----Overall Value 102

The bit pattern 01100110 has the decimal value 102.

Negative Integer ValuesOne way that a computer can store a negative integer is to use the leftmost bit as a sign bit. Whenthis bit is set to 1, it would indicate a negative number, and when it is set to 0 the number wouldbe positive. The problem with this, however, is that we would have two bit patterns for the num-ber 0. One pattern would be for positive 0, the other would be for negative 0. Because of this,most systems use two’s complement representation for negative integers.

Bit Bit Bit Bit Bit Bit Bit Bit

7 6 5 4 3 2 1 0

High Order -------------------------> Low Order

Bit Bit Bit Bit Bit Bit Bit Bit

7 6 5 4 3 2 1 0

Values –> 128 64 32 16 8 4 2 1

Bit Bit Bit Bit Bit Bit Bit Bit

7 6 5 4 3 2 1 0

0 1 1 0 0 1 1 0

Values –> 128 64 32 16 8 4 2 1

Gaddis4.book Page 1271 Monday, January 6, 2003 5:16 PM

Page 40: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1272 Bitwise Operations and Binary Integer Forms

To calculate the two’s compliment of a number, first you must get the one’s compliment. Thismeans changing each 1 to a 0, and each 0 to a 1. Next, add 1 to the resulting number. What youhave is the two’s compliment. Here is how the computer stores the value –2.

2 is stored as 00000010Get the one’s compliment 11111101Add 1 1

-----------And the result is 11111110

As you can see, the highest order bit is still set to 1, indicating not only that this is a negative num-ber, but it is stored in two’s compliment representation.

Bitwise OperatorsC++ provides operators that let you perform logical operations on the individual bits of integervalues, and shift the bits right or left.

The Bitwise Negation OperatorThe bitwise negation operator is the ~ symbol. It is a unary operator that performs a negation, orone’s compliment on each bit in the field. The expression

~val

returns the one’s compliment of val. It does not change the contents of val. It could be used inthe following manner:

negval = ~val;

This will store the one’s compliment of val in negval.

The Bitwise AND OperatorThe bitwise AND operator is the & symbol. This operator performs a logical AND operation oneach bit of two operands. This means that it compares the two operands bit by bit. For each posi-tion, if both bits are 1, the result will be 1. If either or both bits are 0, the results will be 0. Here isan example:

andval = val & 0377;

The result of the AND operation will be stored in andval. There is a combined assignment ver-sion of this operator. Here is an example:

val &= 0377;

This is the same as:

val = val & 0377;

Gaddis4.book Page 1272 Monday, January 6, 2003 5:16 PM

Page 41: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Bitwise Operations and Binary Integer Forms 1273

The Bitwise OR OperatorThe bitwise OR operator is the | symbol. This operator performs a logical OR operation on eachbit of two operands. This means that it compares the two operands bit by bit. For each position, ifeither of the two bits is 1, the result will be 1. Otherwise, the results will be 0. Here is an example:

orval = val | 0377;

The result of the OR operation will be stored in orval. There is a combined assignment versionof this operator. Here is an example:

val |= 0377;

This is the same as

val = val | 0377;

The Bitwise EXCLUSIVE OR OperatorThe bitwise EXCLUSIVE OR operator is the ^ symbol. This operator performs a logical XORoperation on each bit of two operands. This means that it compares the two operands bit by bit.For each position, if one of the two bits is 1, but not both, the result will be 1. Otherwise, theresults will be 0. Here is an example:

xorval = val ^ 0377;

The result of the XOR operation will be stored in xorval. There is a combined assignment ver-sion of this operator. Here is an example:

val ^= 0377;

This is the same as:

val = val ^ 0377;

Using Bitwise Operators with MasksSuppose we have the following variable declarations:

char value = 110, cloak = 2;

The binary pattern for each of these two variables will be as follows:

The operation

value &= cloak;

value --> 0 1 1 0 1 1 1 0 = 110

cloak --> 0 0 0 0 0 0 1 0 = 2

Gaddis4.book Page 1273 Monday, January 6, 2003 5:16 PM

Page 42: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1274 Bitwise Operations and Binary Integer Forms

will perform a logical bitwise AND on the two variables value and cloak. The result will bestored in value. Remember a bitwise AND will produce a 1 only when both bits are set to 1. Hereis a diagram showing the result of the AND operation.

AND

equals

The 0’s in the cloak variable “hide” the values that are in the corresponding positions of thevalue variable. This is called masking. When you mask a variable, the only bits that will “showthrough” are the ones that correspond with the 1’s in the mask. All others will be turned off.

Turning Bits OnSometimes you may want to turn on selected bits in a variable and leave all of the rest alone. Thisoperation can be performed with the bitwise OR operator. Let’s see what happens when we ORthe value and cloak variables we used before, but using a different value for cloak.

char value = 110, cloak = 16;value |= mask;

This diagram illustrates the result of the OR operation:

OR

Equals

This caused bit 4 to be turned on and all the rest to be left alone.

Turning Bits OffSuppose that instead of turning specific bits on, you wish to turn them off. Assume we have thefollowing declaration:

char status = 127, cloak = 8;

Bit 3 of cloak is set to 1, and all the rest are set to 0. If we wish to set bit 3 of status to 0 we mustAND it with the negation of cloak. In other words, we must get the one’s compliment of cloak,then AND it with status. The statement would look like this:

status &= ~cloak;

value --> 0 1 1 0 1 1 1 0

cloak --> 0 0 0 0 0 0 1 0

result --> 0 0 0 0 0 0 1 0

value --> 0 1 1 0 1 1 1 0

cloak --> 0 0 0 1 0 0 0 0

result --> 0 1 1 1 1 1 1 0

Gaddis4.book Page 1274 Monday, January 6, 2003 5:16 PM

Page 43: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Bitwise Operations and Binary Integer Forms 1275

Here is what cloak’s bit pattern looks like:

And here is the one’s compliment of cloak:

Here is what we get when we AND status and the one’s compliment of cloak:

AND

Equals

Bit 3 of status is turned off, and all other bits were left unchanged.

Toggling BitsTo toggle a bit is to flip it off when it is on, and on when it is off. This can be done with theEXCLUSIVE OR operator. We will use the following variables to illustrate.

char status = 127, cloak = 8;

Our objective is to toggle bit 3 of status, so we will use the XOR operator.

status ^= cloak;

Here is the diagram of the operation:

XOR

Equals

Bit 3 of status will be set to 0. If we repeat this operation with the new value of status, this iswhat will happen:

XOR

cloak --> 0 0 0 0 1 0 0 0

~cloak --> 1 1 1 1 0 1 1 1

status --> 0 1 1 1 1 1 1 1

~cloak --> 1 1 1 1 0 1 1 1

result --> 0 1 1 1 0 1 1 1

status --> 0 1 1 1 1 1 1 1

cloak --> 0 0 0 0 1 0 0 0

result --> 0 1 1 1 0 1 1 1

status --> 0 1 1 1 0 1 1 1

cloak --> 0 0 0 0 1 0 0 0

Gaddis4.book Page 1275 Monday, January 6, 2003 5:16 PM

Page 44: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1276 Bitwise Operations and Binary Integer Forms

equals

Bit 3 of status will be toggled again, restoring it to its previous state.

Testing the Value of a BitTo test the value of an individual bit, you must use the AND operator. For example, if we want totest the variable bitvar to see if bit 2 is on, we must use a mask that has bit 2 turned on. Here isan example of the test:

if ((bitvar & 4) == 4)cout << "Bit 2 is on.\n";

Remember that ANDing a value with a mask will produce a value that hides all of the bits butthe ones turned on in the mask. If bit 2 of bitvar is on, the expression bitvar & 4 will returnthe value 4.

The parentheses around bitvar & 4 are necessary because the == operator has higher prece-dence than the & operator.

The Bitwise Left Shift OperatorThe bitwise left shift operator is two less-than signs (<<). It takes two operands. The operand onthe left is the one to be shifted, and the operand on the right is the number of places to shift.When the bit values are shifted left, the vacated positions to the right are filled with 0’s and thebits that shift out of the field are lost. Suppose we have the following variables:

char val = 2, shiftval;

The following statement will store in shiftval the value of val shifted left 2 places.

shiftval = val << 2;

Let’s see what is happening behind the scenes with the value in vals.

Realize, however that val itself is not being shifted. The variable shiftval is being set to thevalue of val shifted left 2 places. If we wanted to shift val itself, we could use the combinedassignment version of the left shift operator.

val <<= 2;

Shifting a number left by n places is the same as multiplying it by 2n. So, this example is the same as:

val *= 4;

result --> 0 1 1 1 1 1 1 1

Before shift 0 0 0 0 0 0 1 0

After shift 0 0 0 0 1 0 0 0

Gaddis4.book Page 1276 Monday, January 6, 2003 5:16 PM

Page 45: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Bitwise Operations and Binary Integer Forms 1277

The bitwise shift will almost always work faster, however.

The Bitwise Right Shift OperatorThe bitwise right shift operator is two greater-than signs (>>). Like the left shift operator, it takestwo operands. The operand on the left is the one to be shifted, and the operand on the right is thenumber of places to shift. When the bit values are shifted right, and the variable is signed, whatthe vacated positions to the left are filled with depends on the machine. They could be filled with0s, or with the value of the sign bit. If the variable is unsigned, the places will be filled with 0s. Thebits that shift out of the field are lost. Suppose we have the following variables:

char val = 8, shiftval;

The following statement will store in shiftval the value of val shifted right 2 places.

shiftval = val >> 2;

Let’s see what is happening behind the scenes with the value in val.

As before, val itself is not being shifted. The variable shiftval is being set to the value of valshifted right 2 places. If we wanted to shift val itself, we could use the combined assignment ver-sion of the right shift operator.

val >>= 2;

Shifting a number right by n places is the same as dividing it by 2n (as long as the number is notnegative). So, the example is the same as

val /= 4;

The bitwise shift will almost always work faster, however.

Bit FieldsC++ allows you to create data structures that use bits as individual variables. Bit fields must bedeclared as part of a structure. Here is an example.

struct {unsigned field1 : 1;unsigned field2 : 1;unsigned field3 : 1;unsigned field4 : 1;} fourbits;

The variable fourbits contains 4 bit fields: field1, field2, field3, and field4. Following thecolon after each name is a number that tells how many bits each field should be made up of. In

Before shift 0 0 0 0 1 0 0 0

After shift 0 0 0 0 0 0 1 0

Gaddis4.book Page 1277 Monday, January 6, 2003 5:16 PM

Page 46: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1278 Bitwise Operations and Binary Integer Forms

this example, each field is 1 bit in size. This structure is stored in memory in a regular unsignedint. Since we are only using 4 bits, the remaining ones will go unused.

Values may be assigned to the fields just as if it were a regular structure. In this example, weassign the value 1 to the field1 member:

fourbits.field1 = 1;

Because these fields are only 1 bit in size, we can only put a 1 or a 0 in them. We can expand thecapacity of bit fields by making them larger, as in the following example:

struct {unsigned field1 : 1;unsigned field2 : 2;unsigned field3 : 3;unsigned field4 : 4;} mybits;

Here, mybits.field1 is only 1 bit in size, but others are larger. mybits.field2 occupies 2 bits,mybits.field3 occupies 3 bits, and mybits.field4 occupies 4 bits. Here is a table that showsthe maximum values of each field:

This data structure uses a total of 10 bits. If you create a bit field structure that uses more bits thanwill fit in an int, the next int sized area will be used. Suppose we define the following bit fieldstructure on a system that has 16 bit integers.

struct {unsigned tiny : 1;unsigned small : 4;unsigned big : 6;unsigned bigger : 8;unsigned biggest : 9;} flags;

The problem that occurs here is that flags.bigger will straddle the boundary between the firstand second integer area. The compiler won’t allow this to happen. flags.tiny, flags.small,and flags.big will occupy the first integer area, and flags.bigger will reside in the secondinteger area. There will be 5 unused bits in the first. Likewise, since flags.bigger andflags.biggest cannot fit within one integer area, flags.biggest will reside in a third area.There will be 8 unused bits in the second area, and 7 unused bits in the third.

Field Name Number of Bits Maximum Value

mybits.field1 1 1

mybits.field2 2 3

mybits.field3 3 7

mybits.field4 4 15

Gaddis4.book Page 1278 Monday, January 6, 2003 5:16 PM

Page 47: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Bitwise Operations and Binary Integer Forms 1279

You can force a field to be aligned with the next integer area by putting an unnamed bit fieldwith a length of 0 before it. Here is an example:

struct {unsigned first : 1; : 0;unsigned second : 1; : 0;unsigned third : 2;} scattered;

The unnamed fields with the 0 width force scattered.second and scattered.third to bealigned with the next int area.

You can create unnamed fields with lengths other than 0. This way you can force gaps to existat certain places. Here is an example.

struct {unsigned first : 1; : 2;unsigned second : 1; : 3;unsigned third : 2;} gaps;

This will cause a 2-bit gap to come between gaps.first and gaps.second, and a 3-bit gap tocome between gaps.second and gaps.third.

Bit fields are not very portable when the physical order of the fields and the exact location ofthe boundaries are used. Some machines order the bit fields from left to right, but others orderthem from right to left.

Gaddis4.book Page 1279 Monday, January 6, 2003 5:16 PM

Page 48: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1280

Appendix JMulti-Source File Programs

Many of the programs you have written have been contained in one file. Once you start writinglonger programs, however, you need to break them into multiple smaller files. Generally, a multi-fileprogram consists of two types of files: ones that contain function definitions, and ones that containfunction prototypes and templates. Here is a common strategy for creating such a program:

� Group all specialized functions that perform similar tasks into the same files. For exam-ple, a file might be created for functions that perform mathematical operations. Another file might contain functions for user input and output.

� Group function main and all functions that play a primary role into one file.

� Create a separate header file for each file that contains function definitions. The header files contain prototypes for each function, and any necessary templates.

As an example, consider a multi-file banking program that processes loans, savings accounts, andchecking accounts. Figure J-1 illustrates the different files that might be used.

Each file whose name ends in .cpp contains function definitions. Each .cpp file has a corre-sponding header file whose name ends in .h. The header file contains function prototypes andtemplates for all functions that are part of the .cpp file. Each .cpp file has an #include directivethat reads its own header file. If the .cpp file contains calls to functions in another .cpp file, it willhave an #include directive to read the header file for that function as well.

All of the .cpp files are compiled into separate object files. The object files are then linkedinto a single executable file. This process is most easily performed with a project or make utility.These utilities allow you to create a list of files that make up a multi-file program. The compilerthen automatically compiles and links all the necessary components into an executable file.(Check with your compiler manuals for instructions on using its specific utilities.)

> Note: Appendix K, L, and M provide instructions for creating multi-file projects using Microsoft Visual C++ 6.0, Borland C++ Builder 5.0, and Microsoft Visual C++ .NET.

Gaddis4.book Page 1280 Monday, January 6, 2003 5:16 PM

Page 49: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Multi-Source File Programs 1281

Global Variables in a Multi-File ProgramNormally, global variables are only in scope in the file that defines them. In order for a global vari-able defined in file A to be accessible to functions in file B, file B must contain an extern declara-tion of the variable. This means the keyword extern must precede the data type name in thedeclaration. The extern declaration does not define another variable, but extends the scope ofthe existing variable.

If a global variable is defined as static, its scope cannot be extended beyond the file it is definedin. This can be done to ensure that a variable is private to one file, and its name is hidden outsidethe file it is defined in.

Figure J-2 shows some global variable declarations in the example banking program. The vari-ables customer (a character array) and accountNum (an int) are defined in bank.cpp. The scopeof these variables is extended to loans.cpp, savings.cpp, and checking.cpp because each filehas an extern declaration of the variables. Even though the variables are defined in bank.cpp,they may be accessed by any function whose file contains an extern declaration of them.

Figure J-1

File: 1: bank.cpp

Contains main and allprimary functions

File: 2: bank.h

Contains prototypesfor functionsin bank.cpp.

File: 3: loans.cpp

Contains all functionsfor processing loans

File: 4: loans.h

Contains prototypes for functionsin loans.cpp

File: 7: checking.cpp

Contains all functionsfor processing checkingaccounts

File: 8: checking.h

Contains prototypes for functionsin checking.cpp

File: 5: savings.cpp

Contains all functionsfor processing savingsaccounts

File: 6: savings.h

Contains prototypes for functionsin savings.cpp

Gaddis4.book Page 1281 Monday, January 6, 2003 5:16 PM

Page 50: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1282 Multi-Source File Programs

Figure J-2

checking.cpp savings.cpp

#include "checking.h" #include "checking.h" ... ... (other #include (other #include directives) directives)

extern char customer[]; extern char customer[]; extern int accountNum; extern int accountNum; static float balance; static float balance; static float checkAmnt; static int interest; static float deposit; static float deposit; static float withdrawl; function5() { function7() ... { } ... function6() } { function8() ... { } ... }

bank.cpp loans.cpp

#include "bank.h" #include "loans.h" #include "loans.h" ... #include "savings.h" (other #include #include "checking.h" directives) ...

(other #include extern char customer[];directives) extern int accountNum;

static float loanAmount; char customer[35]; static int months; int accountNum; static float interest;

static float payment; int main() { function3() ... { } ... function1() } { function4() ... { } ... function2() } { ... }

Gaddis4.book Page 1282 Monday, January 6, 2003 5:16 PM

Page 51: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Multi-Source File Programs 1283

Each file in the example also contains static global variable definitions. These variables maynot be accessed outside the file they are defined in. The variable interest, for example, is definedas a static global in both loans.cpp and savings.cpp. This means each file has its own variablenamed interest, which is not accessible outside the file it is defined in. The same is true of thevariables balance and deposit defined in savings.cpp and checking.cpp.

Class DeclarationsIt is common to store class declarations and member function definitions in their own separatefiles. Typically, program components are stored in the following fashion:

� A class declaration is stored in its own header file, which is called the specification file. The name of the specification file is usually the same as the class, with a .h extension.

� The member function definitions for the class are stored in a separate .cpp file, which is called the implementation file. The file usually has the same name as the class, with the .cpp extension.

� Any program that uses the class should #include the class’s header file. The class’s .cpp file (that which contains the member function definitions) should be compiled and linked with the main program. This process can be automated with a project or make utility, or an integrated development environment such as Visual C++.

Gaddis4.book Page 1283 Monday, January 6, 2003 5:16 PM

Page 52: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1284

Appendix KIntroduction to Microsoft Visual C++ 6.0

This appendix serves as a quick reference for performing the following operations using theMicrosoft Visual C++ integrated development environment (IDE):

� Starting a new project and entering code

� Saving a project to disk

� Compiling and executing a project

� Opening an existing project

� Creating multi-file projects

Starting a New ProjectThe first step in creating a program with Visual C++ is to start a project. A project is a group ofone or more files that make up a software application. (Even if your program consists of no morethan a single source code file, it still must belong to a project.)

To start a project:1. Launch Microsoft Visual C++. The IDE window opens, as shown in Figure K-1.

Gaddis4.book Page 1284 Monday, January 6, 2003 5:16 PM

Page 53: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ 6.0 1285

2. Click File on the menu bar. On the File menu, click New. You see the dialog box shown in Figure K-2.

3. All of the programs in this book are console programs, so click WIN32 Console Application in the list of project types.

Figure K-1

Figure K-2

Gaddis4.book Page 1285 Monday, January 6, 2003 5:16 PM

Page 54: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1286 Introduction to Microsoft Visual C++ 6.0

4. Enter the name of the project (such as lab6, or program5) in the Project name text box. (Do not enter an extension.)

5. When you create a project, Visual C++ creates a folder where all the project files are normally stored. The folder is called the project folder and it has the same name as the project. The Location text box lets you type in or browse to a location on your system where the project folder will be created. If you do not want to keep the default location, click the ellipses (...) button to select a different one. Once you have selected a folder the dialog box should appear similar to Figure K-3.

6. Click the OK button. You now see the dialog shown in Figure K-4.

7. Make sure “An empty project” is selected and click the Finish button. You see the dialog box shown in Figure K-5.

Figure K-3

Figure K-4

Gaddis4.book Page 1286 Monday, January 6, 2003 5:16 PM

Page 55: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ 6.0 1287

8. Click the OK button. You return to the IDE, as shown in Figure K-6.

9. Now you must insert a new C++ source file into the project. Click Project on the menu bar. On the Project menu, click Add To Project, then click New… You see the dialog box shown in Figure K-7.

Figure K-5

Figure K-6

Gaddis4.book Page 1287 Monday, January 6, 2003 5:16 PM

Page 56: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1288 Introduction to Microsoft Visual C++ 6.0

10. In the list of file types, click C++ Source File.

11. In the File name text box, enter the name of the source file. (This can be the same as the project name, if you wish.) Be sure to type the .cpp extension. Your screen should look simi-lar to Figure K-8.

12. Click the OK button. You will return to the IDE. The right pane is now a text editor. This is where you type your C++ source code, as shown in Figure K-9.

Figure K-7

Figure K-8

Gaddis4.book Page 1288 Monday, January 6, 2003 5:16 PM

Page 57: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ 6.0 1289

Saving Your Project to DiskIt is important to periodically save your work. To do so, click File on the menu bar, then clickSave Workspace on the File menu.

Opening an Existing ProjectTo open an existing project, click File on the menu bar, then click on Open Workspace… Use theresulting dialog box to browse to the location of your project. When you have located yourproject, double-click it.

Compiling and ExecutingOnce you have entered a program’s source code, you may compile and execute it by any of the fol-lowing methods:

� By clicking the button

� By pressing Ctrl+F5

� By clicking Build on the menu bar, and then clicking Execute.

Figure K-9

Gaddis4.book Page 1289 Monday, January 6, 2003 5:16 PM

Page 58: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1290 Introduction to Microsoft Visual C++ 6.0

The window at the bottom of the screen shows status messages as the program is compiled. Errormessages are also displayed there. If you see an error message, double-click it and the editor willmove the text cursor to the line of code where the error was encountered.

For example, look at the program in Figure K-10. The first cout statement is missing a semi-colon. When you double-click the error message, the text cursor moves to the line with the error.(Actually, in this case the cursor appears on the line after the statement with the missing semico-lon. The compiler did not detect that the semicolon was missing until it encountered the begin-ning of the next line. Finding errors is not always straightforward.)

If the program compiles successfully, an MS-DOS window appears and the program runs. This isillustrated in Figure K-11.

Creating a Multi-File ProjectMany of your programs consist of more than one file. For example, consider the followingprogram:

// Filename: RectData.cpp// This program uses multiple files#include <iostream>#include "rectang.h" // contains Rectangle class declarationusing namespace std;

Figure K-10

Gaddis4.book Page 1290 Monday, January 6, 2003 5:16 PM

Page 59: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ 6.0 1291

// Don't forget to link this program with rectang.cpp!int main(){

Rectangle box;float wide, long;

cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> wide;cout << "What is the length? ";cin >> long;box.setData(Wide, Long);box.calcArea();cout << "Here rectangle's data:\n";cout << "Width: " << box.getWidth() << endl;cout << "Length: " << box.getLength() << endl;cout << "Area: " << box.getArea() << endl;return 0;

}

This program relies on two other files: rectang.h and rectang.cpp. Before compiling this pro-gram, Rectang.h and Rectang.cpp must be added to the project. The steps listed here show youhow to set the project up with all three of the existing files as members.

1. Start a new project by following steps 1 through 8 under the section Starting a New Project, at the beginning of this appendix. Name the project RectData.

2. Insert the main C++ source file into the project. Click Project on the menu bar. On the Project menu, click Add To Project, then click Files… You see the Insert Files into Project dialog box. Use the dialog box to find the file RectData.cpp on the student disk, under the Appendix K folder. When you locate the file, click it and then click the OK button. The file RectData.cpp is now a member of the project.

Figure K-11

Gaddis4.book Page 1291 Monday, January 6, 2003 5:16 PM

Page 60: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1292 Introduction to Microsoft Visual C++ 6.0

3. Now insert the Rectang.cpp source file into the project. Click Project on the menu bar. On the Project menu, click Add To Project, then click Files… Again, you see the Insert Files into Project dialog box. Use the dialog box to find the file Rectang.cpp on the student disk. When you locate the file, click it and then click the OK button. The file Rectang.cpp is now a member of the project.

4. Now insert the Rectang.h header file into the project. Click Project on the menu bar. On the Project menu, click Add To Project, then click Files… As before, you see the Insert Files into Project dialog box. Use the dialog box to find the file Rectang.h on the student disk. When you locate the file, click it and then click the OK button. The file Rectang.h is now a mem-ber of the project.

5. At this point, RectData.cpp, Rectang.cpp, and Rectang.h are members of the project. The left pane of the IDE, which is called the workspace window, is shown in Figure K-12. This window allows you to navigate among all the files in the project.

The two tabs at the bottom of the workspace window allow you to switch between Class View andFile View. Click on the File View tab. You should see a display similar to Figure K-13.

6. Click the small + sign that appears next to RectData files. The display expands, as shown in Figure K-14, to show folders labeled Source Files, Header Files, and Resource Files. These folders organize the names of the files that are members of the project.

Figure K-12

Figure K-13

Figure K-14

Gaddis4.book Page 1292 Monday, January 6, 2003 5:16 PM

Page 61: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ 6.0 1293

7. Notice that the Source Files and Header Files folders have small + signs next to them. This indicates the folders hold filenames. Click on the small + sign next to the Source Files and Header Files folders. The filenames RectData.cpp, Rectang.cpp, and Rectang.h are listed, as shown in Figure K-15.

8. Double-click on the name RectData.cpp. The file is displayed in the editor. (You may display any of the files in the editor by double-clicking its name.)

9. You may compile and execute the project by following the steps listed under the section Com-piling and Executing.

Creating a New Multi-File ProjectIf you are creating a new multi-file project (not from existing files), follow steps 1 through 12under the section Starting a New Project. Type the code for the main source file into the editor.When you are ready to create another source file (such as a header file for a class declaration, or a.cpp file to contain class member function definitions), follow these steps.

1. Click Project on the menu bar, click Add to Project, then click New.

2. In the New dialog box, click C++ Source File if you are creating a new .cpp file, or C/C++ Header File if you are creating a new header file.

3. In the File Name text box, enter the name of the file. Be sure to include the proper extension.

4. Click the OK button. You will return to the text editor. Enter the code for the new file.

5. Repeat the steps above for each new file you wish to add to the project.

Removing a File from a ProjectTo remove a file from a project, simply select the file’s name in the project browser window andpress the Delete key. This operation removes the file from the project, but does not delete it fromthe disk.

Figure K-15

Gaddis4.book Page 1293 Monday, January 6, 2003 5:16 PM

Page 62: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1294 Introduction to Microsoft Visual C++ 6.0

Where Files are CreatedWhen you create a new project, Visual C++ creates a project folder with the same name as theproject. This is where all of the files associated with the project are normally stored. You can spec-ify the location of the folder when you create the project. (See step 5 of the Starting a New Projectsection.)

For example, suppose we’ve created a project named Lab5, and its project folder is atC:\MyProjects\Lab5. All of the C++ source files that you have created for this project will bestored in that folder. In addition, Visual C++ will create another folder named Debug, under theC:\MyProjects\Lab5 folder. The Debug folder will contain the project’s executable file and itsobject file(s).

It’s important to know the location of the project folder when writing code that opens filesfor input or output. When running a program from the Visual C++ IDE, the project folder is thedefault location for all data files. For example, suppose our Lab5 project creates a file with the fol-lowing code:

ofstream outputFile("names.txt");

Because we have not specified a path with the file name, the file will be created in theC:\MyProjects\Lab5 project folder. Similarly, if our program attempts to open an existing filefor reading, it will look in the project folder by default. For example, suppose our Lab5 programattempts to open a file with the following statement:

ifstream inputFile("names.txt");

Because we have not specified a path, the program will look for the file in the project folder,C:\MyProjects\Lab5.

If we want to open a file in a location other than the project folder, we must provide a path aswell as a file name. For example, the following statement opens a file named data.txt in theC:\Data folder.

ofstream outputFile("C:\\Data\\Data.txt");

Notice that we’ve used two backslashes in the path where you normally use only one.Remember, in a literal string, the compiler interprets the backslash character as the beginning ofan escape sequence. In order to represent a backslash as a character in a literal string, you mustuse two backslashes.

Here’s another example:

ifstream inputFile("A:\\names.txt");

This statement attempts to open the names.txt file in the root folder of drive A.

Gaddis4.book Page 1294 Monday, January 6, 2003 5:16 PM

Page 63: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1295

Appendix LIntroduction to Borland C++ Builder 5.0

This appendix serves as a quick reference for performing the following operations using theBorland C++ Builder integrated development environment (IDE):

� Starting a new project and entering code

� Saving a project to disk

� Compiling and executing a project

� Opening an existing project

� Creating multi-file projects

Starting a New ProjectThe first step in creating a program with Borland C++ Builder is to start a project. A project is agroup of one or more files that make up a software application. (Even if your program consists ofno more than a single source code file, it still must belong to a project.)

To start a project:

1. Launch Borland C++ Builder. The IDE windows open on the desktop, similar to what is shown in Figure L-1.

Gaddis4.book Page 1295 Monday, January 6, 2003 5:16 PM

Page 64: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1296 Introduction to Borland C++ Builder 5.0

2. When C++ Builder starts, it automatically begins an empty project. This project is usually named Project1. This project is not set up properly for the programs in this book, however, so you will begin a new project. Click File on the menu bar. On the File menu, click New. You see the dialog box shown in Figure L-2. (Make sure the New tab is selected.)

Figure L-1

Figure L-2

Gaddis4.book Page 1296 Monday, January 6, 2003 5:16 PM

Page 65: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Borland C++ Builder 5.0 1297

3. All of the programs in this book are console programs, so click Console Wizard, then click the OK button. The dialog box shown in Figure L-3 is displayed.

4. Make sure C++ and Console Application are selected. No other options should be selected. Click the OK button. A dialog box appears asking “Save changes to Project1?” (The name you see may be different from Project1.) Because the default project is empty, click the No button. Your screen now looks similar to Figure L-4.

Figure L-3

Figure L-4

Gaddis4.book Page 1297 Monday, January 6, 2003 5:16 PM

Page 66: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1298 Introduction to Borland C++ Builder 5.0

5. The right-most pane in the window shown above is the text editor. C++ Builder automati-cally creates a program “skeleton” for you. The skeleton contains some preprocessor direc-tives and an empty function main. You can modify the code skeleton, or erase it and write your own program from scratch. For example, Figure L-5 shows a simple program that has been written in the editor after the default program skeleton has been erased.

Saving Your Project to DiskIt is important to periodically save your work. To save your project for the first time, click File onthe menu bar, and then click Save Project As… on the File menu. A Save As dialog box appears forthe C++ source file. The source file’s default name is Unit1.cpp. Click the OK button if you wantto keep this name. If you wish to save the source file under a different name, enter the new name,and click the OK button. Next, a Save As dialog box appears for the project file. A default name,such as Project2.bpr, will appear as the project file’s name. Click the OK button if you want tokeep this name. If you wish to save the project file under a different name, enter the new name,and click the OK button.

After you have saved the project the first time, you may save it subsequent times by clickingFile on the menu bar, then clicking Save All.

Opening an Existing ProjectTo open an existing project, click File on the menu bar, then click on Open Project… Use theresulting dialog box to browse to the location of your project file. When you have located yourproject file, double-click it.

Figure L-5

Gaddis4.book Page 1298 Monday, January 6, 2003 5:16 PM

Page 67: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Borland C++ Builder 5.0 1299

Compiling and ExecutingOnce you have entered a program’s source code, you may compile and execute it by any of the fol-lowing methods:

� by clicking the button

� by pressing F9

� by clicking Run on the menu bar, and then clicking Run.

A window at the bottom of the editor pane appears if errors are found in your program. Double-click an error message in the window, and the editor will highlight the line of code where the errorwas encountered.

For example, look at the program in Figure L-6. The cout statement is missing a semicolon.By double-clicking the error message, the text cursor is positioned on the line with the error.(Actually, in this case the cursor appears on the line after the statement with the missing semico-lon. The compiler did not detect that the semicolon was missing until it encountered the begin-ning of the next line. Finding errors is not always straightforward.)

If the program compiles successfully, an MS-DOS window appears and the program runs. This isillustrated in Figure L-7.

> Note:The program shown in the example above has a cin.get() statement as the last statement in the program. The statement causes the program to pause until the user presses the Enter key. The statement is in the program because the MS-DOS window automatically closes as soon as the program is finished. If

Figure L-6

Gaddis4.book Page 1299 Monday, January 6, 2003 5:16 PM

Page 68: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1300 Introduction to Borland C++ Builder 5.0

the program above did not have the cin.get() statement, it would quickly flash the message "This is a simple program" on the screen, and the MS-DOS window would suddenly close.

Sometimes a single cin.get() statement will not pause the screen. (This is because a prevouscin statement has left a newline character in the keyboard buffer.) A better way of pausing thescreen is to include the conio.h header file, and use the getch() function at the end of the pro-gram. This is demonstrated in the next example.

Creating a Multi-File ProjectMany of your programs consist of more than one file. For example, consider the followingprogram:

// This program demostrates a simple class#include <conio.h> // For the getch() function#include <iostream>#include "rectang.h" // Contains Rectangle class declarationusing namespace std;

// Don't forget to link this program with rectang.cpp!

int main(){

Rectangle box;float wide, long;

cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> wide;

Figure L-7

Gaddis4.book Page 1300 Monday, January 6, 2003 5:16 PM

Page 69: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Borland C++ Builder 5.0 1301

cout << "What is the length? ";cin >> long;box.setData(wide, long);box.calcArea();cout << "Here rectangle's data:\n";cout << "Width: " << box.getWidth() << endl;cout << "Length: " << box.getLength() << endl;cout << "Area: " << box.getArea() << endl;getch();return 0;

}

This program relies on two other files: Rectang.h and Rectang.cpp. Before compiling this pro-gram, rectang.h and rectang.cpp must be added to the project. The steps listed below showyou how to set the project up with all three files as members.

1. Start a new project by following steps 1 through 5 under the section Starting a New Project, at the beginning of this appendix.

2. Enter the main C++ source code (shown above) into the text editor. Your editor window will look similar to Figure L-8.

Figure L-8

Gaddis4.book Page 1301 Monday, January 6, 2003 5:16 PM

Page 70: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1302 Introduction to Borland C++ Builder 5.0

3. Now insert the Rectang.cpp source file into the project. Click Project on the menu bar. On the Project menu, then click Add To Project… The Add to Project dialog box. Use the dialog box to find the file Rectang.cpp in the Appendix L folder on the student disk. When you locate the file, click it and then click the OK button. The file Rectang.cpp is now a member of the project. Your editor window now looks similar to Figure L-9.

5. At this point, the main source file and Rectang.cpp are members of the project. At the top of the editor window are tabs for the two files. Click on either tab to bring the file’s contents into view.

The left pane of the editor window, which is called the Class Explorer, is used to bring class decla-rations into the editor window. In the figure shown above, a folder titled Project2 – Classesappears. (Your screen will look similar, but the project name may be different.) Click the small +sign to expand the view. The window looks similar to Figure L-10.

Figure L-9

Figure L-10

Gaddis4.book Page 1302 Monday, January 6, 2003 5:16 PM

Page 71: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Borland C++ Builder 5.0 1303

6. Click the small + sign next to Rectangle. The view expands further to show entries for all the members of the Rectangle class. Your window should be similar to Figure L-11.

7. By double-clicking any of the Rectangle class’s member names in the Class Explorer window, you bring the source file containing the member’s declaration into the editor. For example, by double-clicking the area member, the Rectang.h file is brought into the editor, as shown in Figure L-12.

Figure L-11

Figure L-12

Gaddis4.book Page 1303 Monday, January 6, 2003 5:16 PM

Page 72: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1304 Introduction to Borland C++ Builder 5.0

8. You may compile and execute the project by following the steps listed under the section Com-piling and Executing.

Removing a File from a ProjectTo remove a file from a project, click Project on the menu bar, then click Remove from Project…The Remove from Project dialog box appears, as shown in Figure L-13.

Select the name of the file you wish to remove from the project and click the OK button. The filewill be removed from the project. (It will not be erased from the disk, however.)

Opening and Running an Existing Program1. Launch Borland C++ Builder. The IDE windows open on the desktop, similar to what is

shown in Figure L-14.

Figure L-13

Figure L-14

Gaddis4.book Page 1304 Monday, January 6, 2003 5:16 PM

Page 73: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Borland C++ Builder 5.0 1305

2. When C++ Builder starts, it automatically begins an empty project. This project is usually named Project1. This project is not set up properly for the programs in this book, however, so you will begin a new project. Click File on the menu bar. On the File menu, click New. You see the dialog box shown in Figure L-15. (Make sure the New tab is selected.)

3. All of the programs in this book are console programs, so click Console Wizard, then click the OK button. The dialog box shown in Figure L-16 is displayed.

4. Make sure C++ and Console Application are selected. Then, click the Specify project source checkbox. At this point, you may either type the name and location of the file in the textbox, or click the button to browse for the file. Figure L-17 shows an example of the dialog box where the file C:\Programs\Chap2\pr2-1.cpp has been selected.

Figure L-15

Figure L-16

Gaddis4.book Page 1305 Monday, January 6, 2003 5:16 PM

Page 74: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1306 Introduction to Borland C++ Builder 5.0

5. Click the OK button. Your screen now looks similar to Figure L-18. The program you selected is loaded into the text editor.

6. You may compile and execute the program by any of the following methods:

� by clicking the button

� by pressing F9

� by clicking Run on the menu bar, and then clicking Run.

Figure L-17

Figure L-18

Gaddis4.book Page 1306 Monday, January 6, 2003 5:16 PM

Page 75: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Borland C++ Builder 5.0 1307

A window at the bottom of the editor pane appears if errors are found in your program. Double-click an error message in the window, and the editor will highlight the line of code where the errorwas encountered.

If the program compiles successfully, an MS-DOS window appears and the program runs.

Where Files are CreatedWhen you save a new project, you normally save all of the files associated with that project in thesame folder. (See the Saving Your Project to Disk section.) This folder is known as the project folder.

For example, suppose we’ve created a project named Lab5, and saved it in the folderC:\MyProjects\Lab5. All of the C++ source files that you have created for this project, as well asthe project file that ends with the extension .bpr, will be stored in that folder.

It’s important to know the location of the project folder when writing code that opens filesfor input or output. When running a program from the C++ Builder IDE, the project folder is thedefault location for all data files. For example, suppose our Lab5 project creates a file with the fol-lowing code:

ofstream outputFile("names.txt");

Because we have not specified a path with the file name, the file will be created in theC:\MyProjects\Lab5 project folder. Similarly, if our program attempts to open an existing filefor reading, it will look in the project folder by default. For example, suppose our Lab5 programattempts to open a file with the following statement:

ifstream inputFile("names.txt");

Because we have not specified a path, the program will look for the file in the project folder,C:\MyProjects\Lab5.

If we want to open a file in a location other than the project folder, we must provide a path aswell as a file name. For example, the following statement opens a file named data.txt in theC:\Data folder.

ofstream outputFile("C:\\Data\\Data.txt");

Notice that we’ve used two backslashes in the path where you normally use only one. Remember,in a literal string, the compiler interprets the backslash character as the beginning of an escapesequence. In order to represent a backslash as a character in a literal string, you must use twobackslashes.

Here’s another example:

ifstream inputFile("A:\\names.txt");

This statement attempts to open the names.txt file in the root folder of drive A.

Gaddis4.book Page 1307 Monday, January 6, 2003 5:16 PM

Page 76: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1308

Appendix MIntroduction to Microsoft Visual C++ .NET

This appendix serves as a quick reference for performing the following operations using theMicrosoft Visual C++ .NET integrated development environment (IDE):

� Starting a new project and entering code

� Saving a project to disk

� Compiling and executing a project

� Opening an existing project

� Creating multi-file projects

Starting a New projectThe first step in creating a program with Visual C++ .NET is to start a project. A project is a groupof one or more files that make up a software application. (Even if your program consists of nomore than a single source code file, it still must belong to a project.)

To start a project:1. Launch Microsoft .NET. The IDE window opens and allows for a number of options, which

are shown in Figure M-1. Click the New Project button in the main window as shown in Fig-ure M-1. (If you do not see the New Project button, click File on the menu bar, then click New, then click Project.)

Gaddis4.book Page 1308 Monday, January 6, 2003 5:16 PM

Page 77: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ .NET 1309

2. The New Projects dialog box appears, as shown in Figure M-2. Under Project Types (the leftpane) select Visual C++ Projects. Under Templates (the right pane), scroll down to andselect WIN 32 Project.

Figure M-1

Figure M-2

Menu bar

New Project Button

Gaddis4.book Page 1309 Monday, January 6, 2003 5:16 PM

Page 78: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1310 Introduction to Microsoft Visual C++ .NET

3. When you create a project, Visual C++ .NET creates a folder where all the project files are normally stored. The folder is called the project folder and it has the same name as the project. The Location text box lets you type in or browse to a location on your system where the project folder will be created. If you do not want to keep the default location, click the Browse... button to select a different one. Once you have selected a folder the dialog box should appear similar to Figure K-3.

4. Enter the name of the project (such as Lab6, or Program5) in the Name text box. (Do not enter an extension for the filename.) Figure M-3 shows an example. Click the OK button if you are satisfied with the name and directory for the project. The Win32 Application Wizard starts and you should see the dialog box shown in Figure M-4.

Figure M-3

Figure M-4

Application Settings option

Gaddis4.book Page 1310 Monday, January 6, 2003 5:16 PM

Page 79: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ .NET 1311

5. Click the Application Settings options, which is shown in Figure M-4. The dialog box should now appear as shown in Figure M-5.

6. Click the Console Application button and click the Empty Project check box. The dialog box should now appear as shown in Figure M-6.

7. Click the Finish button to build the project. This will take you to the main screen with an empty project as shown in Figure M-7.

Figure M-5

Figure M-6

Gaddis4.book Page 1311 Monday, January 6, 2003 5:16 PM

Page 80: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1312 Introduction to Microsoft Visual C++ .NET

8. Now you should insert a new C++ source file into the project. Click Project on the menu bar and then choose Add New Item. You should see the Add New Item dialog box shown in Fig-ure M-8. Click the C++ File icon in the templates pane. In the name box, enter the name of the source file. (This can be the same as the project name, if you wish.) Figure M-9 shows an example of the dialog box with this step completed.

Figure M-7

Figure M-8

Gaddis4.book Page 1312 Monday, January 6, 2003 5:16 PM

Page 81: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ .NET 1313

9. Click the Open button to create the C++ file. This creates an empty source file and adds it to the project. You should see something similar to Figure M-10. Note that above the text editor is a tab showing the name of the file that is currently open. To the right is a window showing the files that are in the project. This is called the Solution Explorer window. Figure M-11 shows the screen after a C++ program has been entered into the editor.

Figure M-9

Figure M-10

Name of file currentlyopen in the editor

Solution Explorer windowshows the files inthis project

Gaddis4.book Page 1313 Monday, January 6, 2003 5:16 PM

Page 82: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1314 Introduction to Microsoft Visual C++ .NET

Saving Your Project to DiskIt is important to periodically save your work. To do so, click File on the menu bar, then click SaveAll on the File menu.

Compiling and ExecutingOnce you have entered a program’s source code, you may compile and execute it by any of the fol-lowing methods:

� Click the Debug menu item and choosing Start without Debugging as shown in Figure M-12.

� by pressing Ctrl+F5

Figure M-11

Gaddis4.book Page 1314 Monday, January 6, 2003 5:16 PM

Page 83: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ .NET 1315

After performing one of these steps, if you see the dialog box in Figure M-13, click the Yes button.

The Output window shown in Figure M-14 appears at the bottom of the screen. This window showsstatus messages as the program is compiled. Error messages are also displayed in this same area.

When compiling a program you will see the dialog box in Figure M-15 if the program hassyntax errors. Click the No button. Next you will see one or more error messages displayed at thebottom of the screen, as shown in Figure M-16.

Figure M-12

Figure M-13

Figure M-14

Figure M-15

Gaddis4.book Page 1315 Monday, January 6, 2003 5:16 PM

Page 84: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1316 Introduction to Microsoft Visual C++ .NET

If you see an error message, double-click it and the editor will move the text cursor to theline of code where the error was encountered. For example, look at the program in Figure M-17.The first cout statement is missing a semi-colon. By double-clicking the error message, the textcursor is positioned on the line with the error. (Actually, in this case the cursor appears on theline after the statement with the missing semicolon. The compiler did not detect that the semi-colon was missing until it encountered the beginning of the next line. Finding errors is notalways straightforward.)

Figure M-16

Figure M-17

Double-click this error message

Gaddis4.book Page 1316 Monday, January 6, 2003 5:16 PM

Page 85: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ .NET 1317

If the program compiles successfully, an MS DOS window appears and the program runs.This is illustrated in Figure M-18.

Opening an Existing ProjectTo open an existing project, click File on the menu bar, then click Open Solution. Use the result-ing dialog box to browse to the folder containing your project. In that folder you should see asolution file. This file has the same name that you gave the project, and the .sln extension. Dou-ble-click this file to open the project.

> Note: If the source file does not open in the editor, double-click the name of the file in the Solutions Explorer window.

Creating a Multi-File ProjectMany of your programs consist of more than one file. For example, consider the followingprogram, which is stored in the Appendix M folder on the student disk, under the nameRectangleData.cpp:

// This program uses the Rectangle class's specification// and implementation files.#include <iostream>#include "Rectangle.h" // Contains the class declaration.using namespace std;

int main(){

Rectangle box; // Define an instance of the class.float rectWidth, // Local variable for width.

rectLength; // Local variable for length.

Figure M-18

Gaddis4.book Page 1317 Monday, January 6, 2003 5:16 PM

Page 86: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1318 Introduction to Microsoft Visual C++ .NET

// Get the rectangle's width and length from the user.cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> rectWidth;cout << "What is the length? ";cin >> rectLength;

if (!box.setWidth(rectWidth)) // Store the width.cout << "Invalid value for width.\n";

else if (!box.setLength(rectLength)) // Store the length.cout << "Invalid value for length.\n";

else{

// Display the rectangle's data.cout << "Here is the rectangle's data:\n";cout << "Width: " << box.getWidth() << endl;cout << "Length: " << box.getLength() << endl;cout << "Area: " << box.getArea() << endl;

}return 0;

}

This program relies on two other files: Rectangle.h and Rectang.cpp. Before compiling thisprogram, Rectangle.h and Rectangle.cpp must be added to the project. The following stepsshow you how to set the project up with all three of the existing files as members.

1. Start a new project by following steps 1–9 under the section Starting a New Project, at the beginning of this appendix. Name the project RectangleData.

2. Now you will insert the main C++ source file into the project. Click Project on the menu bar. On the Project menu, click Add Existing Item. Then insert the student disk and use the browse feature to locate the file RectangleData.cpp in the Appendix M folder on the disk. When you locate the file, click it and click the open button (or just double click it.)

3. Now you will insert the Rectangle.cpp source file into the project. Click Project on the menu bar. On the Project menu, click Add Existing Item. Then use the browse feature to locate the file Rectangle.cpp in the Appendix M folder on the student disk. When you locate the file, click it and click the Open button. The file Rectangle.cpp is now a member of your project.

4. Now you will insert the Rectangle.h header file into the project. Repeat the process in step 3 to locate and insert the Rectangle.h file. The Rectangle.h file is now a member of the project.

5. At this point, RectangleData.cpp, Rectangle.cpp, and Rectangle.h are members of the project. You can use the Solution Explorer window to navigate among all the files in the project. Notice the two tabs at the bottom of the Solution Explorer window, as shown in Figure M-19. One is the Solution Explorer tab and the other is the Class View tab. These tabs allow you to switch between a file-oriented view of your project (the Solution Explorer tab) and a class-oriented view of your projected (the Class View tab). Make sure the Solution Explorer tab is selected.

Gaddis4.book Page 1318 Monday, January 6, 2003 5:16 PM

Page 87: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ .NET 1319

6. You can expand or contract items in the view by clicking the – (minus) sign that appears beside the file folders (a plus sign if the folders are closed). You should see the three files you added to the project shown by default. Double-click on the name RectangleData.cpp. The file is dis-played in the editor. (You may display any of these files in the editor by double-clicking their names.)

Notice that in Figure M-20 there are tabs with the names of each file in the project just above the editor. You may click any of these tabs to rapidly switch between files in a multi-file project.

Figure M-19

Figure M-20

Solution Explorer tab Class View tab

File tabs

Gaddis4.book Page 1319 Monday, January 6, 2003 5:16 PM

Page 88: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1320 Introduction to Microsoft Visual C++ .NET

Creating a New Multi-File ProjectIf you are creating a new multi-file project (not from existing files), follow steps 1 through 9under the section Starting a New Project. Type the code for the main source file into the editor.When you are ready to create another source file (such as the header file for a class declaration, ora .cpp file to contain class member function definitions), follow these steps.

1. Click Project on the menu bar, click Add New Item.

2. In the Add New Item box, click the C++ File (.cpp) icon if you are creating a new .cpp file or Header File (.h) if you are creating a new header file.

3. In the File Name text box, enter the name of the file. Extensions are automatically included for the various types.

4. Click the Open button. You will return to the text editor. Enter the code for the new file.

Repeat these steps for each new file you wish to add to the project.

Removing a File from a ProjectTo remove a file from a project, simply select the file’s name in the solution explorer window andpress the Delete key. This operation removes the file from the project, but does not delete it fromthe disk.

Where Files are CreatedWhen you create a new project, Visual C++ .NET creates a project folder with the same name asthe project. This is where all of the files associated with the project are normally stored. You canspecify the location of the folder when you create the project. (See step 3 of the Starting a NewProject section.)

For example, suppose we’ve created a project named Lab5, and its project folder is atC:\MyProjects\Lab5. All of the C++ source files that you have created for this project will bestored in that folder. In addition, Visual C++ .NET will create another folder named Debug,under the C:\MyProjects\Lab5 folder. The Debug folder will contain the project’s executable fileand its object file(s).

It’s important to know the location of the project folder when writing code that opens filesfor input or output. When running a program from the Visual C++ IDE, the project folder is thedefault location for all data files. For example, suppose our Lab5 project creates a file with the fol-lowing code:

ofstream outputFile("names.txt");

Because we have not specified a path with the file name, the file will be created in theC:\MyProjects\Lab5 project folder. Similarly, if our program attempts to open an existing file

Gaddis4.book Page 1320 Monday, January 6, 2003 5:16 PM

Page 89: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Introduction to Microsoft Visual C++ .NET 1321

for reading, it will look in the project folder by default. For example, suppose our Lab5 programattempts to open a file with the following statement:

ifstream inputFile("names.txt");

Because we have not specified a path, the program will look for the file in the project folder,C:\MyProjects\Lab5.

If we want to open a file in a location other than the project folder, we must provide a path aswell as a file name. For example, the following statement opens a file named data.txt in theC:\Data folder.

ofstream outputFile("C:\\Data\\Data.txt");

Notice that we’ve used two backslashes in the path where you normally use only one. Remember,in a literal string, the compiler interprets the backslash character as the beginning of an escapesequence. In order to represent a backslash as a character in a literal string, you must use twobackslashes.

Here’s another example:

ifstream inputFile("A:\\names.txt");

This statement attempts to open the names.txt file in the root folder of drive A.

Gaddis4.book Page 1321 Monday, January 6, 2003 5:16 PM

Page 90: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1322

Appendix NStream Member Functions for Formatting

Chapter 3 introduced you to stream manipulators for formatting the appearance of data dis-played by cout. Stream manipulators aren’t the only way to format data with cout. Field width,precision, and format flags may also be modified by cout’s member functions. (For more informa-tion on member functions, see section 3.10) Here is an example of how the display field width canbe set with a member function:

cout.width(5);

All of cout’s member functions are called this way. A period separates the word cout from thename of the member function. Any arguments needed by the function are placed in parentheses.In the statement above, cout’s member function width is called to set the field width to 5 spaces.This is equivalent to inserting the setw(5) manipulator before a variable in a cout statement. Forexample, the following code displays the contents of the variable x in a field of 8 spaces.

cout.width(8);cout << x << endl;

There is also a member function named precision, which sets the precision of floating pointnumbers. The following example sets the precision to 2 decimal places:

cout.precision(2);

This setting will remain in effect until it is reset or until the end of the program. Format flags areset with the setf member function. Here is an example that sets the formatting of numbers tofixed point notation:

cout.setf(ios::fixed);

You can also send multiple flags to setf by separating them with the | symbol. Here is a state-ment that sets the flags for fixed point notation, decimal point displaying, and left-justification:

cout.setf(ios::fixed | ios::showpoint | ios::left);

Gaddis4.book Page 1322 Monday, January 6, 2003 5:16 PM

Page 91: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Stream Member Functions for Formatting 1323

Regardless of the way format flags are set, they may be turned off with the unsetf function. Itworks like setf, except the format flags you specify are disabled. The following statement turnsoff the ios::fixed and ios::left flags:

cout.unsetf(ios::fixed | ios::left);

Program N-1 demonstrates the precision and setf member functions.

Program N-1

// This program asks for sales figures for 3 days. The total// sales is calculated and displayed in a table.#include <iostream>#include <iomanip>using namespace std;

int main(){

float day1, day2, day3, total;

cout << "Enter the sales for day 1: ";cin >> day1;cout << "Enter the sales for day 2: ";cin >> day2;cout << "Enter the sales for day 3: ";cin >> day3;

total = day1 + day2 + day3;

cout.precision(2);cout.setf(ios::fixed | ios::showpoint);

cout << "\nSales Figures\n";cout << "-------------\n";cout << "Day 1: " << setw(8) << day1 << endl;cout << "Day 2: " << setw(8) << day2 << endl;cout << "Day 3: " << setw(8) << day3 << endl;cout << "Total: " << setw(8) << total << endl;

return 0;}

Program Output with Example Input Shown in BoldEnter the sales for day 1: 2642.00 [Enter]Enter the sales for day 2: 1837.20 [Enter]Enter the sales for day 3: 1963.00 [Enter]

Sales Figures-------------Day 1: 2642.00Day 2: 1837.20Day 3: 1963.00Total: 6442.20

Gaddis4.book Page 1323 Monday, January 6, 2003 5:16 PM

Page 92: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1324 Stream Member Functions for Formatting

Table N-1 summarizes the member functions we have discussed.

The cin object also supports the width member function, which establishes an input field width.This is most helpful when cin is reading a string and storing it in a character array. You may recallthat cin has no way of knowing how large an array is. If the user types more characters than thearray will hold, cin will store the string in the array anyway, overwriting whatever is in memorynext to the array. An input field width solves this problem by telling cin the number of charactersto read. Here is a statement declaring an array of 10 characters and using a cin statement to readno more characters than the array will hold:

char word[10];cin.width(10);cin >> word;

The field width specified is 10. This value will cause cin to read no more than nine characters ofinput, leaving room for the null character at the end. Program N-2 demonstrates.

Table N-1

Member Function Description

width() Sets the display field width.

precision() Sets the precision of floating point numbers.

setf() Sets the specified format flags.

unsetf() Disables, or turns off, the specified format flags.

Program N-2

// This program uses cin's width member function.#include <iostream>using namespace std;

int main(){

char word[5];cout << "Enter a word: ";cin.width(5);cin >> word;cout << "You entered " << word << endl;return 0;

}

Program Output with Example Input Shown in BoldEnter a word: Eureka [Enter]You entered Eure

Gaddis4.book Page 1324 Monday, January 6, 2003 5:16 PM

Page 93: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Stream Member Functions for Formatting 1325

In this program cin only reads 4 characters into the word array. Without the field width, cinwould have written the entire word “Eureka” into the array, overflowing it.

Using Formatting Member Functions with File StreamsThe same formatting member functions used with cout and cin may also be called from filestream objects. For example, the precision member function may be used to establish the num-ber of digits of precision for floating point numbers that are written to a file. Program N-3 dem-onstrates this.

Notice the file output is formatted just as cout would format screen output. In addition, you mayuse the width, setf, and unsetf functions with file stream objects.

Program N-3

// This program uses the precision member function of a// file stream object to format file output.#include <iostream>#include <fstream>using namespace std;

int main(){

fstream dataFile;float num = 123.456;

// Open the file.dataFile.open("numfile.txt", ios::out);

// Write a value at various digits of precisiondataFile << num << endl;dataFile.precision(5);dataFile << num << endl;dataFile.precision(4);dataFile << num << endl;dataFile.precision(3);dataFile << num << endl;

// Close the file.dataFile.close();return 0;

}

Contents of File numfile.txt123.456123.46123.5124

Gaddis4.book Page 1325 Monday, January 6, 2003 5:16 PM

Page 94: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1326

Appendix OAnswers to Checkpoints

Chapter 11.1 Because the computer can be programmed to do so many different tasks.

1.2 The Central Processing Unit (CPU), main memory, secondary storage devices, input devices, out-put devices.

1.3 Arithmetic and Logic Unit (ALU), and Control Unit

1.4 Fetch: The CPU’s control unit fetches the program’s next instruction from main memory.

Decode: The control unit decodes the instruction, which is encoded in the form of a num-ber. An electrical signal is generated.

Execute: The signal is routed to the appropriate component of the computer, which causes a device to perform an operation.

1.5 A unique number assigned to each section of memory.

1.6 Program instructions and data are stored in main memory while the program is operating. Main memory is volatile, and loses its contents when power is removed from the computer. Secondary storage holds data for long periods of time—even when there is no power to the computer.

1.7 Operating Systems and Application Software

1.8 A single tasking operating system is capable of running only one program at a time. All the com-puter’s resources are devoted to the program that is running. A multi-tasking operating system is capable of running multiple programs at once. A multi-tasking systeFm divides the allocation of the hardware resources among the running programs using a technique known as time sharing.

1.9 A single user system allows only one user to operate the computer at a time. A multi-user system allows several users to operate the computer at once.

1.10 A set of well-defined steps for performing a task or solving a problem.

1.11 To ease the task of programming. Programs may be written in a programming language, and then converted to machine language.

Gaddis4.book Page 1326 Monday, January 6, 2003 5:16 PM

Page 95: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1327

1.12 A low-level language is close to the level of the computer, and resembles the system’s numeric machine language. A high-level language is closer to the level of human readability, and resemble natural languages.

1.13 That a program may be written on one type of computer and run on another type.

1.14 The preprocessor reads the source file searching for commands that begin with the # symbol. These are commands that cause the preprocessor to modify the source file in some way. The com-piler translates each source code instruction into the appropriate machine language instruction, and creates an object file. The linker combines the object file with necessary library routines.

1.15 Source file: contains program statements written by the programmer.

Object file: machine language instructions, generated by the compiler translated from the source file.

Executable file: code ready to run on the computer. Includes the machine language from an object file, and the necessary code from library routines.

1.16 A programming environment that includes a text editor, compiler, debugger, and other utilities, integrated into one package.

1.17 A key word has a special purpose, and is defined as part of a programming language. A program-mer-defined symbol is a word or name defined by the programmer.

1.18 Operators perform operations on one or more operands. Punctuation symbols mark the begin-ning or ending of a statement, or separates items in a list.

1.19 A line is a single line as it appears in the body of a program. A statement is a complete instruction that causes the computer to perform an action.

1.20 Because their contents may be changed.

1.21 The original value is overwritten.

1.22 The variable must be defined.

1.23 Input, processing, and output.

1.24 The program’s purpose, information to be input, the processing to take place, and the desired output.

1.25 To imagine what the computer screen looks like while the program is running. This helps define input and output.

1.26 A chart that depicts each logical step of the program in a hierarchical fashion.

1.27 The programmer steps through each statement in the program from beginning to end. The con-tents of variables are recorded, and screen output is sketched.

1.28 It translates each source code statement into the appropriate machine language statement..

1.29 A logical error that occurs while the program is running.

1.30 By the compiler

1.31 To determine if a logical error is present in the program.

1.32 Procedural programs are made of procedures, or functions. Object-oriented programs are cen-tered on objects, which contain both data and the procedures that operate on the data.

Gaddis4.book Page 1327 Monday, January 6, 2003 5:16 PM

Page 96: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1328 Answers to Checkpoints

Chapter 22.1 // A crazy mixed up program

#include <iostream>using namespace std;

int main(){

cout << "In 1492 Columbus sailed the ocean blue.";return 0;

}2.2 // Today's Date: September 3, 2003

#include <iostream>using namespace std;

int main(){

cout << "Teresa Jones";return 0;

}2.3 B

2.4 A

2.5 // It's a mad, mad program#include <iostream>using namespace std;

int main(){

cout << "Success\n";cout << "Success";cout << " Success\n\n";cout << "\nSucess";return 0;

}2.6 The works of Wolfgang

include the following:The Turkish Marchand Symphony No. 40 in G minor.

2.7 // Today's Date: September 3, 2003#include <iostream>using namespace std;

int main(){

cout << "Teresa Jones\n";cout << "127 West 423rd Street\n";cout << "San Antonio, TX 78204\n";cout << "555-555-1212\n";return 0;

}

Gaddis4.book Page 1328 Monday, January 6, 2003 5:16 PM

Page 97: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1329

2.8 Variables: little and big.

Constants: 2, 2000, “The little number is ”, “The big number is”

2.9 The value is number

2.10 99bottles: Variable names cannot begin with a number.

r&d:Variable names may only use alphabetic letters, digits, or underscores

2.11 No. Variable names are case sensitive.

2.12 A) short, or unsigned short.

B) intC) They both use the same amount of memory.

2.13 They both use the same amount of memory.

2.14 67, 70, 87

2.15 ‘B’

2.16 ‘Q’ uses one byte

“Q” uses two bytes

“Sales” uses six bytes

‘\n’ uses one byte

2.17 #include <iostream>using namespace std;

int main(){

char first, middle, last;

first = 'T';middle = 'E';last = 'G';cout << first << " " << middle << " " << last << endl;return 0;

}2.18 The string constant “Z” is being stored in the character variable letter.

2.19 No

2.20 6.31E17

2.21 #include <iostream>using namespace std;

int main(){

int age;float weight;

age = 26;weight = 180;cout << "My age is " << age << endl;cout << "My weight is " << weight << endl;return 0;

}

Gaddis4.book Page 1329 Monday, January 6, 2003 5:16 PM

Page 98: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1330 Answers to Checkpoints

2.22 Invalid. The value on the left of the = operator must be an lvalue.

2.23 int x = 7, y = 16, z = 28;2.24 The variable number is assigned a value before it is defined. Correct the program by moving the

statement number = 62.7; to the point after the variable declaration. Here is the corrected pro-gram:

#include <iostream>using namespace std;

int main(){

float number;number = 62.7;cout << number << endl;return 0;

}2.25 Integer division. The value 23 will be stored in portion.

Chapter 33.1 iostream3.2 char array

3.3 char customer[53];3.4 True

3.5 B

3.6 cin >> miles >> feet >> inches;3.7 Include one or more cout statements explaining what values the user should enter.

3.8 The program will display:

Hello Jill

The program can be improved by including cout statements that instruct the user to enter only his or her first name.

3.9 #include <iostream>using namespace std;

int main(){

float pounds, kilograms;

cout << "Enter your weight in pounds: ";cin >> pounds;// The following line does the conversion.// One kilogram weighs 2.21 pounds.kilograms = pounds / 2.21;cout << "Your weight in kilograms is ";cout << kilograms << endl;return 0;

}

Gaddis4.book Page 1330 Monday, January 6, 2003 5:16 PM

Page 99: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1331

3.10 Value21 231 524 269 030

3.11 y = 6 * x;a = 2 * b + 4 * c;y = x * x; or y = pow(x, 2);g = (x + 2) / (z * z); or g = (x + 2) / pow(z, 2);y = (x * x) / (z * z); or y = pow(x, 2) / pow (z, 2);

3.12 If the user enters… The program displays…

2 65 274.3 20.496 38

3.13 #include <iostream>#include <cmath>using namespace std;

int main(){

double volume, radius, height;

cout << "This program will tell you the volume of\n";cout << "a cylinder-shaped fuel tank.\n";cout << "How tall is the tank? ";cin >> height;cout << "What is the radius of the tank? ";cin >> radius;volume = 3.14159 * pow(radius, 2.0) * height;cout << "The volume of the tank is " << volume << endl;return 0;

}3.14 A) 2

B) 17.0C) 2.0D) 2.4E) 2.4F) 2.4G) 4H) 27I) 30J) 27.0

Gaddis4.book Page 1331 Monday, January 6, 2003 5:16 PM

Page 100: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1332 Answers to Checkpoints

3.15 #include <iostream>using namespace std;

int main(){

char letter;

cout << "Enter a character: ":cin >> letter;cout << "The ASCII code for " << letter;cout << " is " << static_cast<int>(letter) << endl;return 0;

}3.16 9

9.59

3.17 const float e = 2.71828;const float yearSecs = 5.26e5;const float gf = 32.2;const float gm = 9.8;const int metersPerMile = 1609;

3.18 #define E 2.71828#define YEARSECS 5.26e5#define GF 32.2#define GM 9.8#define METERSPERMILE 1609

3.19 This program calculates the number of candy pieces sold.How many jars of candy have you sold? 6 [Enter]The number of pieces sold: 11160Candy pieces you get for commission: 2232

3.20 #include <iostream>using namespace std;

int main(){

const float conversion = 1.467;float milesPerHour, feetPerSecond;

cout << "This program converts miles-per-hour to\n";cout << "feet-per-second.\n";cout << "Enter a speed in MPH: ";cin >> milesPerHour;feetPerSecond = MilesPerhour * conversion;cout << "That is " << feetPerSecond

<< " feet-per-second.\n";return 0;

}

Gaddis4.book Page 1332 Monday, January 6, 2003 5:16 PM

Page 101: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1333

3.21 total = subtotal = tax = shipping = 0;3.22 A) x += 6;

B) amount -= 4;C) y *= 4;D) total /= 27;E) x %= 7;F) x += (y * 5);G) total -= (discount * 4);H) increase *= (salesRep * 5);I) profit /= (shares – 1000);

3.23 3111

3.24 A) cout << setw(9) << fixed << setprecision(2) << 34.789;B) cout << setw(5) << fixed << setprecision(3) << 7.0;C) cout << fixed << 5.789e12;D) cout << left << setw(7) << 67;

3.25 #include <iostream>#include <iomanip>

int main(){

char person[15] = "Wolfgang Smith";

cout << right;cout << setw(20);cout << person << endl;cout << left;cout << person << endl;return 0;

}3.26 #include <iostream>

#include <iomanip>using namespace std;

int main(){

const float pi = 3.14159;float degrees, radians;

cout << "Enter an angle in degrees and I will convert it\n";cout << "to radians for you: ";cin >> degrees;radians = degrees * pi / 180;cout << degrees << " degrees is equal to ";cout << setw(5) << left << fixed << showpoint << setprecision(4) << radians << " radians.\n";return 0;

}

Gaddis4.book Page 1333 Monday, January 6, 2003 5:16 PM

Page 102: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1334 Answers to Checkpoints

3.27 cos: Returns the cosine of the argument.

exp: Returns the exponential function of the argument.

fmod: Returns the remainder of the first argument divided by the second argument.

log: Returns the natural logarithm of the argument.

log10: Returns the base-10 logarithm of the argument.

pow: Returns the value of the first argument raised to the power of the second argument.

sin: Returns the sine of the argument.

sqrt: Returns the square root of the argument.

tan: Returns the tangent of the argument.

3.28 x = sin(angle1) + cos(angle2);3.29 y = pow(x, 0.2); // 0.2 is equal to 1/53.30 y = 1 / sin(a);

Chapter 44.1 T, T, F, T, T, F, T

4.2 A) Incorrect

B) Incorrect

C) Correct

4.3 A) yes

B) no

C) no

4.4 0010

4.5 True

4.6 False

4.7 A) The if statement is terminated with a semicolon.

B) The = operator is used instead of the == operator.

C) Only the first statement after the if statement is conditionally executed. The first three statements after the if statement should be enclosed in a set of braces. Line 6 should read balance = balance + balance * interestRate;

4.8 if (y == 20) x = 0;

4.9 if (hours > 40) payRate *= 1.5;

4.10 if (sales >= 10000.00) commission = .20;

4.11 if (max) fees = 50;

Gaddis4.book Page 1334 Monday, January 6, 2003 5:16 PM

Page 103: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1335

4.12 false

4.13 if (y == 100) x = 1;else x = 0;

4.14 if (sales >= 50000.00) commission = 0.20;else commisson = 0.10;

4.15 #include <iostream>using namespace std;

int main(){

float taxRate, saleAmount;char residence;

cout << "Enter the amount of the sale: ";cin >> saleAmount;cout << "Enter I for in-state residence or O for out-of-\n";cout "state: ";cin.get(residence);if (residence == 'O')

taxRate = 0;else

taxRate = 0.05;saleAmount += saleAmount * taxRate;cout << "The total is " << saleAmount;return 0;

}

4.16 // This program uses an if/else if statement to assign a// letter grade (A, B, C, D, or F) to a numeric test score.#include <iostream>using namespace std;

int main(){

int testScore;char grade;

cout << "Enter your numeric test score and I will\n";cout << "tell you the letter grade you earned: ";cin >> testScore;if (testScore < 0)

cout << testScore << " is an invalid score.\n”;else if (testScore < 60)

cout << "Your grade is F.\n";

Gaddis4.book Page 1335 Monday, January 6, 2003 5:16 PM

Page 104: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1336 Answers to Checkpoints

else if (testScore < 70)cout << "Your grade is D.\n";

else if (testScore < 80)cout << "Your grade is C.\n";

else if (testScore < 90)cout << "Your grade is B.\n";

else if (testScore <= 100)cout << "Your grade is A.\n";

elsecout << testScore << " is an invalid score.\n";

return 0;}

4.17 11

4.18 If the customer purchases this many coupons arethis many books... given.-----------------------------------------------------

1 12 13 24 25 310 3

4.19 if (amount1 > 10)if (amount2 < 100)

if (amount1 > amount2)cout << amount1;

elsecout << amount2;

4.20 You cannot handle the conditions employed == 'y' and recentGrad = 'y' separately. They are treated as a single condition when linked with the && operator.

4.21

Logical Expression Result (true or false)

true && false falsetrue && true truefalse && true falsefalse && false falsetrue || false truetrue || true truefalse || true truefalse || false false

!true false!false true

Gaddis4.book Page 1336 Monday, January 6, 2003 5:16 PM

Page 105: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1337

4.22 T, F, T, T, T

4.23 if (speed >= 0 && speed <= 200)cout << "The number is valid.";

4.24 if (speed < 0 || speed > 200)cout << "The number is not valid.";

4.25 #include <iostream>using namespace std;

int main(){

int first, second, result;

cout << "Enter a negative integer: ";cin >> first;cout << "Now enter a positive integer: ";cin >> second;if (first >= 0 || second < 0){

cout << "The first number should be negative\n";cout << "and the second number should be\n";cout << "positive. Run the program again and\n";cout << "enter the correct values.\n";

}else{

result = first * second;cout << first << " times " << second << " is " << result << endl;

}return 0;

}4.26 The variables length, width, and area should be defined before they are used.

4.27 Enter your first test score: 40Enter your second test score: 30test 1: 50test 2: 40sum : 70

4.28 A) negativeB) negativeC) negativeD) positive

4.29 if (strcmp(iceCream, "Chocolate") == 0)cout << "Chocolate: 9 fat grams.\n";

else if (strcmp(iceCream, "Vanilla") == 0)cout << "Vanilla: 10 fat grams.\n";

else if (strcmp(iceCream, "Pralines & Pecan") == 0)cout << "Pralines & Pecan: 14 fat grams.\n";

elsecout << "That's not one of our flavors!\n";

Gaddis4.book Page 1337 Monday, January 6, 2003 5:16 PM

Page 106: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1338 Answers to Checkpoints

4.30 A) z = x > y ? 1 : 20;B) population = temp > 45 ? base * 10 : base * 2;C) wages *= hours > 40 ? 1.5 : 1;D) cout << (result >= 0 ? "The result is positive\n" :

"The result is negative.\n");4.31 A) if (k > 90)

j = 57;else

j = 12;B) if (x >= 10)

factor = y * 22;else

factor = y * 35;C) if (count == 1)

total += sales;else

total += count * sales;D) if (num % 2)

cout << "Odd\n";else

cout << "Even\n";4.32 2 2

4.33 Because the if /else if statement tests several different conditions, consisting of different variables.

4.34 The case statements must be followed by an integer constant, not a relational expression.

4.35 That is serious.

4.36 switch (userNum){

case 1 : cout << "One"; break;case 2 : cout << "Two"; break;case 3 : cout << "Three"; break;default: cout << "Enter 1, 2, or 3 please.\n";

}4.37 switch (selection)

{case 1 : cout << "Pi times radius squared\n"; break;case 2 : cout << "Length times width\n"; break;

Gaddis4.book Page 1338 Monday, January 6, 2003 5:16 PM

Page 107: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1339

case 3 : cout << "Pi times radius squared times height\n"; break;case 4 : cout << "Well okay then, good bye!\n"; break;default : cout << "Not good with numbers, eh?\n";

}

Chapter 55.1 A) 32

B) 33C) 23D) 34E) It is true!F) It is true!

5.2 None

5.3 Once

5.4 x is the counter, y is the accumulator

5.5 #include <iostream>using namespace std;

int main(){

int num = 10;

cout << "number number Squared\n";cout << "--------------------------------------\n";while (num > 0){

cout << num << "\t\t" << (num * num) << endl;num--;

}return 0;

}5.6 // This program calculates the total number of points a

// soccer team has earned over a series of games. The user// enters a series of point values, then -1 when finished.#include <iostream>using namespace std;

int main(){

int game = 1, points, total = 0;

cout << "Enter the number of points your team has earned\n";cout << "so far in the season, then enter -1 when finished.\n\n";cout << "Enter the points for game " << game << ": ";cin >> points;

Gaddis4.book Page 1339 Monday, January 6, 2003 5:16 PM

Page 108: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1340 Answers to Checkpoints

while (points > 0){

total += points;cout << "Enter the points for game " << ++game << ": ";cin >> points;

}cout << "\nThe total points are " << total << endl;return 0;

}5.7 A) Hello World

B) 01234C) 6 10 5

5.8 int number, total = 0;do{

cout << "Enter a number: ";cin >> number;total += number;

} while (total <= 300);5.9 The initialization, the test, and the update.

5.10 A) 0246810B) -5-4-3-2-1C) 5 8 11 14 17

5.11 for (count = 0; count <= 100; count += 5)cout << count << endl;

5.12 int count, number, total = 0;for (count = 0; count < 7; count++){

cout << "Enter a number: ";cin >> number;total += number;

}cout << "The total is " << total << endl;

5.13 float x, y, quotient, total = 0;for (x = 1, y = 30; x <= 30; x++, y--){

quotient = x / y;total += quotient;

}cout << "The total is " << total << endl;

Gaddis4.book Page 1340 Monday, January 6, 2003 5:16 PM

Page 109: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1341

5.14 A) forB) do-whileC) whileD) whileE) for

5.15 600 times (20 times 30)

5.16 220 times (20 times 11)

5.17 13712

5.18 int number;cout << "Enter a number in the range 10 - 25: ";cin >> number;while (number < 10 || number > 25){

cout << "That value is out of range. Try again: ";cin >> number;

}5.19 char letter;

cout << "Enter Y, y, N, or n: ";cin >> letter;while (letter != 'Y' && letter != 'y' && letter != 'N' && letter != 'n'){

cout << "That is not a valid choice. Try again: ";cin >> letter;

}5.20 char response[10];

cout << "Enter Yes or No: ";cin >> response;while (strcmp("Yes", response) != 0 && strcmp("No", response) != 0){

cout << "That is not a valid choice. Try again: ";cin >> response;

}

Chapter 66.1 Function call

6.2 Function header

6.3 I saw ElbaAble was I

Gaddis4.book Page 1341 Monday, January 6, 2003 5:16 PM

Page 110: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1342 Answers to Checkpoints

6.4 void qualify(){

cout << "Congratulations, you qualify for\n";cout << "the loan. The annual interest rate\n";cout << "is 12%\n";

}

void noQualify(){

cout << "You do not qualify. In order to\n";cout << "qualify you must have worked on\n";cout << "your current job for at least two\n";cout << "years and you must earn at least\n";cout << "$17,000 per year.\n";

}6.5 Header

PrototypeFunction call

6.6 void timesTen(int number){

cout << (number * 10);}

6.7 void timesTen(int);

6.8 0 01 22 43 64 85 106 127 148 169 18

6.9 0 1.51.5 00 100 1.5

6.10 void showDollars(float amount){

cout << "Your wages are $";cout << setprecision(2);cout << setiosflags(ios::fixed | ios::showpoint);cout << amount << endl;

}6.11 One

6.12 float distance(float rate, float time)6.13 int days(int years, int weeks, int months = 12)

Gaddis4.book Page 1342 Monday, January 6, 2003 5:16 PM

Page 111: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1343

6.14 char getKey()6.15 long lightYears(long miles)6.16 A static local variable’s scope is limited to the function in which it is declared. A global variable’s

scope is the portion of the program beginning at its declaration to the end.

6.17 10050100

6.18 10111213141516171819

6.19 Literals

6.20 Prototype:void compute(float, int = 5, long = 65536);

Header:void compute(float x, int y, long z)

6.21 Prototype:void calculate(long, &float, int = 47);

Header:void calculate(long x, float &y, int z)

6.22 5 10 159 10 156 15 154 11 16

6.23 0 00Enter two numbers: 12 1412 14014 15-114 15-1

6.24 1.26.25 226.26 306.27 Function Prototype:

float calcArea(float, float);

Definition of the function:float calcArea(float len, float wide){

return len * wide;}

Gaddis4.book Page 1343 Monday, January 6, 2003 5:16 PM

Page 112: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1344 Answers to Checkpoints

Chapter 77.1 A) int empNums[100];

B) float payRates[25];C) long miles[14];D) char cityName[26];E) double lightYears[1000];

7.2 int readings[-1]; // Size declarator cannot be negative

float measurements[4.5]; // Size declarator must be an integer

int size;char name[size]; // Size declarator must be a constant

7.3 0 through 3

7.4 The size declarator is used in the array declaration statement. It specifies the number of elements in the array. A subscript is used to access an individual element in an array.

7.5 Array bounds checking is a safeguard provided by some languages. It prevents a program from using a subscript that is beyond the boundaries of an array. C++ does not perform array bounds checking.

7.6 12345

7.7 #include <iostream>using namespace std;

int main(){

int fish[20], count;

cout << "Enter the number of fish caught\n"; cout << "by each fisherman.\n";

for (count = 0; count < 20; count++){

cout << "fisherman " << (count+1) << ": "; cin >> fish[count]; }

return 0;}

7.8 A) int ages[10] = {5, 7, 9, 14, 15, 17, 18, 19, 21, 23};B) float temps[7] = {14.7, 16.3, 18.43, 21.09, 17.9, 18.76, 26.7};C) char alpha[8] = {'J', 'B', 'L', 'A', '*', '$', 'H', 'M'};

7.9 The definition of numbers is valid.

The declaration of matrix is invalid because there are too many values in the initialization list.

The definition of radii is valid.

Gaddis4.book Page 1344 Monday, January 6, 2003 5:16 PM

Page 113: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1345

The definition of table is invalid. Values cannot be skipped in the initialization list.

The definition of codes is valid.

The definition of blanks is invalid. An initialization list must be provided when an array is implicitly sized.

The definition of name is invalid. The string “Joanne” with its null-terminator will use seven array elements, not six.

7.10 A) 10B) 3C) 6D) 14

7.11 0

7.12 10.0025.0032.5050.00110.00

7.13 1 18 182 4 83 27 814 52 2085 100 500

7.14 No. An entire array cannot be copied in a single statement with the = operator. The array must be copied element-by-element.

7.15 The address of the array.

7.16 No.

7.17 ABCDEFGH7.18 (The entire program is shown here.)

#include <iostream>using namespace std;

// Function prototype herefloat avgArray(int []);

int main(){

int userNums[10];

cout << "Enter 10 numbers: ";for (int count = 0; count < 10; count++){

cout << "#" << (count + 1) << " ";cin >> userNums[count];

}

Gaddis4.book Page 1345 Monday, January 6, 2003 5:16 PM

Page 114: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1346 Answers to Checkpoints

cout << "The average of those numbers is ";cout << avgArray(userNums) << endl;return 0;

}

// Function avgArrayfloat avgArray(int array[]){float total = 0.0, average;

for (int count = 0; count < 10; count++)total += array[count];

average = total / 10;return average;

}7.19 int grades[30][10];7.20 24

7.21 sales[0][0] = 56893.12;7.22 cout << sales[5][3];

7.23 int settings[3][5] = {{12, 24, 32, 21, 42}, {14, 67, 87, 65, 90}, {19, 1, 24, 12, 8}};

7.24

7.25 void displayArray7(int array[][7], int rows){

for (int x = 0; x < rows; x++){

for (int y = 0; y < 7; y++){

cout << array[x][y] << " ";}cout << endl;

}}

7.26 int vidNum[50][10][25];7.27 vector7.28 vector <int> frogs;7.29 vector <float> lizards(20);7.30 vector <char> toads(100, 'Z');7.31 vector <int> gators;

gators.push_back(27);7.32 snakes[4] = 12.897;

2 3 0 0

7 9 2 0

1 0 0 0

Gaddis4.book Page 1346 Monday, January 6, 2003 5:16 PM

Page 115: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1347

Chapter 88.1 The linear search algorithm simply uses a loop to step through each element of an array, compar-

ing each element’s value with the value being searched for. The binary search algorithm, which requires the values in the array to be sorted in order, starts searching at the element in the middle of the array. If the middle element’s value is greater than the value being searched for, the algo-rithm next tests the element in the middle of the first half of the array. If the middle element’s value is less than the value being searched for, the algorithm next tests the element in the middle of the last half of the array. Each time the array tests an array element and does not find the value being searched for, it eliminates half of the remaining portion of the array. This method continues until the value is found, or there are no more elements to test. The binary search is more efficient than the linear search.

8.2 10,000

8.3 15

8.4 The items frequently searched for can be stored near the beginning of the array.

Chapter 99.1 cout << &count;9.2 float *fltPtr;9.3 Multiplication operator, pointer definition, indirection operator.

9.4 50 60 70500 300 140

9.5 for (int x = 0; x < 100; x++) cout << *(array + x) << endl;

9.6 12040

9.7 A) ValidB) ValidC) Invalid. Only addition and subtraction are valid arithmetic operations with pointers.D) Invalid. Only addition and subtraction are valid arithmetic operations with pointers.E) Valid

9.8 A) ValidB) ValidC) Invalid. fvar is a float and iptr is a pointer to an int.D) ValidE) Invalid. ivar must be declared before iptr.

9.9 A) TrueB) FalseC) TrueD) False

9.10 makeNegative (&num);

9.11 void convert(float *val){

*val *= 2.54;}

Gaddis4.book Page 1347 Monday, January 6, 2003 5:16 PM

Page 116: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1348 Answers to Checkpoints

9.12 ip = new int;delete ip;

9.13 ip = new int[500];delete [] ip;

9.14 A pointer that contains the address 0.

9.15 char *getname(char *name){

cout >> "Enter your name: ";cin.getline(name, 81);return name;

}9.16 char *getname()

{char name[81];cout >> "Enter your name: ";cin.getline(name, 81);return name;

}

Chapter 1010.1

isalpha Returns true (a nonzero number) if the argument is a letter of the alphabet. Returns 0 if the argument is not a letter.

isalnum Returns true (a nonzero number) if the argument is a letter of the alphabet or a digit. Otherwise it returns 0.

isdigit Returns true (a nonzero number) if the argument is a digit 0–9. Otherwise it returns 0.

islower Returns true (a nonzero number) if the argument is a lowercase letter. Otherwise, it returns 0.

isprint Returns true (a nonzero number) if the argument is a printable character (including a space). Returns 0 otherwise.

ispunct Returns true (a nonzero number) if the argument is a printable character other than a digit, letter, or space. Returns 0 otherwise.

isupper Returns true (a nonzero number) if the argument is an uppercase letter. Otherwise, it returns 0.

isspace Returns true (a nonzero number) if the argument is a whitespace character. Whitespace characters are any of the following:

space................ ‘ ’newline.............. ‘\n’tab.................. ‘\t’vertical tab......... ‘\v’

Otherwise, it returns 0.

Gaddis4.book Page 1348 Monday, January 6, 2003 5:16 PM

Page 117: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1349

10.2 little = tolower(big);

10.3 if (isdigit(ch))cout << "digit";

elsecout << "Not a digit.";

10.4 A10.5 char choice;

do{ cout << "Do you want to repeat the program or quit? (R/Q) "; cin >> choice;} while (toupper(choice) != 'R' && toupper(choice) != 'Q');

10.6

10.7 4

10.8 Have a nice daynice day

10.9 strcpy(composer, "Beethoven");

toupper Returns the uppercase equivalent of its argument.

tolower Returns the lowercase equivalent of its argument.

strlen Accepts a pointer to a string as an argument. Returns the length of the string (not including the null terminator.)

strcat Accepts pointers to two strings as arguments. The function appends the contents of the second string to the first string. (The first string is altered, the second string is left unchanged.)

strcpy Accepts pointers to two strings as arguments. The function copies the second string to the first string. The second string is left unchanged.

strncpy

Accepts pointers to two strings and an integer argument. The third argument, an integer, indicates how many characters to copy from the second string to the first string. If the String2 has fewer than n characters, String1 is padded with ‘\0’ characters.

strcmp Accepts pointers to two string arguments. If String1 and String2 are the same, this function returns 0. If String2 is alphabetically greater than String1, it returns a positive number. If String2 is alphabetically less than String1, it returns a negative number.

strstr Searches for the first occurrence of String2 in String1. If an occurrence of String2 is found, the function returns a pointer to it. Otherwise, it returns a NULL pointer (address 0).

Gaddis4.book Page 1349 Monday, January 6, 2003 5:16 PM

Page 118: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1350 Answers to Checkpoints

10.10 #include <iostream>#include <cstring>using namespace std;

int main(){

char place[] = "The Windy City";if (strstr(place, "Windy"))

cout << "Windy found.\n";else

cout << "Windy not found.\n";return 0;

}10.11

10.12 num = atoi("10");10.13 num = atol("10000");10.14 num = atof("7.2389");10.15 itoa(127, Value, 10);

10.16 Tom Talbert Tried TrainsDom Dalbert Dried Drains

Chapter 1111.1 struct Account

{char acctNum[15];float acctBal;float intRate;float avgBal;

};11.2 Account Savings = {"ACZ42137-B12-7",

4512.59, 0.04, 4217.07 };

atoi Accepts a string as an argument. The function converts the string to an integer and returns that value.

atol Accepts a string as an argument. The function converts the string to a long integer and returns that value.

atof Accepts a string as an argument. The function converts the string to a float and returns that value.

itoa Converts an integer to a string. The first argument is the integer. The result will be stored at the location pointed to by the second argument, String. The third argument is an integer. It specifies the numbering system that the converted integer should be expressed in. (8 = octal, 10 = decimal, 16 = hexadecimal, etc.)

Gaddis4.book Page 1350 Monday, January 6, 2003 5:16 PM

Page 119: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1351

11.3 #include <iostream>using namespace std;

struct Movie{

char name[51];char director[51];char producer[51];char year[5];

};

int main(){

Movie favorite;

cout << "Enter the following information about your\n";cout << "favorite movie.\n";cout << "Name: ";cin.getline(favorite.name, 51);cout << "Director: ";cin.getline(favorite.director, 51);cout << "Producer: ";cin.getline(favorite.producer, 51);cout << "Year of release: ";cin.getline(favorite.year, 51);cout << "Here is information on your favorite movie:\n";cout << "Name: " << favorite.name << endl;cout << "Director: " << favorite.director << endl;cout << "Producer: " << favorite.producer << endl;cout << "Year of release: " << favorite.year << endl;return 0;

}11.4 Product items[100];

11.5 for (int x = 0; x < 100; x++){

items[x].description[0] = '\0';items[x].partNum = 0;items[x].cost = 0;

}11.6 strcpy(items[0].description, "Claw Hammer");

items[0].partNum = 547;items[0].cost = 8.29;

11.7 for (int x = 0; x < 100; x++){

cout << items[x].description << endl;cout << items[x].partNum << endl;cout << items[x].cost << endl << endl;

}

Gaddis4.book Page 1351 Monday, January 6, 2003 5:16 PM

Page 120: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1352 Answers to Checkpoints

11.8 Product items[5] = { {"Screwdriver", 621, 1.72 }, { "Socket set", 892, 18.97 }, { "Claw hammer", 547, 8.29 }, { "Adjustable wrench", 229, 12.15 }, { "Pliers", 114, 3.17 }};

11.9 struct Measurement{

int miles;long meters;

};11.10 struct Destination

{char city[35];Measurement distance;

};Destination place;

11.11 strcpy(place.city, "Tupelo");place.distance.miles = 375;place.distance.meters = 603375;

11.12 void showRect(Rectangle r){

cout << r.length << endl;cout << r.width << endl;

}11.13 void getRect(Rectangle &r)

{cout << "Width: ";cin >> r.width;cout << "length: ";cin >> r.length;

}11.14 Rectangle getRect()

{Rectangle r;cout << "Width: ";cin >> r.width;cout << "length: ";cin >> r.length;return r;

}11.15 Rectangle *rptr;

11.16 cout << r->length << endl << r->width << endl;

11.17 B

Gaddis4.book Page 1352 Monday, January 6, 2003 5:16 PM

Page 121: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1353

11.18 union ThreeTypes{

char letter;int whole;float real

};11.19 ThreeTypes Items[50];

11.20 for (int x = 0; x < 50; x++)items[x].real = 2.37;

11.21 for (int x = 0; x < 50; x++)items[x].letter = 'A';

11.22 for (int x = 0; x < 50; x++)items[x].whole = 10;

Chapter 1212.1 ios::app12.2 Place the | operator between them.

12.3 diskInfo.open("names.dat", ios::out);12.4 diskInfo.open("customers.dat", is::app);12.5 diskInfo.open("payable.dat", ios::in | ios::out);12.6 fstream dataFile("salesfigures.txt", ios::in);

12.7 RunSpotrunSeespotrun

12.8 The >> operator considers whitespace characters as delimiters, and does not tread them. The getline() member function does read whitespace characters.

12.9 The getline function reads a line of text, the get function reads a single character.

12.10 Writes a single character to a file.

12.11 100.28 1.72 8.60 7.78 5.1012.12 You define multiple file stream objects, one for each file you wish to work with.

12.13 Character representation: “479”

ASCII Codes: 52 55 57

12.14 The << operator writes text to a file. The write member function writes binary data to a file.

12.15 The first argument is the starting address of the section of memory, which is to be written to the file. The second argument is the size, in bytes, of the item being written.

12.16 The first argument is the starting address of the section of memory where information read from the file is to be stored. The second argument is the size, in bytes, of the item being read.

Gaddis4.book Page 1353 Monday, January 6, 2003 5:16 PM

Page 122: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1354 Answers to Checkpoints

12.17 A field is an individual piece of data pertaining to a single item. A record is made up of fields, and is a complete set of data about a single item.

12.18 file.write(reinterpret_cast<char *>(&cust), sizeof(cust));12.19 seekg moves the file’s read position (for input) and seekp moves the file’s write position (for

output).

12.20 tellg reports the file’s read position and tellp reports the files write position.

12.21 ios::beg The offset is calculated from the beginning of the file

ios::end The offset is calculated from the end of the file

ios::curr The offset is calculated from the current position

12.22 0

12.23 file.seekp(100L, ios::beg);Moves the write position to the 101st byte (byte 100) from the beginning of the file.

file.seekp(-10L, ios::end);Moves the write position to the 11th byte (byte 10) from the end of the file.

file.seekp(-25L, ios::cur);Moves the write position backward to the 26th byte from the current position.

file.seekp(30L, ios::cur);Moves the write position to the 30th byte (byte 31) from the current position.

12.24 file.open("info.dat", ios::in | ios::out);Input and output.

file.open("info.dat", ios::in | ios::app);Input and output. Output will be appended to the end of the file.

file.open("info.dat", ios::in | ios::out | ios::ate);Input and output. If the file already exists, the program goes immediately to the end of the file.

file.open("info.dat", ios::in | ios::out);Input and output, binary mode.

Chapter 1313.1 False

13.2 B

13.3 A

13.4 C

13.5 class Date{private:

int month;int day;int year;

Gaddis4.book Page 1354 Monday, January 6, 2003 5:16 PM

Page 123: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1355

public:void setDate(int m, int d, int y)

{ month = m; day = d; year = y; }int getMonth()

{ return month; }int getDay()

{ return day; }int getYear()

{ return year; }}

13.6 The BasePay class declaration would reside in basepay.h

The BasePay member function definitions would reside in basepay.cpp

The Overtime class declaration would reside in overtime.h

The Overtime member function declarations would reside in overtime.cpp

13.7 Some functions may have adverse effects if they are called at the wrong time. For example, a function might initialize member variables, or destroy a member variable’s contents. To pre-vent a member function from being called at the wrong time, it can be made private. Then, it can only be called from another member function, which can determine if it appropriate to call the private function.

13.8 It adds the additional overhead of coding a public member function to act as an interface to the private member function.

13.9 A member function whose body is coded in the class declaration.

13.10 A constructor is automatically called when the class object is created. It is useful for initializ-ing member variables, or performing set-up operations.

13.11 A destructor is automatically called before a class object is destroyed. It is useful for perform-ing housekeeping operations, such as freeing memory that was allocated by the class object’s member functions.

13.12 A

13.13 B

13.14 A

13.15 B

13.16 A

13.17 True

13.18 True

13.19 False

13.20 ClassAct sally(25);

13.21 False

13.22 102050

Gaddis4.book Page 1355 Monday, January 6, 2003 5:16 PM

Page 124: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1356 Answers to Checkpoints

13.23 472274

13.24 #include <iostream>using namespace std;

class Yard{private:

int length, width;public:

Yard(){ length = 0; width = 0; }

setLength(int len){ length = len; }

setWidth(int w){ width = w; }

};

int main(){

Yard lawns[10];cout << "Enter the length and width of "

<< "each yard.\n";for (int count = 0; count < 10; count++){

int input;cout << "Yard " << (count + 1) << ":\n";cout << "Length: ";cin >> Input;lawns[count].setLength(input);cout << "width: ";cin >> input;lawns[count].setWidth(input);

}return 0;

}

Chapter 1414.1 Each class object (an instance of a class) has its own copy of the class’s regular member variables. If

a class’s member variable is static, however, only one instance of the variable exists in memory. All objects of that class have access to that one variable.

Gaddis4.book Page 1356 Monday, January 6, 2003 5:16 PM

Page 125: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1357

14.2 Outside the class declaration.

14.3 Before.

14.4 Static member functions can only access member variables that are also static.

14.5 You can call a static member function before any instances of the class have been created.

14.6 No, but it has access to class X’s private members, just as if it were a member.

14.7 Class X.

14.8 Each member of one object is copied to its counterpart in another object of the same class.

14.9 When one object is copied to another with the = operator, and when one object is initialized with another object’s data.

14.10 When an object contains a pointer to dynamically allocated memory.

14.11 When an object is initialized with another object’s data, and when an object is passed by value as the argument to a function.

14.12 It has a reference parameter object of the same class type as the constructor’s class.

14.13 It performs memberwise assignment.

14.14 void operator=(const Pet &);14.15 dog.operator=(cat);14.16 It cannot be used in multiple assignment statements or other expressions.

14.17 It is a built-in pointer, available to a class’s member functions, that always points to the instance of the class making the function call.

14.18 Non-static member functions

14.19 cat is calling the operator+ function. tiger is passed as an argument.

14.20 The operator is used in postfix mode.

14.21 They should always return true or false values.

14.22 The object may be directly used with cout and cin.

14.23 An ostream object.

14.24 An istream object.

14.25 The operator function must be declared as a friend.

14.26 list1.operator[](25); 14.27 The object whose name appears on the right of the operator in the expression.

14.28 So statements using the overloaded operators may be used in other expressions.

14.29 The postfix version has a dummy parameter.

14.30 (Overloaded operator functions)

// Overloaded prefix -- operatorFeetInches FeetInches::operator—-(){

--inches;simplify();return *this;

}

Gaddis4.book Page 1357 Monday, January 6, 2003 5:16 PM

Page 126: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1358 Answers to Checkpoints

// Overloaded postfix -- operatorFeetInches FeetInches::operator—-(int){

FeetInches temp(feet, inches);inches--;simplify();return temp;

}

(Demonstration program)

// This program demonstrates the prefix and postfix –// operators, overloaded to work with the FeetInches class.

#include <iostream>#include "FeetInches6.h"using namespace std;

int main(){

FeetInches distance;

cout << "Enter a distance in feet and inches: ";cin >> distance;cout << "Demonstrating the prefix – operator: \n";cout << "Here is the value: " << --distance << endl;cout << "Demonstrating the postfix – operator: \n";cout << "Here is the value: " << distance-- << endl;cout << "Here is the final value: " << distance << endl;return 0;

}14.31 Objects are automatically converted to other types. This ensures that an object’s data is properly

converted.

14.32 They always return a value of the data type they are converting to.

14.33 BlackBox::operator int()14.34 The Big class “has a” Small class as its member.

Chapter 1515.1 The base class is Vehicle.

15.2 The derived class is Truck.

15.3 A) The radius variable. (The area variable is inherited, but inaccessible.)

B) The setArea function (inherited)

The getArea function (inherited)

The setRadius function

The getRadius function

C) The area variable

Gaddis4.book Page 1358 Monday, January 6, 2003 5:16 PM

Page 127: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1359

15.4 Protected members may be accessed by derived classes. Private members are inaccessible to derived classes.

15.5 Member access specification determines if a class member is accessible to statements outside the class. Class access specification determines if functions in a derived class may access members of the base class.

15.6 A) a is inaccessible, the rest are private.

B) a is inaccessible, the rest are protected.C) a is inaccessible, b, c, and setA are protected, setB and setC are public.D) private

15.7 Entering the SkyEntering the GroundLeaving the GroundLeaving the Sky

15.8 Entering the SkyEntering the GroundLeaving the GroundLeaving the Sky

15.9 An overloaded function is one with the same name as one or more other functions, but with a dif-ferent parameter list. The compiler determines which function to call based on the arguments used. Redefining occurs when a derived class has a function with the same name as a base class function. The two functions can have the same parameter list. Objects that are of the derived class always call the derived class’s version of the function, while objects that are of the base class always call the base class’s version.

15.10 Static binding means the compiler binds member function at compile time calls with the version of the function that resides in the same class as the call itself. Dynamic binding means that func-tion calls are bound at runtime with member functions that reside in the class responsible for the call.

15.11 Dynamically

15.12 15

15.13 22

15.14 21

15.15 2

15.16 Chain of inheritance

15.17 Multiple inheritance

15.18 a) inaccessibleb) protectedc) protectedd) inaccessiblee) protectedf) public

Gaddis4.book Page 1359 Monday, January 6, 2003 5:16 PM

Page 128: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1360 Answers to Checkpoints

g) privateh) protectedi) public

15.19 class SportUtility : public van, public FourByFour{};

Chapter 1616.1 The try block contains one or more statements that may directly or indirectly throw an exception.

The catch block contains code that handles, or responds to an exception.

16.2 The entire program will abort execution.

16.3 Each exception must be of a different type. The catch block whose parameter matches the data type of the exception handles the exception.

16.4 With the first statement after the try/catch construct.

16.5 By giving the exception class a member variable, and storing the desired information in the vari-able. The throw statement creates an instance of the exception class, which must be caught by a catch statement. The catch block can then examine the contents of the member variable.

16.6 When it encounters a call to the function.

16.7 template <class T>float half(T number){

return number / 2.0;}

16.8 That the operator has been overloaded by the class object.

16.9 First write a regular, non-template version of the function. Then, after testing the function, con-vert it to a template.

16.10 List<int> myList;16.11 template <class T>

class Rectangle{

private:T width;T length;T area;

public:void setData(T w, T l)

{ width = w; length = l;}void calcArea()

{ area = width * length; }T getWidth()

{ return width; }T getLength()

{ return length; }T getArea()

{ return area; }};

Gaddis4.book Page 1360 Monday, January 6, 2003 5:16 PM

Page 129: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Answers to Checkpoints 1361

Chapter 1717.1 A data member contains the data stored in the node. A pointer points to another node in the list.

17.2 A pointer to the first node in the list.

17.3 The last node in the list will point to the NULL address.

17.4 A data structure that contains a pointer to an object of the same data structure type.

17.5 Appending a node is adding a new node to the end of the list. Inserting a node is adding a new node in a position between two other nodes.

17.6 Appending

17.7 Because the new node is being inserted between two other nodes, previousNode points to the node that will appear before the new node.

17.8 A) Remove the node from the list without breaking the links created by the next pointersB) Delete the node from memory

17.9 Because there is probably a node pointing to the node being deleted. Additionally, the node being deleted probably points to another node. These links in the list must be preserved.

17.10 The unused memory is never freed, so it could eventually be used up.

Chapter 1818.1 Last-in-first-out. The last item stored in a LIFO data structure is the first item extracted.

18.2 A static stack has a fixed size, and is implemented as an array. A dynamic stack grows in size as needed, and is implemented as a linked list. Advantages of a dynamic stack: There is no need to specify the starting size of the stack. The stack automatically grows each time an item is pushed, and shrinks each time an item is popped. Also, a dynamic stack is never full (as long as the system has free memory).

18.3 Push: An item is pushed onto, or stored in the stack.

Pop: An item is retrieved (and hence, removed) from the stack.

18.4 vector, list, or deque.

Chapter 1919.1 The function calls itself with no way of stopping. It creates an infinite recursion.

19.2 The solvable problem that the recursive algorithm is designed to solve. When the recursive algo-rithm reaches the base case, it terminates.

19.3 10

19.4 In direct recursion, a recursive function calls itself. In indirect recursion, function A calls function B, which in turn calls function A.

Chapter 2020.1 A standard linked list is a linear data structure in which one node is linked to the next. A binary

tree is non-linear, because each node can point to two other nodes.

20.2 The first node in the list.

Gaddis4.book Page 1361 Monday, January 6, 2003 5:16 PM

Page 130: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1362 Answers to Checkpoints

20.3 A node pointed to by another node in the tree.

20.4 A node that points to no other nodes.

20.5 An entire branch of the binary tree, from one particular node down.

20.6 Information can be stored in a binary tree in a way that makes a binary search simple.

20.7 1. The node’s left subtree is traversed.2. The node’s data is processed.3. The node’s right subtree is traversed.

20.8 1. The node’s data is processed2. The node’s left subtree is traversed.3. The node’s right subtree is traversed.

20.9 1. The node’s left subtree is traversed.2. The node’s right subtree is traversed.3. The node’s data is processed

20.10 The node to be deleted is node D.1. Find node D’s parent and set the child pointer that links the parent to node D, to NULL. 2. Free node D’s memory.

20.11 The node to be deleted is node D.1. Find node D’s parent.2. Link the parent node’s child pointer (that points to node D) to node D’s child.3. Free node D’s memory.

20.12 1. Attach the node’s right subtree to the parent, and then find a position in the right subtree to attach the left subtree.2. Free the node’s memory

Gaddis4.book Page 1362 Monday, January 6, 2003 5:16 PM

Page 131: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1363

Appendix PSolutions to Odd Numbered Review Questions

Chapter 11. Main memory, or RAM, is volatile, which means its contents are erased when power is removed

from the computer. Secondary memory, such as a disk, does not lose its contents when power is removed from the computer.

3. System A: Multi-user, multi-taskingSystem B: Single user, multi-taskingSystem C: Single user, single tasking

5. Because high level languages are more like natural language.

7. A syntax error is the misuse of a key word, operator, punctuation, or other part of the program-ming language. A logical error is a mistake that causes the program to produce the wrong results.

9. CPU

11. disk

13. instructions

15. machine language

17. low-level

19. key words

21. operators

23. syntax

25. defined

27. input

29. hierarchy chart

Gaddis4.book Page 1363 Monday, January 6, 2003 5:16 PM

Page 132: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1364 Solutions to Odd Numbered Review Questions

31. Hierarchy chart:

33. 7

35. 365

Chapter 21. 1, 2, 3

3. int months = 2, days, years = 3;5. C style

7. #include <iostream>int main(){

cout << "Two mandolins like creatures in the\n\n\n";cout << "dark\n\n\n";cout << "Creating the agony of ecstasy.\n\n\n";cout << " - George Barker\n\n\n";return 0;

}9. C

11. B

13. B

15. B, C

17. A) 12B) 4C) 2D) 6E) 1

19. A

21. true

Calculate a retail sale.

Calculate and display sales tax.

Get input. Calculate and display sale total.

Read retail price. Read tax rate. Multiply retail price by tax rate. Store result in tax.

Display tax. Add tax to retail price. Store result in total.

Display total.

Gaddis4.book Page 1364 Monday, January 6, 2003 5:16 PM

Page 133: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1365

23. true

25. int speed, time, distance;speed = 20;time = 10;distance = speed * time;cout << distance << endl;

27. The C-style comments symbols are backwards.

iostream should be enclosed in angle brackets.

There shouldn’t be a semicolon after int main.

The opening and closing braces of function main are reversed.

There should be a semicolon after int a, b, c.

The comment \\ Three integers should read // Three integers.

There should be a semicolon at the end of the following lines:

a = 3b = 4c = a + b

cout begins with a capital letter.

The stream insertion operator (that appears twice in the cout statement) should read << instead of <.

The cout statement uses the variable C instead of c.

Chapter 31. A) 40

B) 39C) No

3. A) cin >> setw(25) >> name;B) cin.getline(name, 25);

5. iostream and iomanip7. A) price = 12 * unitCost;

B) cout << setw(12) << 98.7; C) cout << 12;

9. a = 12 * x;z = 5 * x + 14 * y + 6 * k;y = pow(x, 4);g = (h + 12) / (4 * k);c = pow(a, 3) / (pow(b, 2) * pow(k, 4));

11. B

13. const int rate = 12;15. east = west = north = south = 1;

Gaddis4.book Page 1365 Monday, January 6, 2003 5:16 PM

Page 134: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1366 Solutions to Odd Numbered Review Questions

17. cout << setw(12) << fixed << setprecision(4) << totalAge;

19. cos21. tan23. fmod25. log1027. sqrt29. Display “Enter the customer’s maximum amount of credit: ”.

Read maxCredit.Display “Enter the amount of credit the customer has used: ”.Read creditUsed.availableCredit = maxCredit – creditUsed.Display “The customer’s available credit is $”.Display availableCredit.

#include <iostream>using namespace std;

int main(){

float maxCredit, creditUsed, availableCredit;

cout << "Enter the customer's maximum amount of credit: ";cin >> maxCredit;cout << "Enter the amount of credit used by the customer: ";cin >> creditUsed;availableCredit = maxCredit – creditUsed;cout << "The customer's available credit is $";cout << availableCredit << endl;return 0;

}31. #include <iostream> is missing.

Each cin and cout statement starts with capital C.

The << operator is mistakenly used with cin.

The assignment statement should read:

sum = number1 + number2;

The last statement should have << after cout.

The last statement is missing a semicolon.

33. The variables should not be declared const.

The last statement is missing a semicolon.

Gaddis4.book Page 1366 Monday, January 6, 2003 5:16 PM

Page 135: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1367

35. There shouldn’t be a semicolon after the #include directive.

The function header for main should read:

int main()The first cout statements should end with a semicolon.

The variable number1 is used, but never defined.

The combined assignment operator is improperly used. The statement should read:

half /= 2;

There is also a logical error in the program. The value divided by 2 should be number1, not half.

The following statement:

cout << fixedpoint << showpoint << half << endl;

should read:

cout << fixed << showpoint << half << endl;

37. Your monthly wages are 3225.000000

39. In 1492 Columbus sailed the ocean blue.

41. Hello George Washington

Chapter 41. In an if/else if statement, the conditions are tested until one is found to be true. The condi-

tionally executed statement(s) are executed and the program exits the if/else if statement. In a series of if statements, all of the if statements execute and test their conditions because they are not connected.

3. A flag is a Boolean variable signaling that some condition exists in the program. When the flag is set to false it indicates the condition does not yet exist. When the flag is set to true it indicates that the condition does exist.

5. It takes two expressions as operands and creates a single expression that is true only when both subexpressions are true.

7. Because they test for specific relationships between items. The relationships are greater-than, less-than, equal-to, greater-than or equal-to, less-than or equal-to, and not equal-to.

9. relational

11. false, true

13. true

15. true, false

17. nested

19. ||21. left-to-right

Gaddis4.book Page 1367 Monday, January 6, 2003 5:16 PM

Page 136: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1368 Solutions to Odd Numbered Review Questions

23. ||25. strings (C-strings, specifically)

27. integer

29. break

31. if (y == 0)x = 100;

33. if (sales < 10000)commission = .10;

else if (sales <= 15000)commission = .15;

elsecommission = .20;

35. if (amount1 > 10)if (amount2 < 100)

cout << (amount1 > amount2 ? amount1 : amount2);37. if (temperature >= -50 && temperature <= 150)

cout << "The number is valid.";39. if (strcmp(title1, title2) < 0)

cout << title1 << " " << title2 << endl;else

cout << title2 << " " << title1 << endl;41. C, A, B

43. false

45. true

47. true

49. true

51. true

53. false

55. F

57. T

59. The conditionally executed blocks in the if/else construct should be enclosed in braces.

The following statement:

cout << "The quotient of " << num1 <<

should read:

cout << "quotient of " << num1;

61. The if statement does not properly test the strings for equality. The strcmp function should be used instead of the == operator.

63. It should read if (!(x > 20))65. It should read if (count < 0 || count > 100)

Gaddis4.book Page 1368 Monday, January 6, 2003 5:16 PM

Page 137: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1369

Chapter 51. By indenting the statements, you make them stand out from the surrounding code. This helps you

to identify at a glance the statements that are conditionally executed by a loop.

3. Because they are only executed when a condition is true.

5. The while loop.

7. The for loop.

9. An accumulator is used to keep a running total of numbers. In a loop, a value is usually added to the current value of the accumulator. If it is not properly initialized, it will not contain the correct total.

11. increment, decrement

13. postfix

15. iteration

17. posttest

19. counter

21. accumulator

23. do-while25. for27. nested

29. continue

31. do{

float num1, num2;char again;cout << "Enter two numbers: ";cin >> num1 >> num2;cout << "Their sum is " << (num1 + num2) << endl;cout << "Do you wish to do this again? (Y/N) ";cin >> again;

} while (again == 'Y' || again == 'y');33. float total = 0.0, num;

for (int count = 0; count < 10; count++){

cout << "Enter a number: ";cin >> num;total += num;

}35. int x;

do{

cout << "Enter a number: ";cin >> x;

} while (x > 0);

Gaddis4.book Page 1369 Monday, January 6, 2003 5:16 PM

Page 138: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1370 Solutions to Odd Numbered Review Questions

37. for (int count = 0; count < 50; count++)cout << "count is " << count << endl;

39. false

41. false

43. false

45. false

47. false

49. true

51. true

53. false

55. true

57. The while loop tests the variable again before any values are stored in it.

The while loop is missing its opening and closing braces.

59. The variable total is not initialized to 0.

The statement that calculates the average performs integer division. It should use a type cast to cast either total or numCount to a float. The variable count is incremented in the for loop’s update expression and again within the for loop.

61. The variable total is not initialized to 0.

The while loop does not change the value of count, so it iterates an infinite number of times.

Chapter 61. Because they are created in memory when the function begins execution, and are destroyed when

the function ends.

3. Inside the parentheses of a function header.

5. Yes. The first argument is passed into the parameter variable that appears first inside the function header’s parentheses. Likewise, the second argument is passed into the second parameter, and so on.

7. It makes the program easier to manage. Imagine a book that has a thousand pages, but isn’t divided into chapters or sections. Trying to find a single topic in the book would be very difficult. Real-world programs can easily have thousands of lines of code, and unless they are modularized, they can be very difficult to modify and maintain.

9. A function such as the following could be written to get user input. The input is stored in the vari-ables that are passed as arguments.

void getValues(int &x, int &y){

cout << "Enter a number: ";cin >> x;cout << "Enter another number: ";cin >> y;

}11. void13. arguments

Gaddis4.book Page 1370 Monday, January 6, 2003 5:16 PM

Page 139: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1371

15. value

17. local

19. global

21. local

23. return25. last

27. reference

29. reference

31. parameter lists

33. float half(float num){

return num / 2;}

35. void timesTen(int num){

cout << (num * 10) << endl;}

37. void getNumber(int &num){

cout << "Enter a number in the range 1 – 100 : ";cin >> num;while (num < 1 || num > 100){

cout << "That number is out of range.\n";cout << "Enter a number in the range 1 – 100 : ";cin >> num;

}}

39. false

41. true

43. true

45. false

47. true

49. true

51. true

53. false

55. true

57. The assignment statement should read:

average = (value1 + value2 + value3) / 3.0;

The function is defined as a float but returns no value.

Gaddis4.book Page 1371 Monday, January 6, 2003 5:16 PM

Page 140: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1372 Solutions to Odd Numbered Review Questions

59. The parameter should be defined as:

int &value

The cin statement should read:

cin >> value;

Chapter 71. The size declarator is used in a definition of an array to indicate the number of elements the array

will have. A subscript is used to access a specific element in an array.

3. Because, with the array alone the function has no way of determining the number of elements it has.

5. By providing an initialization list. The array is sized to hold the number of values in the list.

7. Because an array name without brackets and a subscript represents the array’s beginning memory address. The statement shown attempts to assign the address of array2 to array1, which is not permitted.

9. By reference.

11. By using the same subscript value for each array.

13. Eight rows

Ten columns

Eighty elements

sales[7][9] = 123.45;

15. • You do not have to declare the number of elements that a vector will have.• If you add a value to a vector that is already full, the vector will automatically increase its size to accommodate the new value.• A vector can report the number of elements it contains.

17. integer, 0

19. 0

21. bounds

23. 0

25. null terminator

27. =

29. address, or name

31. rows, columns

33. braces

35. Standard Template Library (or STL)

37. sequence

39. push_back

Gaddis4.book Page 1372 Monday, January 6, 2003 5:16 PM

Page 141: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1373

41. pop_back43. for (int i = 0; i < 20; i++)

cout << names[i] << endl;45. int id[10];// To hold ID numbers

float weeklyPay[10];// To hold weekly pay// Display each employee's gross weekly pay.for (int i = 0; i < 10; i++){

cout << "The pay for employee " << id[i] << " is $" << fixed << showpoint << setprecision(2) << weeklyPay[i] << endl;

}47. char countries[12]; // To hold the country names

long populations[12]; // To hold populations// Display each country's name and poplualtion.for (int i = 0; i < 12; i++){

cout << "The population of " << countries[1] << " is " << populations[i] << endl;

}49. char myNames[3][10] = {"Jason", "Lee", "Smith" };51. int row, col; // Loop counters

float total = 0.0; // Accumulator// Sum the values in the array.for (row = 0; row < 10; row++){

for (col = 0; col < 20; col++)total += values[row][col];

}53. false

55. true

57. true

59. false

61. false

63. true

65. false

67. true

69. true

71. true

73. true

75. true

77. false

Gaddis4.book Page 1373 Monday, January 6, 2003 5:16 PM

Page 142: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1374 Solutions to Odd Numbered Review Questions

79. false

81. true

83. true

85. The size declarator cannot be negative.

87. The initialization list must be enclosed in braces.

89. Two of the initialization values are left out.

91. A null terminator must be specified in the initialization list.

93. The parameter should be declared as int nums[].

Chapter 81. Because it uses a loop to sequentially step through an array, starting with the first element. It com-

pares each element with the value being searched for, and stops when either the value is found or the end of the array is encountered.

3. N/2 times

5. Ten

7. The selection sort usually performs fewer exchanges because it moves items immediately to their final position in the array.

9. binary

11. binary

13. descending

15. false

17. false

Chapter 91. It dereferences a pointer, allowing code to work with the value that the pointer points to.

3. Multiplication operator, definition of a pointer variable, and the indirection operator.

5. It adds 4 times the size of an int to the address stored in ptr.

7. To dynamically allocate memory.

9. To free memory that has been dynamically allocated with the new operator.

11. address

13. pointer

15. pointers

17. new19. null

21. new23. *(set + 7) = 99;

Gaddis4.book Page 1374 Monday, January 6, 2003 5:16 PM

Page 143: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1375

25. delete [] tempNumbers;27. true

29. true

31. false

33. false

35. true

37. false

39. true

41. false

43. false

45. The assignment statement should read ptr = &x;47. The assignment statement should read *ptr = 100;49. Multiplication cannot be performed on pointers.

51. iptr cannot be initialized with the address of ivalue. ivalue is defined after iptr.

53. The second statement should read pint = new int;55. The last line should read delete [] pint;

Chapter 101. cctype3. 'A'

'B''d''E'

5. cstring7. string9. isupper

11. isdigit13. toupper15. cctype17. concatenate

19. strcpy21. strcmp23. atoi25. atof27. if (toupper(choice) == 'Y')29. if (strlen(name) <= 9)

strcpy(str, name);

Gaddis4.book Page 1375 Monday, January 6, 2003 5:16 PM

Page 144: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1376 Solutions to Odd Numbered Review Questions

31. int wCount(char *str){

int num = 0;while (*str != '\0'){

if (*str == 'w')num++;

}return num;

}33. false

35. false

37. true

39. false

41. true

43. The isupper function can only be used to test a character, not a string.

45. The compiler will not allocate enough space in string1 to accommodate both strings.

Chapter 111. A data type that is built into the C++ language, such as int, char, float, etc.

3. The elements of an array must all be of the same data type. The members of a structure may be of different data types.

5. A) FullName info;B) info.lastName = "Smith";

info.middleName = "Bart";info.firstName = "William";

C) cout << info.lastName << endl;cout << info.middleName << endl;cout << info.firstName << endl;

7. A) "Canton"

B) "Haywood"

C) 9478

D) uninitialized

9. All the members of a union occupy the same area of memory, whereas the members of a structure have their own memory locations.

11. declared

13. members

15. tag

17. Car hotRod = {"Ford", "Mustang", 1997, 20000};19. Car forSale[35] = {{"Ford", "Taurus", 1997, 21000},

{"Honda", "Accord", 1992, 11000}, {"Lamborghini", "Countach", 1997, 200000}};

Gaddis4.book Page 1376 Monday, January 6, 2003 5:16 PM

Page 145: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1377

21. struct TempScale{

float fahrenheit;float centigrade;

};struct Reading{

int windSpeed;float humidity;tempScale temperature;

};Reading today;

23. void showReading(Reading values){

cout << "Wind speed: " << values.windSpeed << endl;cout << "Humidity: " << values.humidity << endl;cout << "Fahrenheit temperature: " <<values.temperature.fahrenheit << endl;cout << "Centigrade temperature: " <<values.temperature.centigrade << endl;

}25. Reading getReading()

{Reading local;

cout << "Enter the following values:\n";cout << "Wind speed: ";cin >> local.windSpeed;cout << "Humidity: ";cin >> local.humidity;cout << "Fahrenheit temperature: ";cin >> local.temperature.fahrenheit;cout << "Centigrade temperature: ";cin >> local.temperature.centigrade;return local;

}27. rptr->WindSpeed = 50;29. union Items

{char alpha;int num;long bigNum;float real;

};Items x;

31. num = 452;33. true

Gaddis4.book Page 1377 Monday, January 6, 2003 5:16 PM

Page 146: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1378 Solutions to Odd Numbered Review Questions

35. false

37. false

39. true

41. true

43. true

45. false

47. false

49. true

51. true

53. The structure declaration has no tag.

55. No structure variable has been declared. TwoVals is the structure tag.

57. The initialization list of the customer variable must be enclosed in braces.

59. Structure members cannot be initialized in the structure definition.

61. The function must define a variable of the TwoVals structure. The variable, then, should be used in the assignment statement.

63. Both x and y cannot be meaningfully used at the same time.

Chapter 121. The fstream data type allows both reading and writing, while the ifstream data type allows

only for reading, and the ofstream data type allows only for writing.

3. Its contents are erased. (In other words, the file is truncated.)

5. By reference because the internal state of file stream objects changes with most every operation. They should always be passed to functions by reference to ensure internal consistency.

7. When the end of the file has been encountered. The eof member function reports the state of this bit.

9. By using the getline member function.

11. Two arguments: The starting address of the section of memory where the data will be stored, and the number of bytes to read.

13. The seekg function moves a file’s write position, and the seekp function moves a file’s read posi-tion.

15. Call the file object’s clear member function.

17. Use the seekg member function to move the read position back to the beginning of the file.

19. NULL or 0

21. getline23. put25. text, ASCII text

27. structures

29. read

Gaddis4.book Page 1378 Monday, January 6, 2003 5:16 PM

Page 147: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1379

31. sequential

33. seekg35. tellg37. ios::beg39. ios::cur41. fstream places("places.dat", ios::in | ios::out);43. pets.open("pets.dat", ios::in);

fstream pets("pets.dat" ios::in);45. fstream employees;

employees.open("emp.dat", ios::in | ios::out | ios::binary);if (!employees)

cout << "Failed to open file.\n";47. dataFile.seekg(0L, ios::end);

numBytes = dataFile.tellg();cout << "The file has " << numBytes << " bytes.\n";

49. true

51. true

53. true

55. false

57. true

59. true

61. true

63. false

65. File should be opened as

fstream file("info.dat", ios::in | ios::out);

or

fstream file;file.open("info.dat", ios::in | ios::out);

67. File access flags must be specified with fstream objects.

69. The file access flag should be ios::in.

Also, the while statement should read

while(!dataFile.eof())

71. The file access flag should be ios::in. Also, the get member function cannot be used to read a string.

73. The file access flag should be ios::out. Also, the last line should read

dataFile.write(reinterpret_cast<char *>(&dt), sizeof(dt));

Gaddis4.book Page 1379 Monday, January 6, 2003 5:16 PM

Page 148: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1380 Solutions to Odd Numbered Review Questions

Chapter 131. A class describes a data type. An instance of a class is an object of the data type that exists in memory.

3. private5. A class is analogous to the blueprint.

7. Yes it is. This protects the variables from being directly manipulated by code outside the class, and prevents them from receiving invalid data.

9. When the function is necessary for internal processing, but not useful to the program outside the class. In some cases a class may contain member functions that initialize member variables or destroy their contents. Those functions should not be accessible by an external part of program because they may be called at the wrong time.

11. A default constructor is a constructor that is called without any arguments. It is not possible to have more than one default constructor.

13. Yes, the constructor executes when the object is created.

15. procedural programming, object-oriented programming

17. object-oriented

19. class21. access specifier

23. public25. ->27. canine.cpp

29. constructor

31. constructors

33. default

35. ~

37. default

39. constructor, destructor

41. class Circle{private:

float radius;public:

void setRadius(float r){ radius = r; }

float getRadius(){ return radius; }

float getArea(){ return 3.14159 * radius * radius; }

};

Gaddis4.book Page 1380 Monday, January 6, 2003 5:16 PM

Page 149: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1381

43. class Circle{private:

float radius;public:

Circle(){ radius = 0.0; }

Circle(float r){ radius = r; }

void setRadius(float r){ radius = r; }

float getRadius(){ return radius; }

float getArea(){ return 3.14159 * radius * radius; }

};45. Circle collection[5] = {12, 7, 9, 14, 8 };47. false

49. false

51. false

53. true

55. false

57 true

59. true

61. true

63. false

65. true

67. There should not be a colon after the word Circle.

Colons should appear after the words private and public.

A semicolon should appear after the closing brace.

69. The semicolon should not appear after the word DumbBell.

The function header for setWeight should appear as:

void DumbBell::setWeight(int w)

The line that reads:

DumbBell(200);

should read:

bar.setWeight(200);

bar.weight cannot be accessed outside of the class because no access specifier appeared before it in the class, making the variable private to the class by default. This means the cout statement will not work.

Gaddis4.book Page 1381 Monday, January 6, 2003 5:16 PM

Page 150: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1382 Solutions to Odd Numbered Review Questions

Chapter 141. Each class object has its own copy of the class’s instance member variables. All objects of a class

share the class’s static member variables.

3. Outside the class declaration.

5. Because every member function of the friend class would have access to the class’s private member variables.

7. When an object is initialized with another object’s data.

9. When an object has a pointer as a member, and it points to a chunk of dynamically-allocated memory. When this object is copied to another object via memberwise assignment, the receiving object’s pointer will point to the same chunk of memory.

11. It is a copy constructor that is automatically created for a class, and performs memberwise assign-ment.

13. The object on the right side of the = operator in the statement that called the overloaded operator function.

15. A dummy parameter is used in the function header of a postfix operator.

17. A Boolean value.

19. Place the key word static before the variable declaration (inside the class). Then, place a sepa-rate definition of the variable outside the class.

21. 3, 3, 1, 0, Thing::putThing(2);23. To inform the compiler of the class’s existence before it reaches the class’s definition.

25. Because the parameter variable is created in memory when the function executes, and is initialized with the argument object. This causes the copy constructor to be called.

27. outside

29. before

31. forward declaration

33. copy constructor

35. overloaded

37. composition

39. Bird Bird::operator=(const Bird &right)41. bool Yen::operator<(const Yen &right)43. Collection Collection::operator[](const Collection &sub)45. true

47. false

49. true

51. true

53. true

55. false

57. true

Gaddis4.book Page 1382 Monday, January 6, 2003 5:16 PM

Page 151: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1383

59. The copy constructor’s parameter should be a reference variable.

61. The overloaded + operator function header should read

void operator+(const Point &right)63. The float conversion function header should read

operator float()

Chapter 151. When one object is a specialized version of another object, there is an “is a” relationship between

them. This indicates that one class "is a" specialized version of the other class.

3. Base class access specification specifies how the derived class is allowed to access the members of the base class. Member access specification specifies how class members may be accessed by code outside the class.

5. No.

7. When a derived class has a function with the same name as a base class's function, and the base class function is not virtual, it is said that the function is redefined in the derived class. If the base class's function is virtual, however, it is said that the function is overridden.

9. An abstract base class is not instantiated itself, but serves as a base class for other classes. The abstract base class represents the generic, or abstract form of all the classes that are derived from it. A class is abstract when it has one or more virtual functions.

11. Dog13. public15. private17. inaccessible, protected, protected19. members

21. last

23. The base class version.

25. static27. polymorphism

29. abstract base class

31. chain

33. override or redefine

35. class SoundSystem : public CDplayer, public Tuner, public CassettePlayer37. class B

{private:

int m;protected:

int n;

Gaddis4.book Page 1383 Monday, January 6, 2003 5:16 PM

Page 152: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1384 Solutions to Odd Numbered Review Questions

public:void setM(int);int getM();void setN(int);int getN();virtual int calc()

{ return m * n; }};

class D : public B{protected:

float q;float r;

public:void setQ(float);float getQ();void setR(float);float getR();virtual float calc()

{ return q * r; }};

39. true

41. true

43. false

45. false

47. true

49. true

51. true

53. The first line of the class declaration should read

class Car : public VehicleAlso, the class declaration should end in a semicolon.

55. The constructor function header should read

SnowMobile(int h, float w) : Vehicle(h)Also, the constructor parameter w is not used.

57. The parameter lists for the setContents functions must be different.

Chapter 161. A throw point is a line in a program that contains a throw statement, thus throwing an exception.

3. A try block contains a block of code executing any statements that might directly or indirectly cause an exception to be thrown. A catch block catches a specific exception and contains code to respond to it.

Gaddis4.book Page 1384 Monday, January 6, 2003 5:16 PM

Page 153: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1385

5. Once an exception has been thrown, the program cannot jump back to the throw point. The func-tion that executes a throw statement will immediately terminate. If that function was called by another function, then the calling function will terminate as well. This process, known as unwind-ing the stack, continues for the entire chain of nested function calls, from the throw point, all the way back to the try block.

7. By catching the bad_alloc exception.

9. Because a class object passed to a function template must support all the operators the function will use on the object.

11. Sequence and associative.

13. throw point

15. catch

17. template prefix

19. specialized

21. associative

23. bad_alloc25. char * allocBlock(int size)

{char *ptr;

try{

ptr = new char[size];}catch(bad_alloc){

ptr = 0;}return ptr;

}27. template <class T>

void displayContents(T array[], int size){

for (int i = 0; i < size; i++)cout << array[i] << endl;

}

29. // Search for the value 7.binary_search(vect.begin(), vect.end(), 7)

31. false

33. true

35. true

37. true

39. false

41. true

43. false

45. true

Gaddis4.book Page 1385 Monday, January 6, 2003 5:16 PM

Page 154: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1386 Solutions to Odd Numbered Review Questions

47. The try block must appear before the catch block.

49. The return statement should read return number * number;51. The type parameter T2 is not used.

53. The statement should read cout << valueSet[2] << endl;

Chapter 171. A linked list can easily grow or shrink in size. In fact, the programmer doesn’t need to know how

many nodes will be in the list. They are simply created in memory as they are needed. Also, when a node is inserted into or deleted from a linked list, none of the other nodes have to be moved.

3. A pointer that simply points to the first node in the list.

5. The last node in the list usually points to address 0, the null address.

7. Appending a node means that a new node is added to the end of the list. Inserting a node means that a new node is inserted somewhere in the middle of the list.

9. • Remove the node from the list without breaking the links created by the next pointers.• Deleting the node from memory.

11. In a singly linked list each node is linked to a single other node. In a doubly linked list each node not only points to the next node, but also the previous one. In a circularly linked list the last node points to the first,

13. head pointer

15. NULL

17. Inserting

19. circular

21. ListNode *nodePtr;nodePtr = head;while (nodePtr){

cout << nodePtr->value << endl;nodePtr = nodePtr->next;

}23. list<float> myList;25. myList.reverse();27. false

29. true

31. false

33. nodePtr is never properly initialized.

35. The node pointers are simply set to NULL. The nodes themselves are not deleted from memory.

Chapter 181. Last in first out

3. A static stack has a fixed size and is usually implemented as an array. A dynamic stack expands as items are added to it. Dynamic stacks are implemented as linked lists.

Gaddis4.book Page 1386 Monday, January 6, 2003 5:16 PM

Page 155: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1387

5. isFull and isEmpty. The isFull operation returns true if the stack is full, and false otherwise. This operation is necessary to prevent a stack overflow in the event a push operation is attempted when all of the stack’s elements have values stored in them. The isEmpty operation returns true when the stack is empty, and false otherwise. This prevents an error from occurring when a pop operation is attempted on an empty stack.

7. vector, list, or deque. By default it is base on the deque type.

9. The rear

11. The two primary queue operations are enqueuing and dequeuing. To enqueue means to insert an element at the rear of a queue, and to dequeue means to remove an element from the front of a queue.

13. last

15. static

17. vectors, lists, and deques19. enqueuing and dequeuing

21. deque23.

25.

27. Code segment using an if/else statement:

if (rear == queueSize - 1)rear = 0;

elserear++;

Code segment using modular arithmetic:

rear = (rear + 1) % queueSize;29. false

31. true

19

8

Top of stack

Bottom of stack

129 10

Front Rear

Gaddis4.book Page 1387 Monday, January 6, 2003 5:16 PM

Page 156: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

1388 Solutions to Odd Numbered Review Questions

Chapter 191. For question 12: num <= 0

For question 13: num > 0For question 14: pos < size – 1

3. Recursive functions are less efficient, due to the overhead associated with each function call.

5. The program will eventually run out of stack memory and abort.

7. base case

9. indirect

11. int findLargest(const int array[], int start, int end){ int largest;

if(start == end) return array[start]; else {

largest = findLargest(array, start + 1, end); if(array[start] >= largest)

return array[start];else

return largest; }}

13. *******************************************************

Chapter 201. Two others.

3. A node that has no children.

5. The order in which the values are inserted.

7. root node

9. leaf node

11. inorder, preorder, and postorder

Gaddis4.book Page 1388 Monday, January 6, 2003 5:16 PM

Page 157: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Solutions to Odd Numbered Review Questions 1389

13. (Recursive Function)Display In Order(Node Pointer)

If Node Pointer is not NullDisplay In Order (Node Pointer -> Left).Display the node's Value.Display In Order (Node Pointer -> Right).

End IfEnd Display In Order

15. (Recursive Function)Display Post Order(Node Pointer)

If Node Pointer is not NullDisplay Post Order (Node Pointer -> Left).Display Post Order (Node Pointer -> Right).Display the node's Value.

End IfEnd Display Post Order

17.

19. 12 7 3 9 10 22 18 14 20 24 30

21. true

23. false

25. false

PointerPointer

TreePointer

12

PointerPointer

NULL

9

PointerPointer

7

NULLNULL

PointerPointer

3

NULL NULL

PointerPointer

10

PointerPointer

22

PointerPointer

18PointerPointer

24

PointerPointer

30

NULL

PointerPointer14

NULL

PointerPointer

20

NULL NULL

NULL

NULL

NULL

Gaddis4.book Page 1389 Monday, January 6, 2003 5:16 PM

Page 158: Appendix C Introduction to Flowchartingdigital.cs.usu.edu/~scott/1400_f06/Gaddis_Appendices.pdf · Appendix C Introduction to Flowcharting ... The position of the module symbol indicates

Gaddis4.book Page 1390 Monday, January 6, 2003 5:16 PM