Chapter 2 - Simple C++ Programs - Accessible
Chapter 2 - Simple C++ Programs - Accessible
Fourth Edition
Chapter 2
Simple C++ Programs
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Outline (1 of 2)
2.1 C++ Program Structure
2.2 Constant and Variables
2.3 C++ Classes
2.4 Building C++ Solutions with IDEs:Xcode
2.5 C++ Operators
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Outline (2 of 2)
2.6 Standard Input and Output
2.7 Building C++ Solutions with IDEs:NetBeans
2.8 Basic Functions in C++ Standard Library
2.9 Problem Solving Applied
2.10 System Limitations
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Learning Objectives
Develop problem-solving solutions in C++ containing:
• Simple arithmetic computations
• Information printed on the screen
• User-supplied Information from keyboard
• Programmer-defined data types
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (1 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (2 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (3 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (4 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (5 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (6 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (7 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Program Structure (8 of 8)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Constants and Variables (1 of 2)
• Constants and variables represent memory locations that
we reference in our program solutions.
• Constants are objects that store specific data values that can
not be modified.
– 10 is an integer constant
– 4.5 is a floating point constant
– "The distance between the two points" is a
string constant
– ‘a’ is a character constant
• Variables are named memory locations that store values that
can be modified.
– double x11.0, x2 4.5, side1;
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Constants and Variables (2 of 2)
– side1 = x2 − x1;
– x1, x2 and side1 are examples of variables that can be
modified.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Initial Values
• C++ does not provide initial values for variables.
– Thus using the value of a variable before it is initialized
may result in ‘garbage’.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Memory Snapshots
• Memory ‘snapshots’ are diagrams that show the types
and contents of variables at a particular point in time.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Valid C++ Identifiers
• Must begin with an alphabetic
character or the underscore character ‘_’
• Alphabetic characters may be either upper or lower case.
– C++ is CASE SENSITIVE, so ‘a’ ! ‘A’, etc…
• May contain digits, but not as the first character.
• May be of any length, but the first 31 characters must be
unique.
• May NOT be C++ keywords.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Keywords (1 of 2)
Table 2.1 Keywords
alignas else mutable register
char32_t
alignof enum namespac reinterpret_ca
class
e st
and compl explicit
new return
and_eq const extern
noexcept short
asm constexpr false
not signed
auto const_cast float
not_eq sizeof
bitand continue for
nullptr static
bitor decltype friend
operator static_assert
bool default goto
or static_cast
break delete if
or_eq struct
case do inline
private switch
catch double int
protected template
char16_t dynamic_cast long
public this
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Keywords (2 of 2)
Table 2.1 [continued]
thread_local virtual
throw void
true volatile
try wchar_t
typedef while
typeid xor
typename xor_eq
union
unsigned
using
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Identifiers
• Should be carefully chosen to reflect the contents of the object.
– The name should also reflect the units of measurements
when applicable.
• Identifiers must be declared before they may be used.
– C++ is a strongly typed programming language.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Common C++ Data Types
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Declarations
• A type declaration statement defines new identifiers and
allocates memory.
• An initial value may be assigned to a memory location at the
time an identifier is defined.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Symbolic Constants
• A symbolic constant is defined in a declaration statement using
the modifier const.
• A symbolic constant allocates memory for an object that can
not be modified during execution of the program. Any attempt
to modify a constant will be flagged as a syntax error by the
compiler.
• A symbolic constant must be initialized in the declaration
statement.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Auto Type Specifier
• The C++11 keyword auto supports the declaration of an
object without specifying a data type, as long as an initializer is
provided.
• The data type of the initializer defines the data type of the
identifier.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Examples
•
•
•
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Order of Types
• Because different data types have different High: long double
double
representations, it may be necessary to convert float
long integer
between data types. integer
– Conversion from a lower type to a higher Low: short integer
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Classes
C++ Supports the use of classes to define new data types.
• Definition of a new class type requires a
– Class Declaration
– Class Implementation
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Class Declarations
• Typically written in a file named “className.h”.
• Begins with keyword class followed by the name (identifier)
of the new class type.
• Body of the class declaration is a block of code containing
– declaration of data members (attributes)
– method (function) prototypes
– keywords public, protected, and private are used to
control access to data members and methods
– A semicolon must terminate the body of the class
declaration. };
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Class Implementation
• The class is typically written in a file named
“className.cpp”
• File should
• Provides the code to implement class methods.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Class Syntax
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Class Methods
• Define the operations that can be performed on class objects.
– A constructor is a special method that is executed when
objects of the class type are declared (instantiated).
– Constructors have the same name as the class.
– A class may define multiple constructors to allow greater
flexibility in creating objects.
▪The default constructor has no parameters.
▪Parameterized constructors provide initial values for
data members.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Using a Class
• Once a class is defined, you may use the class name as a type
specifier.
– You must include the class declaration (i.e. header file)
– You must link to the class implementation (i.e. .cpp file)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Integrated Development Environments (I DEs)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Xcode
The Xcode IDE was developed by Apple for the development of
applications that run on Macs, iPads, and iPhones. Xcode is
available as a free download at https://developer.apple.com/ .
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
C++ Operators
• Assignment Operator
• Arithmetic Operators
• Increment and Decrement Operators
• Abbreviated Arithmetic Operators
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Assignment Operator
• The assignment operator (=) is used in C++ to assign a
value to a memory location.
• The assignment statement:
x1 = 1.0;
– assigns the value 1.0 to the variable x1.
– Thus, the value 1.0 is stored in the memory location
associated with the identifier x1.
(Note: x1 must have been previously declared.)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Assignment Statements
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Arithmetic Expressions
• Expressions used in assignment statements for numeric
variables may be literal constants (e.g. x1 = 10.4;), other
variables (e.g. x2= x1;), or complex expressions involving
arithmetic operators (e.g. x1 = -3.4*x2 + 10.4).
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Arithmetic Operators
• Addition +
• Subtraction −
• Multiplication
Asterisk
• Division /
Forward slash
• Modulus Percent
%
– Modulus returns remainder of division between two
integers
– Example
▪ 5%2 returns a value of 1
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Operator Basics (1 of 2)
• The five operators * / % are binary operators -
operators that require two arguments (i.e. operands).
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Operator Basics (2 of 2)
• The five operators * / % are binary operators -
operators that require two arguments (i.e. operands).
• C++ also includes unary operators - operators that
require only a single argument.
– For example, the minus sign preceding an
expression, as in (y = −x2), is a unary operator.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Integer Division
• Division between two integers results in an integer.
• The result is truncated, not rounded
• Example:
5
– The expression evaluates to 1
3
– The expression 3 evaluates to 0
6
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Mixed Operations
• Binary operations on two values of same type yield a value of
that type (e.g. dividing two integers results in an integer).
• Binary operations between values of different types is a mixed
operation.
– Value of the lower type must be converted to the higher
type before performing operation.
– Result is of the higher type.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Casting
• The cast operator.
– The cast operator is a unary operator that requests that the
value of the operand be cast, or changed, to a new type for
the next computation. The type of the operand is not
affected.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Overflow and Underflow
• Overflow
– answer too large to store
Example: using 16 bits for integers
result = 32000+532;
• Exponent overflow
– answer’s exponent is too large
Example: using float, with exponent range −38 to 38
result = 3.25e28 * 1.0e15;
• Exponent underflow
– answer’s exponent too small
Example: using float, with exponent range −38 to 38
result = 3.25e-28 * 1.0e-15;
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Increment and Decrement Operators
• Unary Operators
• Increment Operator + +
– post increment x + +;
– pre increment + + x;
• Decrement Operator - -
– post decrement x - -;
– pre decrement - - x;
• For example, assume k=5 prior to executing each of the following
statements.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Abbreviated Assignment Operators
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Operator Precedence
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Standard Input/Output
cin Standard input, pronounced “c in”
cout Standard output, pronounced “c out”
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Sample Output - cout
• cout is an ostream object, defined in the header file
iostream
• cout is defined to stream data to standard output (the
display)
• We use the output operator << with cout to
output the value of an expression.
General Form:
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Characters and Input
• The input operator skips all whitespace characters.
• The get() method gets the next character.
• Example:
Memory Snapshot
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Manipulators and Methods
• endl – places a newline character in the output buffer and flushes
the buffer.
•
Flag Meaning
display the decimal point
I o s colon colon show point
ios :: showpoint
fixed decimal notation
I o s colon colon fixed.
ios :: fixed
scientific notation
I o s colon colon scientific
ios :: scientific
set the number of significant digits to be printed to the integer
I o s colon colon set precision left parenthesis n right parenthesis
Ios :: setprecision n
value n
set the minimum number of columns for printing the next value
I o s colon colon set w left parenthesis n right parenthesis
ios :: right
left justification
I o s colon colon left
ios :: left
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Building C++ Solutions with IDEs:NetBeans
The NetBeans IDE is open source software that provides a
development environment for multiple languages including Java, C and
C++.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Basic Functions in C++ Standard
Library
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Math Functions #include < cmath >
pow(x,y) computes Xy
X to the power of y
ceil x
c e I l left parenthesis x right parenthesis
E to the x power
log x
Log of left parenthesis x right parenthesis
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Trigonometric Functions
sine of x, where x is in radians
Sine of left parenthesis x right parenthesis
sin x
cosine of x, where x is in radians
Tangent of left parenthesis x right parenthesis
cos x
asin x
in the range -1, 1.
Left bracket negative 1 comma 1 right bracket
The function returns an angle in radians in the range / 2, / 2. Left bracket negative pie over 2 comma pie over 2 right bracket
acos x
must be in the range -1, 1.
The function returns an angle in radians in the range 0, .
Left bracket negative 1 comma 1 right bracket
The function returns an angle in radians in the range / 2, / 2. Left bracket negative pie over 2 comma pie over 2 right bracket
atan2 y,x
parenthesis
Y over x
The function returns an angle in radians in the range , . Left bracket negative pie comma pie right bracket
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Common Functions Defined in < cctype >
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Problem Solving Applied
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Problem Solving Applied (1 of 5)
1. Problem Statement
Compute the new velocity and acceleration of the aircraft
after a change in power level.
2. Input/Output Description
The following diagram shows that the input to the program
is a time value, and that the output of the program is the
pair of new velocity and acceleration values. The built-in
data type double can be used to represent these values.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Problem Solving Applied (2 of 5)
3. Hand Example
Suppose that the new time value is 50 seconds. Using the
equations given for the velocity and accelerations, we can
compute these values:
Velocity = 208.3 m / s;
Acceleration = 0.31 m / s2 .
4. Algorithm Development
The first step in the development of an algorithm is the
decomposition of the problem solution into a set of
sequentially executed steps:
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Problem Solving Applied (3 of 5)
Decomposition Outline
1. Read new time value.
2. Compute corresponding velocity and acceleration
values.
3. Print new velocity and acceleration.
Because this program is a very simple program, we can
convert the decomposition directly to C++.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Problem Solving Applied (4 of 5)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Problem Solving Applied (5 of 5)
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
System Limitations
• C++ standards do not specify limitations of data types –
they are compiler-specific.
• C++ does provide standard methods of accessing the
limits of the compiler:
– <climits> defines ranges of integer types.
– <cfloat> defines ranges of floating-point types.
– the sizeof(type) function returns the memory size of
the type, in bytes.
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved
Copyright
Copyright © 2017, 2012, 2008 Pearson Education, Inc. All Rights Reserved