C++ Programming
C++ Programming
C++ Programming
Chapter 2
Basic Elements of C++
A Guide to this Instructor’s Manual:
We have designed this Instructor’s Manual to supplement and enhance your teaching
experience through classroom activities and a cohesive chapter summary.
This document is organized chronologically, using the same headings that you see in the
textbook. Under the headings, you will find lecture notes that summarize the section, Teacher
Tips, Classroom Activities, and Lab Activities. Pay special attention to teaching tips and
activities geared towards quizzing your students and enhancing their critical thinking skills.
In addition to this Instructor’s Manual, our Instructor’s Resources also contain PowerPoint
Presentations, Test Banks, and other supplements to aid in your teaching experience.
At a Glance
• Objectives
• Teaching Tips
• Quick Quizzes
• Additional Projects
• Additional Resources
• Key Terms
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-2
Lecture Notes
Overview
Chapter 2 teaches your students the basics of C++. Learning a programming language is
similar to learning to be a chef or learning to play a musical instrument. All three
require direct interaction with the tools; in other words, you cannot become proficient
by simply reading books on the topics. In this chapter, your students will begin
acquiring a fundamental knowledge of C++ by learning about data types, functions,
identifiers, assignment statements, arithmetic operations, and input/output operations.
They will then write and test programs using these concepts to verify their knowledge
of the material.
Objectives
In this chapter, the student will:
• Become familiar with the basic components of a C++ program, including functions,
special symbols, and identifiers
• Explore simple data types
• Discover how to use arithmetic operators
• Examine how a program evaluates arithmetic expressions
• Become familiar with the string data type
• Learn what an assignment statement is and what it does
• Learn about variable declaration
• Discover how to input data into memory using input statements
• Become familiar with the use of increment and decrement operators
• Examine ways to output results using output statements
• Learn how to use preprocessor directives and why they are necessary
• Learn how to debug syntax errors
• Explore how to properly structure a program, including using comments to document a
program
• Become familiar with compound statements
• Learn how to write a C++ program
Teaching Tips
Introduction
1. Define the terms computer program and programming.
2. Use the recipe analogy to give students an idea of the process of programming.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-3
1. Note that every C++ program must have a function called main. Use Example 2-1 to
illustrate a basic main function. Walk through this example and point out the
meaning of each line.
Teaching Reassure students that although most of this example probably looks confusing,
Tip they will soon understand it and be comfortable with it.
6. Use Figures 2-2 and 2-3 to describe how memory is allocated and used to store values.
2. Define the terms syntax rules and semantic rules as they relate to a programming
language and explain the difference between the two.
Teaching Emphasize that compilers check for syntax but not semantic errors. Give an
Tip example of each type of error.
Comments
1. Use the program in Example 2-1 to describe the use and importance of comments.
Stress that comments are for the reader, not for the compiler.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-4
Special Symbols
1. Explain that the C++ programming language consists of individual units called tokens,
and these are divided into special symbols, word symbols, and identifiers.
1. Discuss the word symbols, or keywords, used in C++, using Appendix A as a guide.
Emphasize that C++ keywords are reserved and cannot be redefined for any other
purpose with a program.
Identifiers
1. Define the term identifier as a name for something, such as a variable, constant, or
function.
2. Discuss the rules for naming identifiers in C++. Also note that C++ is a case-sensitive
language.
Discuss the difference between C++ conventions and rules. For example, it is a
Teaching
rule that a mathematical symbol cannot be used in an identifier name. However,
Tip
it is a convention to begin an identifier with a lowercase letter.
Whitespaces
1. Explain that whitespaces (which include blanks, tabs, and newline characters) are used
to separate special symbols, reserved words, and identifiers.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-5
Data Types
1. Explain that C++ categorizes data into different types in order to manipulate the data in
a program correctly. Although it may seem cumbersome at first to be so type-conscious,
emphasize that C++ has these built-in checks to guard against errors.
Explain that C++ is called a strongly typed language because it checks for
Teaching operations between inconsistent data types. This results in more robust and error-
Tip free programs. Demonstrate how C++ checks for data types with a simple
program that attempts to add a string and a numeric value.
2. Define the term data type as a set of values together with a set of operations.
3. Mention that C++ data types fall into three categories: simple data types, structured data
types, and pointers. Only the first type is discussed in this chapter.
1. Describe the three categories of simple data types in C++: integral, floating-point, and
enumeration.
2. Mention the eleven categories of integral data types. Explain why C++ (and many other
languages) has so many categories of the same data type. In addition, discuss the rules
involving the use of integral types.
5. Discuss the char data type, including its primary uses. Mention commonly used
ASCII characters and their predefined ordering. Explain that a char data type is
enclosed in single quotation marks, and note that only one symbol may be designated as
a character.
6. Use Table 2-2 to summarize the three simple data types. Point out the difference in the
amount of memory storage required, but inform students that this is system-dependent.
1. Use Table 2-3 to explain how C++ represents real, or floating-point, numbers. Mention
the three categories of data types to represent real numbers (float, double, and
long double), and explain when to use each type.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-6
Quick Quiz 1
1. What is an enumeration type?
Answer: C++’s method for allowing programmers to create their own simple data types
2. Define the terms unary and binary operators, and discuss the difference between them.
Order of Precedence
1. Review operator precedence rules, as C++ uses these rules when evaluating
expressions. Explain that parentheses can be used to override the order of operator
precedence.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-7
Expressions
3. Use Examples 2-6 and 2-7 to clarify how C++ processes expressions.
Mixed Expressions
1. Discuss the two rules for evaluating mixed expressions and illustrate these rules in
practice using Example 2-8.
Quick Quiz 2
1. A(n) operator has only one operand.
Answer: unary
2. Illustrate the form of the C++ cast operator using Example 2-9.
Students may feel a bit overwhelmed after the discussion of the static_cast
operator. Ask them to run the program from Example 2.9. They should
Teaching
experiment with removing the static_cast operator from various
Tip
statements, as well as changing the variable values. Ask them to report on any
unpredictable results.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-8
string Type
1. Introduce the C++ data type string, which is a programmer-defined data type
available in the C++ library. Define a string as a sequence of zero or more characters.
3. Discuss how to determine the length of a string, as well as the position of each character
in a string.
Teaching Emphasize that the first position of a character in a string is 0, not 1. This will be
Tip helpful when manipulating both strings and arrays later on the text.
1. Emphasize that when allocating memory, the programmer must instruct the computer
which names to use for each memory location as well as what type of data to store in
those memory locations.
2. Define the term named constant and describe the syntax for declaring a named constant.
Use Example 2-11 to illustrate the naming conventions for named constants. Explain
why named constants are used in programs.
3. Define the term variable and use Example 2-12 to illustrate the syntax for declaring
single and multiple variables.
1. Mention the two ways you can place data in a variable in C++.
Assignment Statement
1. Discuss the C++ assignment statement, including its syntax, variable initialization, and
the associativity rules of the assignment operator.
2. Step through Example 2-13 to illustrate how assignment statements operate in C++.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-9
3. Use Example 2-14 to discuss the importance of doing a walk-through (tracing values
through a sequence of steps) when writing code.
Teaching Building a table showing the values of variables at each step of the program is
Tip very helpful for students to understand the nature of variables.
1. Explain the steps involved in saving the value of an expression using Example 2-15.
1. Explain that when a variable is declared, C++ may not automatically put a meaningful
value in it.
2. Emphasize that it is a good practice to initialize variables while they are being declared.
Use one or more examples to illustrate how to do this in C++.
1. This section teaches your students to read data into variables from a standard input
device. Define and explain the use of the C++ object cin and the stream
extraction operator >>.
2. Step through Examples 2-16 through 2-18 to illustrate how to read in numeric and string
data.
Variable Initialization
Quick Quiz 3
1. What is a named constant?
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-10
Answer: A memory location whose content is not allowed to change during program
execution
3. True or False: If you refer to an identifier without declaring it, the compiler will
generate an error message.
Answer: True
1. Explain the purpose of the C++ increment (++) and decrement (--) operators.
2. Discuss how pre and post versions of these operators affect the results in a program.
Use Example 2-20 to help explain the difference between these versions.
Verify that students are comfortable with using pre- and post-
Teaching
increment/decrement operators correctly, as it will be useful when working with
Tip
control structures.
Output
1. Review how the C++ output statement is coded with the cout object and stream
insertion operator (<<). Review the role of the endl manipulator in output
statements as well.
2. Discuss the use of escape characters (see Table 2-4), such as the newline character, to
format output. Demonstrate how to format output with Examples 2-21 through 2-26.
Outputting strings can be confusing at first. Talk about the various methods to
Teaching deal with several lines of string output, and give your opinion as to the best
Tip approach. Emphasize that the Enter key cannot be used to break up a long string
into two lines.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-11
Preprocessor Directives
1. Explain the role of the preprocessor in C++. Discuss the use of header files and the
syntax for including them in a C++ program.
Teaching Show your students some of the available operations in the <cmath>
Tip header. Here is one Web site with a description:
http://www.cplusplus.com/reference/cmath/
1. Mention that the <string> header must be included in C++ programs using the
string data type.
1. Discuss the role of the function main in a C++ program. Go over the syntax of a
main function, including declaration, assignment, executable, and return statements.
Mention that named constant definitions and preprocessor directives are written before
the main function.
2. Spend some time stepping through Examples 2-27 through 2-29. Verify that students
understand each line of code in Example 2-29.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-12
Syntax
1. Remind students that syntax rules define what is legal and what is not.
2. Discuss some common syntax errors. Emphasize that syntax errors should be corrected
in the order in which the compiler lists them.
Use of Blanks
1. Discuss when blanks should and should not be used in a C++ program.
1. Explain the purpose and meaning of semicolons, brackets, and commas in C++
programs. Define the term statement terminator.
Semantics
2. Reiterate that a program may run without compiler errors and still have semantic errors
that generate incorrect results. Use the example in the text to illustrate.
Naming Identifiers
Prompt Lines
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-13
2. Explain why well-written prompt lines are essential for user input.
Documentation
1. Explain the purpose behind formatting and indentation conventions in source code. Use
Example 2-30 to illustrate.
As with naming conventions, discuss your own preferences in terms of form and
Teaching style in programming. Use the programming examples at the end of the chapter
Tip to talk about various stylistic elements. Discuss the value of the “art” of
programming.
Quick Quiz 4
1. True or False: The semantic rules of a language tell you what is legal and what is not
legal.
Answer: False
2. Define the C++ compound operators (+=, -=, *=, /=, and %=) and explain how and
why compound assignment statements are used in C++ programs. Use Example 2-31 to
illustrate this.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-14
3. Step through the “Convert Length” and “Make Change” Programming Examples to
help the students consolidate all the information from this chapter.
2. The text mentioned that the char data type can be cast into an int. What are
some possible uses of this functionality?
Additional Projects
1. Learn and report on various compiler errors by modifying one or two of the programs in
this chapter. Try to compile the program. What happens when you fail to initialize a
value for a named constant? What are the error messages when you use a numeric or
string constant in an expression without first giving it a value? Finally, what happens
when you initialize a char data type with a character enclosed in double quotes?
2. Use one of the programs in this chapter to test for invalid user input. The program
should compile with no errors. What happens when you enter an unexpected value
(such as an incorrect data type) when prompted for user input? Test with several sets of
invalid data and document your findings.
Additional Resources
1. C++ Examples:
https://developers.google.com/edu/c++/getting-started
2. Basic Input/Output:
http://www.cplusplus.com/doc/tutorial/basic_io/
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-15
Key Terms
Arithmetic expression: an expression constructed using arithmetic operators and
numbers
Assignment operator: =; assigns whatever is on the right side to the variable on the left
side
Associativity: the associativity of arithmetic operators is said to be from left to right
Binary operator: an operator that has two operands
Cast operator (type conversion, type casting): used to explicitly convert one data type
to another data type
Character arithmetic: arithmetic operation on char data
Collating sequence: a predefined ordering for the characters in a set
Compound assignment statement: statements that are used to write simple assignment
statements in a more concise notation
Computer program: a sequence of statements whose objective is to accomplish a task
Data type: a set of values together with a set of operations
Declaration statements: statements that are used to declare things, such as variables
Decrement operator: --; decreases the value of a variable by 1
Double precision: values of type double
Enumeration: a user-defined data type
Executable statements: statements that perform calculations, manipulate data, create
output, accept input, and so on
Floating-point: a data type that deals with decimal numbers
Floating-point (decimal) expression: an expression in which all operands in the
expression are floating-point numbers
Floating-point notation: a form of scientific notation used to represent real numbers
Function (subprogram): a collection of statements; when activated, or executed, it
accomplishes something
Identifier: a C++ identifier consists of letters, digits, and the underscore character (_); it
must begin with a letter or underscore
Implicit type coercion: when a value of one data type is automatically changed to
another data type
Increment operator: ++; increases the value of a variable by 1
Initialized: the first time a value is placed in the variable
Input (read) statement: a statement that places data into variables using cin and >>
Integral: a data type that deals with integers, or numbers, without a decimal part
Integral expression: an expression in which all operands are integers
Keyword: a reserved word
Mixed expression: an expression that has operands of different data types
Named constant: a memory location whose content is not allowed to change during
program execution
Null (empty) string: a string containing no characters
Operands: numbers appearing in an arithmetic expression
Output statement: an output on the standard output device via cout and <<
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
C++ Programming: From Problem Analysis to Program Design, Eighth Edition 2-16
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in
a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Chapter 2
1. a. false; b. false; c. true; d. true; e. false; f. false; g. true; h. true; i. false; j. false; k. true; l. false
2. b, d, e, f
3. b, e
4. A keyword is a reserved word and is defined by the system. A keyword cannot be redefined in
a program. A user-defined identifier can be redefined.
5. The identifiers quizNo1 and quizno1 are not the same. C++ is case sensitive. The fifth letter
of quizNo1 is uppercase N while the fifth character of quizno1 is lowercase n. So these
identifiers are different
6 . a. 22
b. 2
c. 14
d. 8
e. 7.00
f. 21
g. 20
h. 0.00
i. 15.50
7. a. 7
b. 5.50
c. -1.00
d. Not possible. Both the operands of the operator % must be integers. y + z is of type double.
Both operands, y + z and x, of %V must be integers.
e. 13.50
f. 1
g. Not possible. Both the operands of the operator % must be integers. Because the second operand,
z, is a floating-point value, the expression is invalid.
h. 3.00
7
char grade = 'B'; //Line 2
Variable declaration in Line 3 is incorrect because the left side of the assignment operator must be
a variable, and the semicolon at the end of the statement is missing. A correct declaration is:
double num = 28.5; //Line 3
The variable declaration in Line 4 is incorrect because strings are enclosed in double quotation
marks. A correct declaration is:
string message = "First C++ course"; //Line 4
The variable declaration in Line 5 is incorrect because the value assigned to age must be an int
value. A correct declaration is:
int age = 18; //Line 5
13. a. 9.0 / 5 * C + 32
b. static_cast<int>('+')
c. static_cast<int>(x + 0.5)
d. str = "C++ Programming is exciting"
e. totalInches = 12 * feet + inches
f. i++, ++i, or i = i + 1;
g. v = 4 / 3 * (3.1416 * r * r *r);
h. s = 2* (3.1416 * r * *r) + 2 * (3.1416 * r) * h;
i. a + (b – c) / d * (e * f – g * h)
j. (–b + (b * b – 4 * a * c)) / (2 * a)
8
14. x = 1
y = 102
z = 15
w = 44
15. x = 101
y = 11
z = 104
w = 159.00
t = 81.50
16. a. x = 18, y = 5, z = 4
b. 5 * x - y = 85
c. Product of 18 and 4 is 72
d. x - y / z = 17
e. 18 square = 324
17. a. 1000
b. 42.50
c. 1.25
d. 11.00
e. 9
f. 88.25
g. -2.00
18. a. cout << endl; or cout << "\n"; or cout << '\n';
b. cout << "\t";
c. cout << "\"";
9
21. a. int num1;
int num2;
b. cout << "Enter two numbers separated by spaces." << endl;
c. cin >> num1 >> num2;
d. cout << "num1 = " << num1 << ", num2 = " << num2
<< ", 2 * num1 – num2 = " << 2 * num1 – num2 << endl;
int main()
{
int height, weight;
double discount;
double billingAmount;
double bonus;
int hoursWorked = 45;
double price;
height = 6;
weight = 156;
cout << height << " " << weight << endl;
cout << price << blanks << "$" << billingAmount << endl;
return 0;
}
10
int main()
{
int count, sum;
double x;
count = 1;
sum = count + PRIME;
x = 25.67; // x = 25.67;
newNum = count * 1 + 2; //newNum = count * ONE + 2;
sum++; //(x + sum)++;
sum = sum + count; //sum + count = sum;
x = x + sum * count; // x = x + sum * COUNT;
sum += 3; //sum += 3--;
cout << " count = " << count << ", sum = " << sum
<< ", PRIME = " << PRIME << endl;
return 0;
}
#include <iostream>
#include <string>
int main()
{
int num1, num2;
string str1;
return 0;
}
11
e. y /= x + 5;
28. a. x = x + 5 – z;
b. y = y * (2 * x + 5 – z);
c. w = w + 2 * z + 4;
d. x = x – (z + y – t);
e. sum = sum + num;
29.
a b c
a = (b++) + 3; 8 3 und
c = 2 * a + (++b); 8 2 12
b = 2 * (++c) – (a++); 9 -3 11
30.
a b c sum
sum = static_cast<int>(a + b + c); 6 3 2.2 11
b += c * a; 6 16 2.2 11
c -= a; 6 16 -3.8 11
a *= 2 * b - c; 214 16 -3.8 11
Name: Miller
Id: 34
Mystery number: -5.14286
33.
#include <iostream>
#include <string>
12
const double X = 13.45;
const int Y = 18;
const char STAR = '*';
int main()
{
string employeeID;
string department;
int num;
double salary;
salary = num * X;
return 0;
}
13