CHAPTER 4

Literals, Variables,
and Constants

Chapter Objectives

By the end of the chapter, readers will be able to:

images  Understand the types and use of literals.

images  Explore the role of data types in programming.

images  Describe some of the key primitive data types found in C++.

images  Understand the requirements and conventions used in naming identifiers.

images  Differentiate between initialization and assignment.

images  Use and interpret an ASCII chart.

images  Understand the use of constants.

images  Understand the use of variables.

Introduction

In this chapter we will explore how to store information in memory so that our program has access to the information when needed. Several other chapters focus on the same issue, but they all require the basic concepts introduced in this chapter.

To explain the difference between literals, variables, and constants, let's look at the mathematical formula to calculate the circumference of a circle: 2πr. The character r is a variable that represents the radius of the circle. The symbol π represents the constant for pi, and the character 2 is a numeric literal. We will refer to this example throughout the chapter.

4.1 Literals

A literal is a value that is interpreted exactly as it is written. In our introductory example of the circle circumference formula, the 2 is a numeric literal. It is not a variable or a constant, as explained later in this chapter, because it has no name associated with it.

There are three types of literals: numeric, character, and string. In C++, a numeric literal is represented exactly as suspected. Examples of numeric literals would include 14, 457, and 3.14. A character literal is a single character enclosed by single quotation marks, such as ‘a’, ‘Z’, and ‘9’. A string literal is composed of multiple characters surrounded by double quotation marks (''). You have already been exposed to string literals in the previous chapters. For example, in the following statement, the string literal would be “Hello World”.

std::cout << “Hello World”;

Table 4.1.1 shows examples of the different types of literals.

In Table 4.1.1, the fourth numeric literal, 0xFF, specifies that the value following the x is a hexadecimal value. Notice that the fifth numeric literal starts with a zero, which designates that the literal is an octal value.

Also notice that in the third example of string literals, “A” is a single character surrounded by double quotation marks. Although perfectly legal, it should be avoided because of the additional overhead required. We will have more to say about this later in the text.

Literal Type

Examples

Numeric

0

 

3.12

 

-5

 

0xFF

 

0777

Character

’A’

 

''

String

“Hello World”

 

“Ralph”

 

“A”

Table 4.1.1 Literals

Section 4.1 Exercises

In the following exercises, find the illegal literals. If the literal is legal, state what type of literal it is.

1. -12.34

2. ‘Hello’

3. “F”

4. “1234”

5. ‘1’

6. A

7. “Marcus”

4.2 Character Escape Sequences

An exception to the rule that literals are interpreted exactly as they are written is an escape sequence. Character escape sequences also violate the rule that a character literal be a single character surrounded by single quotation marks. All escape sequences start with a backslash () followed by one or more characters.

Escape Sequence

Character Representation

Carriage return and line feed (new line)

Tab (eight characters wide)

Double quote

Single quote

\

Backslash

Null character

Table 4.2.1 Character escape sequences

The reason for character escape sequences is that it is difficult to use some characters as literals. Escape sequences allow us to use a special notation to represent a specific character or a control character. Some escape sequences, such as and , are referred to as control characters because they don't display anything but control the position of the text displayed. Table 4.2.1 shows some of the more commonly used escape sequences.

Example 4.2.1 demonstrates how to use escape sequences.

images

Section 4.2 Exercise

1.  Given the following text, make a legal string literal using escape sequences.

This is a “backslash” , this is a forward slash /.

The way to remember is to stand up and turn to your right.

If you lean “back”, you become a backslash; if you lean

“forward”, you become a forward slash.

This is Randy's surefire method!

4.3 Variable Declarations

We will use mathematics to help introduce the concept of variables. A variable is nothing more than a placeholder whose contents can change. The placeholder is given a name (many times x in mathematics), which we use to reference the value stored in the variable. If we again refer to the circumference formula, the r is a variable representing the radius. Programming has taken this concept and added some other features.

In order to use a variable in any of our programs, we must first declare it. Declaring a variable has several purposes:

images  Informs the operating system how much internal memory (RAM) the variable will need

images  Identifies the memory address to use for that variable

images  Identifies the type of data to be stored in that physical memory location

images  Indicates what operations (+, -, /) can be performed on the data contained within that variable (or memory location)

