Chapter 2 Introduction to C++
2.1 The Parts of a C++ Program
Concept:
C++ programs have parts and components that serve specific purposes.
- Every C++ program has a structure, though the parts are not always in the same location. Learning these parts is the first step to learning C++.
🗊 Program 2-1
The output of the program is shown below. This is what appears on the screen when the program runs.
💻 Program Output
Line 1:
// A simple C++ program- The
//signifies a comment. - The compiler ignores all text from the
//to the end of the line. - Comments are crucial for explaining complex code to human readers.
- The
Line 2:
#include <iostream>- Lines starting with
#are preprocessor directives. - The preprocessor runs before the compiler, setting up the source code.
- The
#includedirective includes a header file, in this case,iostream. - The
<iostream>file is required for screen output (cout) and keyboard input.
- Lines starting with
Line 3:
using namespace std;- C++ uses namespaces to organize the names of program entities like variables and functions.
- This statement declares that the program will use entities from the
std(standard) namespace. - Access to the
stdnamespace is necessary because the names used fromiostreamare part of it.
Line 5:
int main()- This marks the beginning of a function named
main. - A function is a named group of programming statements.
- The
()aftermainindicates it is a function. intsignifies that the function returns an integer value to the operating system upon completion.- Every C++ program must have a
mainfunction, as it is the program’s starting point.
- This marks the beginning of a function named
Note:
C++ is a case-sensitive language. That means it regards uppercase letters as being entirely different characters than their lowercase counterparts. In C++, the name of the function main must be written in all lowercase letters. C++ doesn’t see “Main” the same as “main,” or “INT” the same as “int.” This is true for all the C++ key words.
- Line 6:
{- This is a left or opening brace.
- It marks the beginning of the
mainfunction’s body. All statements within the function are enclosed in braces.
Warning!
Make sure you have a closing brace for every opening brace in your program!
- Line 7:
cout << "Programming is great fun!";- This statement displays a message on the screen.
- The text inside the double quotation marks is called a string literal.
- A semicolon
;marks the end of a complete C++ statement.
Note:
This is the only line in the program that causes anything to be printed on the screen. The other lines, like #include <iostream> and int main(), are necessary for the framework of your program, but they do not cause any screen output. Remember, a program is a set of instructions for the computer. If something is to be displayed on the screen, you must use a programming statement for that purpose.
Line 8:
return 0;- This sends the integer value 0 back to the operating system.
- A return value of 0 typically indicates that the program executed successfully.
Line 9:
}- This is a closing brace.
- It marks the end of the
mainfunction.
| Character | Name | Description |
|---|---|---|
// |
Double slash | Marks the beginning of a comment. |
# |
Pound sign | Marks the beginning of a preprocessor directive. |
< > |
Opening and closing brackets | Enclose a filename when used with the #include directive. |
( ) |
Opening and closing parentheses | Used in naming a function, as in int main(). |
{ } |
Opening and closing braces | Enclose a group of statements, such as the contents of a function. |
" " |
Opening and closing quotation marks | Enclose a string of characters, such as a message that is to be printed on the screen. |
; |
Semicolon | Marks the end of a complete programming statement. |
Checkpoint
2.1 The following C++ program will not compile because the lines have been mixed up.
int main() } return 0; #include <iostream> cout << "In 1492 Columbus sailed the ocean blue."; { using namespace std;When the lines are properly arranged, the program should display the following on the screen:
In 1492 Columbus sailed the ocean blue.Rearrange the lines in the correct order. Test the program by entering it on the computer, compiling it, and running it.
2.2 The cout Object
Concept:
Use the cout object to display information on the computer’s screen.
- Console output refers to the plain text a program displays, typically in a dedicated window.
- In C++, the
coutobject is used to produce console output. It is a stream object, working with streams of data. - The
<<operator is the stream insertion operator. It sends data tocoutto be displayed on the screen. - The operator is written as two less-than signs (
<<) and must point towardcout.
Using cout
🗊 Program 2-2
💻 Program Output
🗊 Program 2-3
💻 Program Output
- The
coutobject displays information in a continuous stream, without automatically adding spaces or new lines.
🗊 Program 2-4
💻 Program Output
- To start a new line, you can use one of two methods:
endlStream Manipulator: Whencoutencountersendl, it moves the cursor to the beginning of the next line.
🗊 Program 2-5
💻 Program Output
Note:
The last character in endl is the lowercase letter L, not the number one.
- Escape Sequence: An escape sequence starts with a backslash (
\) and is embedded inside a string to control output.- The newline escape sequence is
\n. It tellscoutto advance the cursor to the next line.
- The newline escape sequence is
🗊 Program 2-6
💻 Program Output
- Common mistakes include using a forward slash (
/ninstead of\n) or placing\noutside the quotation marks.
| Escape Sequence | Name | Description |
|---|---|---|
\n |
Newline | Causes the cursor to go to the next line for subsequent printing. |
\t |
Horizontal tab | Causes the cursor to skip over to the next tab stop. |
\a |
Alarm | Causes the computer to beep. |
\b |
Backspace | Causes the cursor to back up, or move left one position. |
\r |
Return | Causes the cursor to go to the beginning of the current line, not the next line. |
\\ |
Backslash | Causes a backslash to be printed. |
\' |
Single quote | Causes a single quotation mark to be printed. |
\" |
Double quote | Causes a double quotation mark to be printed. |
Warning!
When using escape sequences, do not put a space between the backslash and the control character.
- An escape sequence is typed as two characters but is stored in memory as a single character.
2.3 The #include Directive
Concept:
The #include directive causes the contents of another file to be inserted into the program.
- The
iostreamheader file must be included in any program that uses thecoutobject becausecoutis part of the input-output stream library, not the core C++ language. - Preprocessor directives are commands to the preprocessor, which runs before the compiler.
- The
#includedirective automatically inserts the necessary setup information from a header file, saving the programmer from typing it manually. - The compiler sees the inserted code, not the
#includedirective itself.
Warning!
Do not put semicolons at the end of processor directives. Because preprocessor directives are not C++ statements, they do not require semicolons. In many cases, an error will result from a preprocessor directive terminated with a semicolon.
Checkpoint
2.2 The following C++ program will not compile because the lines have been mixed up.
cout << "Success\n"; cout << " Success\n\n"; int main() cout << "Success"; } using namespace std; #include <iostream> cout << "Success\n"; { return 0;When the lines are properly arranged, the program should display the following on the screen:
Success Success Success SuccessRearrange the lines in the correct order. Test the program by entering it on the computer, compiling it, and running it.
2.3 Study the following program and show what it will print on the screen:
#include <iostream> using namespace std; int main() { cout << "The works of Wolfgang\ninclude the following"; cout << "\nThe Turkish March" << endl; cout << "and Symphony No. 40 "; cout << "in G minor." << endl; return 0; }2.4 Write a program that will display your name on the first line, your street address on the second line, your city, state, and ZIP code on the third line, and your telephone number on the fourth line. Place a comment with today’s date at the top of the program. Test your program by compiling and running it.
2.4 Variables, Literals, and Assignment Statements
Concept:
Variables represent storage locations in the computer’s memory. Literals are constant values that are assigned to variables.
- Variables allow programs to store and work with data in the computer’s memory (RAM).
- Programmers must determine the number and types of variables a program needs.
🗊 Program 2-7
💻 Program Output
- Variable Definition:
int number;- This statement defines a variable.
- It tells the compiler the variable’s name (
number) and the type of data it holds (intfor integer). - Variable definitions end with a semicolon.
Variable Definitions
Note:
You must have a definition for every variable you intend to use in a program. In C++, variable definitions can appear at any point in the program. Later in this chapter, and throughout the book, you will learn the best places to define variables.
- Assignment Statement:
number = 5;- The equal sign (
=) is the assignment operator. - It copies the value on its right into the variable on its left.
- The equal sign (
Note:
This line does not print anything on the computer’s screen. It runs silently behind the scenes, storing a value in RAM.
- When a variable name is sent to
coutwithout quotes, its value is printed. - If the variable name is enclosed in quotes (
"number"), it is treated as a string literal and the name itself is printed.
🗊 Program 2-8
💻 Program Output
- Numbers can be represented as numeric types (for math) or as strings (for display). You cannot perform math on a string representation of a number (e.g.,
"5").
Literals
- A literal is a piece of data written directly into the program’s code, like
100or"Welcome to my program.". - Literals are often used to assign values to variables or for display.
🗊 Program 2-9
💻 Program Output
| Literal | Type of Literal |
|---|---|
20 |
Integer literal |
"Today we sold" |
String literal |
"bushels of apples.\n" |
String literal |
0 |
Integer literal |
Note:
Literals are also called constants.
Checkpoint
2.5 Examine the following program:
#include <iostream> using namespace std; int main() { int little; int big; little = 2; big = 2000; cout << "The little number is " << little << endl; cout << "The big number is " << big << endl; return 0; }List all the variables and literals that appear in the program.
2.6 What will the following program display on the screen?
#include <iostream> using namespace std; int main() { int number; number = 712; cout << "The value is " << "number" << endl; return 0; }
2.5 Identifiers
Concept:
Choose variable names that indicate what the variables are used for.
- An identifier is a programmer-defined name for a program element, such as a variable.
- You cannot use C++ key words as identifiers. Key words are reserved and have specific meanings.
alignas |
const |
for |
private |
throw |
alignof |
constexpr |
friend |
protected |
true |
and |
const_cast |
goto |
public |
try |
and_eq |
continue |
if |
register |
typedef |
asm |
decltype |
inline |
reinterpret_cast |
typeid |
auto |
default |
int |
return |
typename |
bitand |
delete |
long |
short |
union |
bitor |
do |
mutable |
signed |
unsigned |
bool |
double |
namespace |
sizeof |
using |
break |
dynamic_cast |
new |
static |
virtual |
case |
else |
noexcept |
static_assert |
void |
catch |
enum |
not |
static_cast |
volatile |
char |
explicit |
not_eq |
struct |
wchar_t |
char16_t |
export |
nullptr |
switch |
while |
char32_t |
extern |
operator |
template |
xor |
class |
false |
or |
this |
xor_eq |
compl |
float |
or_eq |
thread_local |
- Choose meaningful variable names to make code self-documenting and easier to understand (e.g.,
itemsOrderedinstead ofx). - Common naming conventions include CamelCase (
itemsOrdered) or using underscores (items_ordered).
Legal Identifiers
- The first character must be a letter (a-z, A-Z) or an underscore (
_). - After the first character, you can use letters, digits (0-9), or underscores.
- Uppercase and lowercase characters are distinct (e.g.,
ItemsOrderedis different fromitemsordered).
| Variable Name | Legal or Illegal? |
|---|---|
dayOfWeek |
Legal. |
3dGraph |
Illegal. Variable names cannot begin with a digit. |
_employee_num |
Legal. |
June1997 |
Legal. |
Mixture#3 |
Illegal. Variable names may only use letters, digits, or underscores. |
2.6 Integer Data Types
Concept:
There are many different types of data. Variables are classified according to their data type, which determines the kind of information that may be stored in them. Integer variables can only hold whole numbers.
- A variable’s data type determines the kind of information it can hold.
- Data types can be broadly categorized as numeric (integer, floating-point) and character.
- When choosing a numeric data type, consider:
- Largest and smallest possible values.
- Memory usage.
- Whether it needs to store negative numbers (signed vs. unsigned).
- Required decimal precision.
| Data Type | Typical Size | Typical Range |
|---|---|---|
short int |
2 bytes | -32,768 to +32,767 |
unsigned short int |
2 bytes | 0 to +65,535 |
int |
4 bytes | -2,147,483,648 to +2,147,483,647 |
unsigned int |
4 bytes | 0 to 4,294,967,295 |
long int |
4 bytes | -2,147,483,648 to +2,147,483,647 |
unsigned long int |
4 bytes | 0 to 4,294,967,295 |
long long int |
8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
unsigned long long int |
8 bytes | 0 to 18,446,744,073,709,551,615 |
Note:
The data type sizes and ranges shown in Table 2-6 are typical on many systems. Depending on your operating system, the sizes and ranges may be different.
- Most integer data types can be abbreviated (e.g.,
short intasshort,unsigned intasunsigned). - Unsigned data types can only store non-negative values.
- C++ has size guarantees:
long longis at least 64 bits,longis at least as big asint, andintis at least as big asshort.
Note:
The long long int and the unsigned long long int data types were introduced in C++ 11.
🗊 Program 2-10
#include <iostream>
using namespace std;
int main()
{
int checking;
unsigned int miles;
long days;
checking = -20;
miles = 4276;
diameter = 100000;
cout << "We have made a long journey of " << miles;
cout << " miles.\n";
cout << "Our checking account balance is " << checking;
cout << "\nThe galaxy is about " << diameter;
cout << " light years in diameter.\n";
return 0;
}💻 Program Output
- You can define multiple variables of the same type in a single statement by separating them with commas.
🗊 Program 2-11
💻 Program Output
Integer and Long Integer Literals
- Numeric literals without a decimal point are typically treated as type
int. - To force a literal to be a
long, append the letterL(e.g.,32L). - To force a literal to be a
long long, appendLL(e.g.,32LL).
Tip:
When writing long integer literals or long long integer literals, you can use either an uppercase or a lowercase L. Because the lowercase l looks like the number 1, you should always use the uppercase L.
If You Plan to Continue in Computer Science: Hexadecimal and Octal Literals
- Programmers sometimes use hexadecimal (base 16) or octal (base 8) numbering systems.
- In C++, hexadecimal literals are prefixed with
0x(e.g.,0xF4). - Octal literals are prefixed with
0(e.g.,031).
Note:
You will not be writing programs for some time that require this type of manipulation. It is important, however, that you understand this material. Good programmers should develop the skills for reading other people’s source code. You may find yourself reading programs that use items like long integer, hexadecimal, or octal literals.
Checkpoint
2.7 Which of the following are illegal variable names, and why?
X 99bottles july97 theSalesFigureForFiscalYear98 r&d grade_report2.8 Is the variable name
Salesthe same assales? Why or why not?2.9 Refer to the data types listed in Table 2-6 for these questions.
If a variable needs to hold numbers in the range 32 to 6,000, what data type would be best?
If a variable needs to hold numbers in the range 240,000 to 140,000, what data type would be best?
Which of the following literals uses more memory?
20or20L
2.10 On any computer, which data type uses more memory, an integer or an unsigned integer?
2.7 The char Data Type
- The
chardata type is used to store a single character. - Character literals are enclosed in single quotation marks (e.g.,
'g'). - You cannot assign a string (even one with a single character like
"g") to acharvariable.
🗊 Program 2-12
💻 Program Output
- The
chartype is an integer data type, typically 1 byte, because characters are stored internally as numeric codes. - The most common character encoding is ASCII (American Standard Code for Information Interchange).
- For example, the character ‘A’ is stored as the ASCII code 65.
🗊 Program 2-13
💻 Program Output
The Difference between String Literals and Character Literals
- Strings are sequences of characters stored in consecutive memory locations.
- String literals stored in memory are always appended with a null terminator (
\0), which marks the end of the string. - The null terminator is ASCII code 0, not to be confused with the character
'0', which is ASCII code 48. - Due to the null terminator, a string like
"Sebastian"(9 characters) occupies 10 bytes of memory.
Note:
C++ automatically places the null terminator at the end of string literals.
A character literal like
'A'is stored as a single byte (its ASCII code).A string literal like
"A"is stored as two bytes: the ASCII code for ‘A’ and the null terminator.Escape sequences like
\nare represented by two characters in code but are stored internally as a single character.
🗊 Program 2-14
💻 Program Output
- Review of Key Points:
- Characters are represented internally by numeric codes (usually ASCII).
charvariables typically occupy one byte.- Strings are consecutive sequences of characters.
- String literals are terminated by a null character (
\0) in memory. - Character literals use single quotes (
'...'), while string literals use double quotes ("...").
2.8 The C++ string Class
Concept:
Standard C++ provides a special data type for storing and working with strings.
- Because
charvariables hold only one character, C++ provides thestringclass to work with variables that can hold entire strings.
Using the string Class
- Step 1: Include the
<string>header file:#include <string>. - Step 2: Define a
stringobject (a variable of typestring):string movieTitle;. - Step 3: Assign a value using the assignment operator:
movieTitle = "Wheels of Fury";. - Step 4: Use the
stringobject withcoutjust like any other variable.
🗊 Program 2-15
💻 Program Output
Checkpoint
2.11 What are the ASCII codes for the following characters? (Refer to Appendix A.)
C F W2.12 Which of the following is a character literal?
'B' "B"2.13 Assuming the
chardata type uses 1 byte of memory, how many bytes do the following literals use?'Q' "Q" "Sales" '\n'2.14 Write a program that has the following character variables:
first,middle, andlast. Store your initials in these variables then display them on the screen.2.15 What is wrong with the following program statement?
char letter = "Z";2.16 What header file must you include in order to use
stringobjects?2.17 Write a program that stores your name, address, and phone number in three separate
stringobjects. Display the contents of thestringobjects on the screen.
2.9 Floating-Point Data Types
Concept:
Floating-point data types are used to define variables that can hold real numbers.
- Floating-point numbers are values that can have fractional parts.
- They are stored internally in a format similar to scientific notation (e.g., 47,281.97 is 4.728197 × 104).
- Computers often use E notation, where 4.728197 × 104 is written as
4.728197E4.
| Decimal Notation | Scientific Notation | E Notation |
|---|---|---|
| 247.91 | 2.4791 × 102 | 2.4791E2 |
| 0.00072 | 7.2 × 10-4 | 7.2E–4 |
| 2,900,000 | 2.9 × 106 | 2.9E6 |
- C++ offers three floating-point data types:
float: Single precision.double: Double precision (usually twice the size offloat).long double: Intended to be larger than or equal todouble.
- Size guarantees: A
doubleis at least as big as afloat, and along doubleis at least as big as adouble.
| Data Type | Key Word | Description |
|---|---|---|
| Single precision | float |
4 bytes. Numbers between ±3.4E–38 and ±3.4E38 |
| Double precision | double |
8 bytes. Numbers between ±1.7E–308 and ±1.7E308 |
| Long double precision | long double |
8 bytes*. Numbers between ±1.7E–308 and ±1.7E308 |
*Some compilers use 10 bytes for long doubles. This allows a range of ±3.4E–4932 to ±1.1E4832. |
||
Floating-Point Literals
- Floating-point literals can be written in E notation or standard decimal notation.
- By default, floating-point literals are treated as
doubles. - You can force a literal to be a
floatby appendingForf(e.g.,1.2F). - You can force a literal to be a
long doubleby appendingLorl(e.g.,1034.56L).
🗊 Program 2-16
💻 Program Output
Note:
Because floating-point literals are normally stored in memory as doubles, most compilers issue a warning message when you assign a floating-point literal to a float variable. For example, assuming num is a float, the following statement might cause the compiler to generate a warning message:
num = 14.725;You can suppress the warning message by appending the f suffix to the floating-point literal, as shown below:
num = 14.725f;Assigning Floating-Point Values to Integer Variables
- When a floating-point value is assigned to an integer variable, the fractional part is discarded (truncated).
- This is truncation, not rounding. For example, assigning 7.9 to an
intvariable will result in 7 being stored.
Note:
When a floating-point value is truncated, it is not rounded. Assigning the value 7.9 to an int variable will result in the value 7 being stored in the variable.
Warning!
Floating-point variables can hold a much larger range of values than integer variables can. If a floating-point value is being stored in an integer variable, and the whole part of the value (the part before the decimal point) is too large for the integer variable, an invalid value will be stored in the integer variable.
2.10 The bool Data Type
Concept:
Boolean variables are set to either true or false.
- Expressions that result in a
trueorfalsevalue are called Boolean expressions. - The
booldata type creates variables that can holdtrueorfalsevalues. - Internally,
trueis represented by the integer 1, andfalseis represented by 0.
2.11 Determining the Size of a Data Type
Concept:
The sizeof operator may be used to determine the size of a data type on any system.
- The size of data types can vary between different computer systems.
- The
sizeofoperator reports the number of bytes of memory used by any data type or variable. - You place the data type or variable name inside parentheses following the operator (e.g.,
sizeof(int)).
🗊 Program 2-18
#include <iostream>
using namespace std;
int main()
{
long double apple;
cout << "The size of an integer is " << sizeof(int);
cout << " bytes.\n";
cout << "The size of a long integer is " << sizeof(long);
cout << " bytes.\n";
cout << "An apple can be eaten in " << sizeof(apple);
cout << " bytes!\n";
return 0;
}💻 Program Output
Checkpoint
2.18 Yes or No: Is there an unsigned floating-point data type? If so, what is it?
2.19 How would the following number in scientific notation be represented in E notation?
6.31\, \times \, 10^{17}
2.20 Write a program that defines an integer variable named
ageand afloatvariable namedweight. Store your age and weight, as literals, in the variables. The program should display these values on the screen in a manner similar to the following:My age is 26 and my weight is 180 pounds.(Feel free to lie to the computer about your age and your weight—it’ll never know!)
2.12 More about Variable Assignments and Initialization
Concept:
An assignment operation assigns, or copies, a value into a variable. When a value is assigned to a variable as part of the variable’s definition, it is called an initialization.
- The
=symbol is the assignment operator, which copies a value into a variable. - The data that operators work on are called operands.
- The operand on the left side of
=must be an lvalue (a memory location that can be modified, like a variable). - The operand on the right side is an rvalue (an expression that has a value).
- Initialization is assigning a value to a variable as part of its definition.
🗊 Program 2-19
💻 Program Output
Declaring Variables with the auto Key Word
- Introduced in C++ 11, the
autokey word can be used to define a variable. - It tells the compiler to automatically determine the variable’s data type from its initialization value.
- Example:
auto amount = 100;definesamountas anint.auto interestRate = 12.0;definesinterestRateas adouble.
Alternative Forms of Variable Initialization
- Besides using the assignment operator (
int value = 5;), there are other ways to initialize variables. - Parenthesis Notation:
int value(5); - Brace Notation (C++ 11):
int value {5};- Brace notation is stricter and will produce a compiler error if you try to initialize a variable with a value of a different type that would cause data loss (e.g.,
int value {4.9};).
- Brace notation is stricter and will produce a compiler error if you try to initialize a variable with a value of a different type that would cause data loss (e.g.,
2.13 Scope
Concept:
A variable’s scope is the part of the program that has access to the variable.
- A variable’s scope is the part of the program where it may be used.
- Rule of Scope: A variable cannot be used in the program before its definition. The compiler reads code from top to bottom.
2.14 Arithmetic Operators
Concept:
There are many operators for manipulating numeric values and performing arithmetic operations.
- Operators are categorized by the number of operands they require:
- Unary: One operand (e.g., the negation operator in
-5). - Binary: Two operands (e.g., addition, assignment).
- Ternary: Three operands (C++ has one, covered later).
- Unary: One operand (e.g., the negation operator in
Assignment Statements and Simple Math Expressions
| Operator | Meaning | Type | Example |
|---|---|---|---|
+ |
Addition | Binary | total = cost + tax; |
- |
Subtraction | Binary | cost = total - tax; |
* |
Multiplication | Binary | tax = cost * rate; |
/ |
Division | Binary | salePrice = original / 2; |
% |
Modulus | Binary | remainder = value % 3; |
- The modulus operator (
%) works only with integers and returns the remainder of a division.
🗊 Program 2-21
#include <iostream>
using namespace std;
int main()
{
double regularWages,
basePayRate = 18.25,
regularHours = 40.0,
overtimeWages,
overtimePayRate = 27.78,
overtimeHours = 10,
totalWages;
regularWages = basePayRate * regularHours;
overtimeWages = overtimePayRate * overtimeHours;
totalWages = regularWages + overtimeWages;
cout << "Wages for this week are $" << totalWages << endl;
return 0;
}💻 Program Output
Integer Division
- When both operands of the division operator (
/) are integers, the result is also an integer. Any fractional part is truncated (discarded). - For example,
5 / 2results in2. - To perform a floating-point division, at least one of the operands must be a floating-point type (e.g.,
5.0 / 2).
In the Spotlight:
Calculating Percentages and Discounts
Determining percentages is a common calculation in computer programming. Although the % symbol is used in general mathematics to indicate a percentage, most programming languages (including C++) do not use the % symbol for this purpose. In a program, you have to convert a percentage to a floating-point number, just as you would if you were using a calculator. For example, 50 percent would be written as 0.5, and 2 percent would be written as 0.02.
Let’s look at an example. Suppose you earn $6,000 per month and you are allowed to contribute a portion of your gross monthly pay to a retirement plan. You want to determine the amount of your pay that will go into the plan if you contribute 5 percent, 7 percent, or 10 percent of your gross wages. To make this determination, you write the program shown in Program 2-22.
🗊 Program 2-22
#include <iostream>
using namespace std;
int main()
{
double monthlyPay = 6000.0, contribution;
contribution = monthlyPay * 0.05;
cout << "5 percent is $" << contribution
<< " per month.\n";
contribution = monthlyPay * 0.07;
cout << "7 percent is $" << contribution
<< " per month.\n";
contribution = monthlyPay * 0.1;
cout << "10 percent is $" << contribution
<< " per month.\n";
return 0;
}💻 Program Output
Line 11 defines two variables: monthlyPay and contribution. The monthlyPay variable, which is initialized with the value 6000.0, holds the amount of your monthly pay. The contribution variable will hold the amount of a contribution to the retirement plan.
The statements in lines 14 through 16 calculate and display 5 percent of the monthly pay. The calculation is done in line 14, where the monthlyPay variable is multiplied by 0.05. The result is assigned to the contribution variable, which is then displayed in line 15.
Similar steps are taken in lines 18 through 21, which calculate and display 7 percent of the monthly pay, and lines 24 through 26, which calculate and display 10 percent of the monthly pay.
Calculating a Percentage Discount
Another common calculation is determining a percentage discount. For example, suppose a retail business sells an item that is regularly priced at $59.95, and is planning to have a sale where the item’s price will be reduced by 20 percent. You have been asked to write a program to calculate the sale price of the item.
To determine the sale price, you perform two calculations:
First, you get the amount of the discount, which is 20 percent of the item’s regular price.
Second, you subtract the discount amount from the item’s regular price. This gives you the sale price.
Program 2-23 shows how this is done in C++.
🗊 Program 2-23
#include <iostream>
using namespace std;
int main()
{
double regularPrice = 59.95, discount, salePrice;
discount = regularPrice * 0.2;
salePrice = regularPrice - discount;
cout << "Regular price: $" << regularPrice << endl;
cout << "Discount amount: $" << discount << endl;
cout << "Sale price: $" << salePrice << endl;
return 0;
}💻 Program Output
Line 11 defines three variables. The regularPrice variable holds the item’s regular price, and is initialized with the value 59.95. The discount variable will hold the amount of the discount once it is calculated. The salePrice variable will hold the item’s sale price.
Line 14 calculates the amount of the 20 percent discount by multiplying regularPrice by 0.2. The result is stored in the discount variable. Line 18 calculates the sale price by subtracting discount from regularPrice. The result is stored in the salePrice variable. The cout statements in lines 21 through 23 display the item’s regular price, the amount of the discount, and the sale price.
In the Spotlight:
Using the Modulus Operator and Integer Division
The modulus operator (%) is surprisingly useful. For example, suppose you need to extract the rightmost digit of a number. If you divide the number by 10, the remainder will be the rightmost digit. For instance, 123 ÷ 10 = 12 with a remainder of 3. In a computer program, you would use the modulus operator to perform this operation. Recall that the modulus operator divides an integer by another integer, and gives the remainder. This is demonstrated in Program 2-24. The program extracts the rightmost digit of the number 12345.
🗊 Program 2-24
💻 Program Output
Interestingly, the expression number % 100 will give you the rightmost two digits in number, the expression number % 1000 will give you the rightmost three digits in number, and so on.
The modulus operator (%) is useful in many other situations. For example, Program 2-25 converts 125 seconds to an equivalent number of minutes, and seconds.
🗊 Program 2-25
#include <iostream>
using namespace std;
int main()
{
int totalSeconds = 125;
int minutes, seconds;
minutes = totalSeconds / 60;
seconds = totalSeconds % 60;
cout << totalSeconds << " seconds is equivalent to:\n";
cout << "Minutes: " << minutes << endl;
cout << "Seconds: " << seconds << endl;
return 0;
}💻 Program Output
Let’s take a closer look at the code:
Line 8 defines an
intvariable namedtotalSeconds, initialized with the value 125.Line 11 declares the
intvariablesminutesandseconds.Line 14 calculates the number of minutes in the specified number of seconds. There are 60 seconds in a minute, so this statement divides
totalSecondsby 60. Notice we are performing integer division in this statement. BothtotalSecondsand the numeric literal 60 are integers, so the division operator will return an integer result. This is intentional because we want the number of minutes with no fractional part.Line 17 calculates the number of remaining seconds. There are 60 seconds in a minute, so this statement uses the
%operator to divide thetotalSecondsby 60, and get the remainder of the division. The result is the number of remaining seconds.Lines 20 through 22 display the number of minutes and seconds.
Checkpoint
2.21 Is the following assignment statement valid or invalid? If it is invalid, why?
72 = amount;2.22 How would you consolidate the following definitions into one statement?
int x = 7; int y = 16; int z = 28;2.23 What is wrong with the following program? How would you correct it?
#include <iostream> using namespace std; int main() { number = 62.7; double number; cout << number << endl; return 0; }2.24 Is the following an example of integer division or floating-point division? What value will be stored in
portion?portion = 70 / 3;
2.16 Named Constants
Concept:
Literals may be given names that symbolically represent them in a program.
- Using unnamed literal values (magic numbers) in code can cause two problems:
- It makes the code hard to understand (e.g., what does
0.069represent?). - If the value needs to be changed, you must find and update every occurrence of it throughout the program.
- It makes the code hard to understand (e.g., what does
- Named constants solve these problems. A named constant is a variable whose content is read-only and cannot be changed while the program runs.
- Define a named constant using the
constqualifier before the data type. - A value must be assigned upon definition.
- By convention, named constants are written in all uppercase letters to distinguish them from regular variables.
- Using named constants makes programs self-documenting and easy to update.
🗊 Program 2-28
💻 Program Output
Checkpoint
2.25 Write statements using the
constqualifier to create named constants for the following literal values:Literal Value Description 2.71828 Euler’s number (known in mathematics as e) 5.256E5 Number of minutes in a year 32.2 The gravitational acceleration constant (in ft/s2) 9.8 The gravitational acceleration constant (in m/s2) 1609 Number of meters in a mile
2.17 Programming Style
Concept:
Programming style refers to the way a programmer uses identifiers, spaces, tabs, blank lines, and punctuation characters to visually arrange a program’s source code. These are some, but not all, of the elements of programming style.
- While syntax rules are mandatory for the compiler, programming style is for human readability.
- The compiler processes code as a continuous stream, ignoring stylistic elements like indentation and spacing.
- A good programming style uses visual cues to make the code easier for people to read and understand.
🗊 Program 2-29
💻 Program Output
🗊 Program 2-30
💻 Program Output
- Elements of good style include:
- Indenting lines of code within braces (
{}). - Using blank lines to visually separate logical sections of code (e.g., variable definitions from executable statements).
- Breaking long statements across multiple lines for better readability.
- Indenting lines of code within braces (
Note:
Although you are free to develop your own style, you should adhere to common programming practices. By doing so, you will write programs that visually make sense to other programmers.
Review Questions and Exercises
Short Answer
How many operands does each of the following types of operators require?
______ Unary
______ Binary
______ Ternary
How may the
doublevariablestemp,weight, andagebe defined in one statement?How may the
intvariablesmonths,days, andyearsbe defined in one statement, withmonthsinitialized to 2 andyearsinitialized to 3?Write assignment statements that perform the following operations with the variables
a,b, andc:Adds 2 to
aand stores the result inb.Multiplies
bby 4 and stores the result ina.Divides
aby 3.14 and stores the result inb.Subtracts 8 from
band stores the result ina.Stores the value 27 in a.
Stores the character ‘K’ in
c.Stores the ASCII code for ‘B’ in
c.
Is the following comment written using single-line or multi-line comment symbols?
/* This program was written by M. A. Codewriter*/Is the following comment written using single-line or multi-line comment symbols?
Modify the following program so it prints two blank lines between each line of text.
#include <iostream> using namespace std; int main() { cout << "Two mandolins like creatures in the"; cout << "dark"; cout << "Creating the agony of ecstasy."; cout << " - George Barker"; return 0; }What will the following programs print on the screen?
-
#include <iostream> using namespace std; int main() { int freeze = 32, boil = 212; freeze = 0; boil = 100; cout << freeze << endl << boil << endl; return 0; } -
#include <iostream> using namespace std; int main() { int x = 0, y = 2; x = y * 4; cout << x << endl << y << endl; return 0; } -
#include <iostream> using namespace std; int main() { cout << "I am the incredible"; cout << "computing\nmachine"; cout << "\nand I will\namaze\n"; cout << "you."; return 0; } -
#include <iostream> using namespace std; int main() { cout << "Be careful\n"; cout << "This might/n be a trick "; cout << "question\n"; return 0; } -
#include <iostream> using namespace std; int main() { int a, x = 23; a = x % 2; cout << x << endl << a << endl; return 0; }
-
Multiple Choice
Every complete statement ends with a(n) ________.
period# symbolsemicolonending brace
Which of the following statements is correct?
#include (iostream)#include {iostream}#include <iostream>#include [iostream]All of the above
Every C++ program must have a ________.
coutstatementfunction
main#includestatementAll of the above
Preprocessor directives begin with ________.
#!<*None of the above
The following data
72 'A' "Hello World" 2.8712are all examples of ________.
variables
literals or constants
strings
none of the above
A group of statements, such as the contents of a function, is enclosed in ________.
braces
{}parentheses
()brackets
<>all of the above will do
Which of the following are not valid assignment statements? (Select all that apply.)
total = 9;72 = amount;profit = 129letter = 'W';
Which of the following are not valid
coutstatements? (Select all that apply.)cout << "Hello World";cout << "Have a nice day"\n;cout < value;cout << Programming is great fun;
Assume
w= 5,x= 4,y= 8, andz= 2. What value will be stored inresultin each of the following statements?result = x + y;result = z * 2;result = y / x;result = y - z;result = w % 2;
How would each of the following numbers be represented in E notation?
3.287×106-978.65×10127.65491×10-3-58710.23×10-4
The negation operator is ________.
unary
binary
ternary
none of the above
A(n) _______________ is like a variable, but its value is read-only and cannot be changed during the program’s execution.
secure variable
uninitialized variable
named constant
locked variable
When do preprocessor directives execute?
Before the compiler compiles your program
After the compiler compiles your program
At the same time as the compiler compiles your program
None of the above
True or False
T F A variable must be defined before it can be used.
T F Variable names may begin with a number.
T F Variable names may be up to 31 characters long.
T F A left brace in a C++ program should always be followed by a right brace later in the program.
T F You cannot initialize a named constant that is declared with the
constmodifier.
Algorithm Workbench
Convert the following pseudocode to C++ code. Be sure to define the appropriate variables.
Store 20 in the
speedvariable.Store 10 in the
timevariable.Multiply
speedby time and store the result in thedistancevariable.Display the contents of the
distancevariable.
Convert the following pseudocode to C++ code. Be sure to define the appropriate variables.
Store 172.5 in the
forcevariable.Store 27.5 in the
areavariable.Divide area by
forceand store the result in thepressurevariable.Display the contents of the
pressurevariable.
Find the Error
There are a number of syntax errors in the following program. Locate as many as you can.
*/ What's wrong with this program? /* #include iostream using namespace std; int main(); } int a, b, c \\ Three integers a = 3 b = 4 c = a + b Cout < "The value of c is %d" < C; return 0; {
Programming Challenges
Visit www.myprogramminglab.com to complete many of these Programming Challenges online and get instant feedback.
Sum of Two Numbers
Write a program that stores the integers 50 and 100 in variables, and stores the sum of these two in a variable named
total.Sales Prediction
The East Coast sales division of a company generates 58 percent of total sales. Based on that percentage, write a program that will predict how much the East Coast division will generate if the company has $8.6 million in sales this year.
Sales Tax
Write a program that will compute the total sales tax on a $95 purchase. Assume the state sales tax is 4 percent, and the county sales tax is 2 percent.

Solving the Restaurant Bill Problem
Restaurant Bill
Write a program that computes the tax and tip on a restaurant bill for a patron with a $88.67 meal charge. The tax should be 6.75 percent of the meal cost. The tip should be 20 percent of the total after adding the tax. Display the meal cost, tax amount, tip amount, and total bill on the screen.
Average of Values
To get the average of a series of values, you add the values up then divide the sum by the number of values. Write a program that stores the following values in five different variables: 28, 32, 37, 24, and 33. The program should first calculate the sum of these five variables and store the result in a separate variable named
sum. Then, the program should divide thesumvariable by 5 to get the average. Display the average on the screen.
Tip:Use the
doubledata type for all variables in this program.Annual Pay
Suppose an employee gets paid every two weeks and earns $2,200 each pay period. In a year, the employee gets paid 26 times. Write a program that defines the following variables:
payAmountThis variable will hold the amount of pay the employee earns each pay period. Initialize the variable with 2200.0. payPeriodsThis variable will hold the number of pay periods in a year. Initialize the variable with 26. annualPayThis variable will hold the employee’s total annual pay, which will be calculated. The program should calculate the employee’s total annual pay by multiplying the employee’s pay amount by the number of pay periods in a year and store the result in the
annualPayvariable. Display the total annual pay on the screen.Ocean Levels
Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, write a program that displays:
The number of millimeters higher than the current level that the ocean’s level will be in 5 years.
The number of millimeters higher than the current level that the ocean’s level will be in 7 years.
The number of millimeters higher than the current level that the ocean’s level will be in 10 years.
Total Purchase
A customer in a store is purchasing five items. The prices of the five items are as follows:
Price of item 1 = $15.95
Price of item 2 = $24.95
Price of item 3 = $6.95
Price of item 4 = $12.95
Price of item 5 = $3.95
Write a program that holds the prices of the five items in five variables. Display each item’s price, the subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is 7 percent.
Cyborg Data Type Sizes
You have been given a job as a programmer on a Cyborg supercomputer. In order to accomplish some calculations, you need to know how many bytes the following data types use:
char,int,float, anddouble. You do not have any technical documentation, so you can’t look this information up. Write a C++ program that will determine the amount of memory used by these types and display the information on the screen.Miles per Gallon
A car holds 15 gallons of gasoline and can travel 375 miles before refueling. Write a program that calculates the number of miles per gallon the car gets. Display the result on the screen.
Hint: Use the following formula to calculate miles per gallon (MPG):
MPG 5 Miles Driven/Gallons of Gas Used
Distance per Tank of Gas
A car with a 20-gallon gas tank averages 23.5 miles per gallon when driven in town, and 28.9 miles per gallon when driven on the highway. Write a program that calculates and displays the distance the car can travel on one tank of gas when driven in town and when driven on the highway.
Hint: The following formula can be used to calculate the distance:
Distance 5 Number of Gallons 3 Average Miles per Gallon
Land Calculation
One acre of land is equivalent to 43,560 square feet. Write a program that calculates the number of acres in a tract of land with 391,876 square feet.
Circuit Board Price
An electronics company sells circuit boards at a 35 percent profit. Write a program that will calculate the selling price of a circuit board that costs $14.95. Display the result on the screen.
Personal Information
Write a program that displays the following pieces of information, each on a separate line:
Your name
Your address, with city, state, and ZIP code
Your telephone number
Your college major
Use only a single
coutstatement to display all of this information.Triangle Pattern
Write a program that displays the following pattern on the screen:
* *** ***** *******Diamond Pattern
Write a program that displays the following pattern:
* *** ***** ******* ***** *** *Stock Commission
Kathryn bought 750 shares of stock at a price of $35.00 per share. She must pay her stockbroker a 2 percent commission for the transaction. Write a program that calculates and displays the following:
The amount paid for the stock alone (without the commission).
The amount of the commission.
The total amount paid (for the stock plus the commission).
Energy Drink Consumption
A soft drink company recently surveyed 16,500 of its customers and found that approximately 15 percent of those surveyed purchase one or more energy drinks per week. Of those customers who purchase energy drinks, approximately 58 percent of them prefer citrus-flavored energy drinks. Write a program that displays the following:
The approximate number of customers in the survey who purchase one or more energy drinks per week.
The approximate number of customers in the survey who prefer citrus-flavored energy drinks.
Annual High Temperatures
The average July high temperature is 85 degrees Fahrenheit in New York City, 88 degrees Fahrenheit in Denver, and 106 degrees Fahrenheit in Phoenix. Write a program that calculates and reports what the new average July high temperature would be for each of these cities if temperatures rise by 2 percent.
How Much Paint
A particular brand of paint covers 340 square feet per gallon. Write a program to determine and report approximately how many gallons of paint will be needed to paint two coats on a wooden fence that is 6 feet high and 100 feet long.
2.15 Comments
Concept:
Comments are notes of explanation that document lines or sections of a program. Comments are part of the program, but the compiler ignores them. They are intended for people who may be reading the source code.
Single-Line Comments
//.//to the end of the line.🗊 Program 2-26
Multi-Line Comments
/*and ends with*/.🗊 Program 2-27
Note:
Many programmers use a combination of single-line comments and multi-line comments in their programs. Convenience usually dictates which style to use.