This is a very crucial concept, and it is imperative that by the end of this section you fully understand variables and their usage. The basic syntax for a variable declaration is:

<data type> identifier;

The previous <data type> needs to be replaced with any data type, many of which are discussed in the next section. This declaration creates a variable with the name identifier. This form of declaration is shown in Example 4.3.1.

images

A variable declaration can be written in a variety of ways. For example, we can declare many distinct variables in a single statement as long as they are all the same data type.

 <data type> identifier1, identifier2, identifier3;

This form of variable declaration is illustrated in Example 4.3.2.

images

In C++, variables can be declared anywhere within your code as long as they are declared before they are used. However, at this point we strongly suggest that all of your variable declarations be placed directly after the opening curly brace of main.

4.3.1 Variable's Initial Value

So what is the initial value stored in the variables declared in Example 4.3.2? The value in each variable is unknown, often referred to as undefined and commonly thought of as garbage. The reason for the unknown value is that memory will never be guaranteed to be clean or empty when given to your variable. Therefore, when we request memory for a variable, the variable may contain whatever was there previously. We can initialize variables to either a constant or a literal, which allows us to provide a known value to a variable during its declaration. This is also referred to as initializing the variable. The syntax is shown here.

 1. <data type> identifier = <literal>;

 2. <data type> identifier = <constant>;

Both of these forms are demonstrated in Example 4.3.3.

images

Interestingly enough, we can even initialize our new variable to another variable's value as long as the variable we are using to obtain the initial value is declared before being used. Assuming that identifier has already been declared and, preferably, initialized, the syntactical example that follows initializes identifier2 with the value stored in the variable identifier.

 <data type> identifier2 = identifier;

Although this form is not used as often as that in the examples shown previously, Example 4.3.4 illustrates this style.

images

Be careful, however; in Example 4.3.4, only base_salary and staff_salary are initialized. The other variable, num_dependents, remains uninitialized, and its value is unknown or indeterminate.

It is legal in C++ to use an additional form of variable initialization. Notice the parentheses in the following syntax diagrams.

1. <data type> identifier (<literal>);

2. <data type> identifier (<constant>);

3. <data type> identifier1, identifier2 (identifier);

images

The style shown in Example 4.3.5 is the preferred style of some programmers, while others choose the style discussed previously. Just remember—the parenthetical form can only be used with initialization.

4.3.2 Initialization

One of the principles good programmers adhere to is to always know the state, or value, of all variables. If you declare a variable without initializing it, the value stored in the variable is unknown (or undefined). Even if the variable is assigned a value later, there is still a period of time during which the value is unknown. Therefore, it is always a good practice to give all variables an initial value at the time they are declared.

The most common value used to initialize numeric variables is zero. Character variables are usually initialized to the null character ().

4.3.3 Data Types

A data type is a key piece to any variable declaration. It specifies the type of data to be stored in the variable, the amount of memory the variable uses, and the operations (+,, *, /) that can be used on the variable. There are many different data types to choose from, some of which are shown in Table 4.3.1. All of the data types shown are primitive data types.

images

Table 4.3.1 Data types

Table 4.3.1 is sure to raise some questions. First, the size of an int is dependent on which operating system the program is running. For example, an int in Windows 3.1, which is a 16-bit operating system, is allocated two bytes (16 bits). On the current version of Windows XP, which is a 32-bit operating system, an int is allocated four bytes (32 bits) of memory. Starting to see the pattern? What would happen if we were running our program on one of the newer 64-bit operating systems?

The amount of memory allocated is the key to determining the range of values an int can hold on the platform you are targeting with your program. On a 32-bit operating system, an int is 32 bits in size. Since each bit only has two possibilities, a 0 or a 1, we could calculate the number of different possibilities as 232. However, the most significant bit (MSB) is used as a sign bit, eliminating that bit from our calculations. Therefore, we are left with ±231, which equates to the range of −2,147,483,648 to 2,147,483,647. We can use the same idea with a 16-bit operating system: −215, which equates to the range of −32,768 to 32,767.

Some of you might be concerned about the one bit that can't be used as data. There is a remedy! The unsigned prefix allows you to use the MSB as data rather than as a sign bit for all integral data types. This means you can have: unsigned char, unsigned short, unsigned int, and unsigned long.

The next thing many beginning students often find confusing is the long and long double data types. These data types are guaranteed to be equal to or bigger than an int and a double. Both of the larger data types are exactly the same size as the smaller data types (assuming a 32-bit operating system).

STYLE NOTE One of the lost arts of programming to resurface in recent years relates to memory management. When computers had a very limited amount of memory, programmers were forced to be very conservative. Now that computers have much more memory, some programmers forget that they should still not waste resources. One thing to remember as you declare variables is to use the smallest (most efficient) data type that will work for your projected needs. For example, there is no reason to declare a variable as an int if all you are going to do is hold a person's age. A short int (or just short) would work fine and conserve two bytes of memory.

One of the exciting areas continuing to emerge today is embedded systems. An embedded system is a very small, specialized computer that is a part of a larger system. A good example is a cell phone. There is at least one, and sometimes more, embedded systems in each phone.

One common aspect of all embedded systems is that they typically have very few resources, including memory. This is driving a resurgence of the increased awareness on the part of programmers in resource conservation.

4.3.4 The sizeof Operator

There is an easy way to determine how many bytes of memory are reserved for either a variable or a data type. The sizeof operator returns the number of bytes set aside for whatever parameter you pass it, as shown in Example 4.3.6.

images

In Example 4.3.6, Part 1 will print a 1 on the screen, while Part 2 will print a2.

4.3.5 Numeric Literal Suffixes

Numeric literals have a feature that allows you to explicitly specify the type of certain values. This feature, called a suffix, uses special characters to specify the type of literal. A numeric literal with the suffix F specifies that the number is to be treated as a float. Likewise, the L suffix specifies that the number is to be treated as a long.

This feature is mostly used in the initialization of variables. Since all floating-point numeric literals are treated as doubles, the compiler will generate a warning if a float variable is initialized or even assigned a floating-point literal. This is because a double is eight bytes and a float is four bytes; therefore, it would be like trying to stuff eight pounds of sand into a four-pound sack. Without the suffix, the compiler will flag that line with the warning: “initializing : truncation from double to float”. The F suffix changes the literal from the default type of double to a float. Example 4.3.7 demonstrates the use of suffixes.

images

Notice in Example 4.3.7 that the suffix can be upper- or lowercase. However, as shown with the declaration of salary, it is much more readable to use the uppercase letter for the suffix since it is difficult to distinguish between the lowercase L and the numeral 1. Although there are a few other suffixes, F and L are by far the most commonly used.

4.3.6 Naming Rules

There are certain rules in any programming language that we must adhere to when naming variables. The following are the rules for C++.

images  Variables can only be made up of letters, digits, and underscores.

images  Variables can't start with a digit (i.e., they must begin with a letter or an underscore).

images  Variables can't be a reserved word (e.g., if, else, while, for).

Although legal, it is best not to start a variable name with two underscores. The double underscore is usually reserved for special predefined identifiers.

STYLE NOTE Although not a requirement of the C++ language, all variable names should be descriptive of their purpose. This greatly increases both the readability and the maintainability of your program—by others as well as yourself. Sometimes beginning programmers fall into the trap of having single-character variable names, such as a, b, or c. If working with a well-known mathematical formula that uses these variables—such as the quadratic formula, in which they represent the coefficients of the x terms—then they might be appropriate. Generally, though, these short names are not representative of most of the data we tend to use, such as a person's age or test score. Use descriptive variable names like age or test_score to make your code more readable.

Section 4.3 Exercises

1.  Calculate the range for the following data types.

a. unsigned char

b. unsigned short

c. unsigned int(on a 16-bit operating system)

d. unsigned int(on a 32-bit operating system)

e. unsigned int(on a 64-bit operating system)

f. int (on a 64-bit operating system)

g. unsigned long

h. short int

2.  Which of the following are invalid variable names? For each invalid name, state why it is illegal.

a. a

b. tot-pay

c. tot_pay

d. avg

e. One&Two

f. One_and_Two

g. 1day

h. temp1

i. One and Two

j. ss#

k. short

3.  What is wrong with each of the following statements?

a. int a, intb;

b. int a = b;

int b = 0;

c. int a = 0, b = 3.5;

d. char grade = “A”;

e. char c = 1;

f. int a, b, c, d, e, f;

g. char x = “This is a test.”;

Section 4.3 Learn by Doing Exercises

The following exercises are intended to be short, hands-on programs emphasizing topics covered in this section. Write, compile, and run the following program.

1.  Write a program to create variables for each of the following items. Be sure to use the smallest data type appropriate for each situation.

a. A person's age (initialize to 19)

b. A person's shoe size (initialize to 8.5)

c. The altitude specified in feet (initialize to 0)

d. A person's gender (initialize to ‘F’)

e. A person's weight in pounds (initialize to 175)

4.4 ASCII Characters

As mentioned previously, all data is stored in memory as ones and zeros. For the most part, we can easily see how to convert numbers to their binary equivalent. However, how are characters stored as binary? The answer lies in what is called an ASCII chart. The American Standard Code for Information Interchange (ASCII) chart associates each character with a number. Take a few minutes now to review the ASCII chart in Appendix A.

As you can see from the chart, related characters tend to be grouped together. For example, capital letters start at 65 while lowercase letters start at 97. A common mistake is to think that the uppercase letters are represented by a higher number than the lowercase letters. Personally we agree, but we weren't consulted in 1967 when the chart was developed.

The basic ASCII chart has values ranging from 0 to 127. However, there is an extended ASCII chart that includes 256 unique characters. These additional characters are typically line-drawing characters or special characters for foreign languages. Examples of these characters are ê, ë, è, ï, and î.

So, how are characters stored in memory? Each character is associated with a numeric value that is stored in memory as binary. This process is shown here.

’A’ → 65 → 1000001
’a’ → 97 → 1100001

Although not used as often as character escape sequences, engineers sometimes need to use numbers specified in a different base other than base 10. Therefore, two numeric escape sequences that allow the programmer to specify ASCII values in either hexadecimal or octal bases are shown in Table 4.4.1.

Escape Sequence

Numeric Representation

x###

Hexadecimal number

o###

Octal number

Table 4.4.1 Numeric escape sequences

Be careful when using the escape sequences shown in Table 4.4.1. The value specified must not exceed 25510. Therefore, the largest hexadecimal value would be FF16, and the largest valid octal value would be 3778. Example 4.4.1 demonstrates how to use numeric escape sequences.

images

Section 4.4 Exercises

1.  Convert the following statement to ASCII numbers. Display the numbers in base 10.

Hello World!

2.  Convert the following number sequence to text.

67  43  43  32  82  111  99  107  115  33

4.5 Constants

Literals are a common occurrence in any program. We saw in the formula 2π r that the 2 is a literal but the π (pi) is a constant. The difference between a constant and a literal is that a constant has a name (e.g., PI) whereas a literal doesn't.

Creating constants for specific values, such as pi, not only makes your code more readable, it also makes it more easily modifiable as well. For example, seeing the literal 65 in a formula may not mean much, but what if you were to use the constant SPEED_LIMIT instead? It is much more readable. Now let's assume 65 can refer to the maximum speed limit as well as to a person's retirement age. If the retirement age were to change to 67, we would have to search through all of the instances of 65 within our code and change only those that refer to the retirement age to 67. This could be an extremely time-consuming task in a program that may have several hundred thousand lines of code. If we used constants, however, all we would need to do is change the value associated with that specific constant and recompile.

Example 4.5.1 shows how to declare constants in C++.

images

It is a common mistake for beginning programmers to forget to include the data type when declaring a constant. Although syntactically legal, the compiler assumes you wanted to create a constant integer. Therefore, if you initialized the constant to a decimal number, you will get a compiler warning about a type mismatch.

STYLE NOTE Notice in Example 4.5.1 that the names of the constants are uppercase. It is common practice to use uppercase letters to name constants and lowercase letters to name variables to easily and quickly differentiate between constants and variables.

Section 4.5 Exercises

What is wrong with each of the following statements?

 1.  const PI = 3.14;

 2.  const intDAYS_IN_YEAR;

 3.  const char AUTHOR = “Randy Albert”;

4.6 const Versus #define

We have already seen how to create a constant using the reserved word const. Another method is using the #define preprocessor directive, which has its roots firmly planted in the C programming language.

Here is the syntax for creating a constant using #define.

 #define identifier <value>

The <value> in the syntax diagram can be replaced with any literal: numeric, character, or string. Notice a couple of things about the preceding statement:

1.  There isn't a semicolon at the end

2.  There isn't an equals sign used to associate the value with the identifier

3.  No data type is provided

During the compilation process, when the preprocessor encounters a #define statement, the preprocessor searches through the entire program looking for the existence of the identifier. When it is found, the preprocessor textually replaces the identifier with the value we associated with it. Example 4.6.1 illustrates how to create constants using the #define directive.

images

Be careful not to use semicolons or equals signs in a #define directive. If you do, you introduce undesirable characters via your #define directive, as shown in Example 4.6.2.

images

Except for the #define, everything looks syntactically correct. However, the compiler tells us we have an error, but on a line of code we might not expect. The error is on the line:

 circumference = 2 * PI * radius;

Although this line of code appears syntactically correct, look what happens when we expand PI as the preprocessor would.

 circumference = 2 * = 3.14; * radius;

Even with your limited experience with mathematical expressions in C/C++, you can probably tell that the line of code is malformed. The problem is that we weren't able to locate the error until we manually expanded the #define directive. This type of syntax error is extremely difficult to find—even for experienced programmers.

We have now seen how to create constants using #define. Next, let's explore the added benefits of using const versus #define. First, using const allows us to associate a data type with a constant, and allocates the same amount of memory a variable of the same type would receive. Second, constants created with const provide the added benefit of type checking. Last, although it doesn't mean much now, constants declared using const have scope, meaning we can hide the constant from other parts of our program. Constants declared with #define are always going to be seen by all parts of our program.

Given these added benefits, we suggest all C++ constants be made using the const reserved word. The potential dangers of #define even caused a change in the C language specifications. The newer versions of C allow the use of const to create constants.

4.7 Bringing It All Together

Now that we have covered many of the fundamental concepts associated with declaring and initializing variables, it's time to make sure you can visualize exactly what is happening behind the scenes. Assume you have declared the variables shown in Table 4.7.1.

In Example 1, we requested the compiler to declare a variable in memory that we are calling age. The memory will be the size of a short integer, or two bytes. Because we did not initialize the contents of the variable age, its value is currently unknown or undefined.

Imagine Figure 4.7.1 illustrates a contiguous section of the computer's RAM. Assuming each box represents one byte, we know the variable age would require two adjacent memory locations to hold its contents, or value.

The type of this variable has been declared a short int; thus, the size is two bytes. At any given time, the variable age can hold one value. The range of that value is 32,768 to 32,767. Should we put a value that is too large into this variable, we will have a definite problem. The contents of the variable would depend on how much out of range the value is. Regardless, the resulting value is going to be incorrect. We will indeed be in for a very long day as we try to figure out what just happened.

Example Number

Variable and Constant Declarations

1

shortintage;

2

char grade = ‘A’;

3

float gpa(0.0);

4

const float PI = 3.14F;

Table 4.7.1 Declaration examples

images

Figure 4.7.1 Memory diagram

images

Figure 4.7.2 Memory diagram

The process just described is somewhat similar to making a reservation in a fancy restaurant for dinner this Friday night. You call ahead and tell the restaurant you will need a table for 4 people at 7:00 p.m. However, when you arrive at the restaurant with your group of 16 people (not the 4 you reserved), you may find that the establishment is filled to capacity and a problem clearly exists!

In the second example in Table 4.7.1, you requested the compiler to find you a single byte of memory and associate the variable name grade with that particular section of memory. In this case, we did the right thing and initialized the value to a known state. Remember, because of the char data type we asked for, we can only store one character at a time in the variable we call grade. Attempting to put more than one value in this location would be an error. Your memory might now look somewhat like that in Figure 4.7.2.

images

Figure 4.7.3 Memory diagram

The third example in Table 4.7.1 requests room in memory to hold a value associated with a variable called gpa that is four bytes long. Similar to what we had done in Example 2, we again initialized the variable; however, this time we used the C++ parentheses as the initialization syntax.

For the last example in Table 4.7.1 we created a constant called PI. As required when declaring constants, we initialized it to a known state. Figure 4.7.3 is the final illustration showing one possible interpretation of how our memory might look with some imagination on your part.

4.8 Variable Declarations in Pseudocode

One thing that may seem a little confusing is that variable declarations are not represented in pseudocode. Pseudocode is reserved for executable statements, and variable declarations are not executable. While the declarations serve an important purpose, they don't actually do anything. This is also why we don't see any #includes or constant declarations in our pseudocode. Also, data types and #includes are C++ specific. Remember, pseudocode should be programming-language independent.

4.9 Problem Solving Applied

Problem statement: Develop the pseudocode solution to calculate the weekly developmental billing report for local radio station WJJQ's biggest client, a car dealership. WJJQ has been in operation for over 30 years, and recently Alexis Blough has taken over as general manager. The station has a format of contemporary rock and country music.

WJJQ uses the following rate structure for the car dealership account:

Production $100.00 per hr
Pre-production $60.00 per hr
Producer's fee $40.00 per hr
   
   

The car dealership will be billed for the following time during the past week:

Production 1.5 hours
Pre-production 2 hours
Producer's fee 3 hours

Alexis needs you to display the amount due for each respective activity and to display the overall total owed by the car dealership.

Requirement Specification:

Input(s):

Input Type

Data

Source

Decimal

ProductionHours

Keyboard

Decimal

PreProductionHours

Keyboard

Decimal

ProducersHours

Keyboard

Output(s):

Output Type

Data

Destination

Decimal

ProductionCost

Screen

Decimal

PreProductionCost

Screen

Decimal

ProducersCost

Screen

Decimal

TotalCost

Screen

Constants:

Type

Data

Value

Decimal

PRODUCTION_RATE

100.00

Decimal

PRE_PRODUCTION_RATE

60.00

Decimal

PRODUCERS_RATE

40.00

Design:

Required Formulas:

images

Pseudocode:

images

images

Testing and Verification:

Desk Checking:

images

4.10 C—The Differences

There are only a few differences between C and C++ in the topics discussed in this chapter. First, there isn't a Boolean (bool) data type and therefore no predefined true and false values in C. Many advanced C programmers make their own data type that simulates a Boolean data type, but the bool data type does not exist. Don't be disheartened; by the end of this text you will be able to create your own Boolean-like data type in C if needed.

Another difference is that you can't use the parentheses form of initialization (i.e.,intx(1);) in C. That, too, was one of the enhancements made by the developers of C++, and we will see its use again later in the text.

In older versions of C, unlike in C++, you must declare variables as the first statements in a block of code. Therefore, the variable declarations must come directly after an opening curly brace.

The current C standard allows a programmer to use const to create constants. However, legacy C programs written prior to the current standard must use #define to create constants.

4.11 SUMMARY

We began our discussion in this chapter with a quick look at literals and found that, with the exception of escape sequences, they are interpreted as they are presented. We also discussed the three types of literals: numeric, character, and string. We then examined escape sequences and how they offer us the ability to use a special notation to represent a specific character or perform some predetermined action.

The next discussion centered on the use of variables and how they are used to store data in memory. The concept of a data type was also introduced along with a number of the fundamental data types available to us. We also stressed that a data type is the central piece to any variable declaration because it indicates the type of data stored in the variable, the amount of memory the variable uses, and the specific operations that can be performed on the variable. Remember, when creating your variable names, you must follow the rules outlined. Time was also spent stressing the importance of initializing your variables.

The ASCII chart was introduced to help facilitate your understanding of how character data is represented in memory. An ASCII chart is included in Appendix A.

Next, we began our discussion of constants, and the important role they play within programming. As we learned, constants are unchangeable values used to enhance the readability and maintainability of your program. Finally, we concluded the chapter with an overview of the #define statement, which is a preprocessor directive sometimes used to create constants. However, because of the added benefits of the const reserved word, it is best to not use a #define to declare constants unless programming in C.

As done in previous chapters, we made you aware of the problems our students encounter when creating and using variables, constants, and literals. Many of the concepts presented in this chapter are crucial to your understanding of the language and will become the building blocks for much of the material that follows. As usual, make sure you feel pretty confident about the material presented. If you feel good about the information we just provided, you are ready to continue your journey.

4.12 Debugging Exercise

Find and correct the logic errors in the following pseudocode examples. You will need to desk-check these problems carefully to locate the errors.

1.  Problem: Your brother has decided to give all of the employees in his small company a 6% raise. A novice programmer, he wants to create a program that calculates the new wages. He has created the following pseudocode and has asked you to look it over for errors.

           images

2.  Problem: Last term your grade in math was lower than you, or your parents, expected. You want to create a program to check your professor's calculations. The course syllabus states that all of the assignments were worth 30% of the total grade, the three tests were worth 15% each, and the final exam was worth 25%. Look over the following pseudocode for correctness.

           images

      images

4.13 Programming Exercises

1.  In Section 4.9, Problem Solving Applied, we provided a solution for WJJQ's billing program. Based on that pseudocode solution, please declare the variables and constants needed.

2.  Just to keep you in practice using your development environment, type in the following program, then compile and run it. The output will make you smile.

     images

3.  Write a C++ program to calculate how old you are in days. Declare an integer variable and initialize it to your age. Also, declare a constant that represents the number of days in a year. Make sure you write your pseudocode solution before attempting to write your code. HINT: Here is an example of an assignment statement that might be similar to what you will need to perform the actual calculation: gross = hours * RATE;. Of course you will also need to use cout.

4.14 Team Programming Exercise

Well, your old pen pal continues to need your assistance. In the last chapter you helped her with the pseudocode solution to convert a given distance in kilometers to miles. With some additional time and your help, she was able to construct the expanded, although rough, pseudocode solution. Now, however, she needs your assistance to help her in identifying the different C++ variables and constants needed in this program.

Based on the following solution, your job is to declare all the variables and constants needed. Remember to initialize your variables as previously discussed. Here is some additional background information related to the program that you may find helpful.

a.  A decimeter (dm) is 0.1 meter.

b.  A kilometer is 1000 meters, or meters per kilometer (MPK) is 1000.

c.  One kilometer is less than one mile.

d.  KPM stands for kilometers per mile.

e.  There are approximately 1.6093 kilometers per mile (KPM).

f.  Your friend is thinking of changing her major from physics to software engineering.

     images

4.15 Answers to Chapter Exercises

Section 4.1

1.  legal; numeric

2.  illegal; you can't enclose more than one character in single quotation marks.

3.  1. legal; string

4.  2. legal; string

5.  legal; character

6.  illegal; you must enclose the character in either single or double quotation marks.

7.  illegal; you must enclose the group of characters in double quotation marks.

Section 4.2

1.  “This is a” “backslash” \, this is a forward slash /. The way to remember is to stand up and turn to your right. If you lean “back”, you become a backslash; if you lean “forward” you become a forward slash. This is Randy’s surefire method!”

Section 4.3

1.  

a. 0 to 255

b. 0 to 65,535

c. 0 to 65,535

d. 0 to 4,294,967,295

e. 0 to 18,446,744,073,709,551,615

f. −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

g. 0 to 4,294,967,295

h. −32,768 to 32,767

2.  

a. legal

b. illegal; dash (-) is an illegal character

c. legal

d. legal in C++; however, use with caution, as it may be a reserved word in some languages

e. illegal; ampersand (&) is an illegal character

f. legal

g. illegal; can't start with a digit

h. legal

i. illegal; spaces are illegal characters

j. illegal; pound sign (#) is an illegal character

k. illegal; reserved word

3.   

a. Either replace the comma with a semicolon or remove the second int.

b. You can't use b to initialize a because b hasn't been declared yet.

c. The literal 3.5 is an invalid value for an integer.

d. Replace the double quotation marks with single quotation marks.

e. This is legal, although you are probably not going to get the results you had anticipated. Since the 1 is a numeric literal, it will be used as the ASCII value 1 instead of the character ‘1’. images

f. Legal, but not ideal as variable names.

g. You cannot store more than one character in a char variable.

Section 4.4

1.  Hello World! = 72 101 108 108 111 32 87 111 114 108 100 33

2.  C++ Rocks!

Section 4.5

1.  There is no data type; therefore, it defaults to an int, and the literal 3.14 is not valid for an int.

2.  All constants must be initialized to a value.

3.  You cannot store more than one character in a char constant.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.123.34