0% found this document useful (0 votes)
3 views

Chapter 2 - Simple C++ Programs

Uploaded by

johnmf1011
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 2 - Simple C++ Programs

Uploaded by

johnmf1011
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 59

©2017 Pearson Education, Inc.

Hoboken,
NJ. All Rights Reserved.

Chapter 2
Simple C++ Programs
Outline
Objectives
1. C++ Program Structure
2. Constant and Variables
3. C++ Classes
4. Building C++ Solutions with IDEs:Xcode
5. C++ Operators
6. Standard Input and Output
7. Building C++ Solutions with IDEs:NetBeans
8. Basic Functions in C++ Standard Library
9. Problem Solving Applied
10.System Limitations
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
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

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects. C++11 recommended
notation for initializing
double x1{1}, y1{5}, x2{4}, y2{7}, objects.
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
C++
Program
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.

Structure
cout << "The distance between the two points is "
<< distance << endl;
// Exit program.
return 0;
}
//--------------------------------------------------------

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1; Comments:
side2 = y2 - y1; •Document the
distance = sqrt(side1*side1 + side2*side2); program’s purpose
// Print distance.
•Help the human
cout << "The distance between the two points is "
<< distance << endl; reader understand the
// Exit program. program
return 0; •Are ignored by the
} compiler
//-------------------------------------------------------- •// comments to end-of
line
•/* starts a comment
block ending with */
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1; Preprocessor
distance = sqrt(side1*side1 + side2*side2); Directives:
// Print distance. •Give instructions to the
cout << "The distance between the two points is " preprocessor before
<< distance << endl;
the program is
// Exit program.
return 0;
compiled.
} •Begin with #
//-------------------------------------------------------- #include directives ‘ad
d’ or ‘insert’ the
contents of the named
file into the program

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1; ‘using’ Directives:
side2 = y2 - y1; •Tell the compiler to
distance = sqrt(side1*side1 + side2*side2);
use the library
// Print distance.
cout << "The distance between the two points is "
names declared in
<< distance << endl; the specified
// Exit program. namespace.
return 0; •The ‘std’, or
} standard
//--------------------------------------------------------
namespace contains
C++ language-
defined
components.
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1; main function header:
side2 = y2 - y1; •Defines the starting
distance = sqrt(side1*side1 + side2*side2);
point (i.e. entry point)
// Print distance.
cout << "The distance between the two points is "
for a C++ program
<< distance << endl; •The keyword ‘int’
// Exit program. indicates that the
return 0; function will return an
} integer value to the
//--------------------------------------------------------
operating system.
• Every C++ program
has exactly one
function named main.
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.
cout << "The distance between the two points is " Code blocks:
<< distance << endl;
•are zero or more C++
// Exit program.
return 0;
declarations and/or
} statements enclosed
//-------------------------------------------------------- within curly braces { }

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.
cout << "The distance between the two points is "
<< distance << endl;
// Exit program.
return 0;
}
//--------------------------------------------------------

Declarations:
•Define identifiers and
allocate memory.
•May also provide initial
values for variables.
•Identifiers must be
declared before using
in a statement.
•C++11 recommends
using { } notation.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
/*--------------------------------------------------------
* Program chapter1_1
* This program computes the distance between two points.
*/
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std;
int main() {
// Declare and initialize objects.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.
cout << "The distance between the two points is "
<< distance << endl;
Statements :
// Exit program.
return 0;
•specify the operations
} to be performed.
//--------------------------------------------------------

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Constants and
Variables

• Constants and variables both represent memory locations


that we reference in our program solutions.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Constants and Variables
• 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 x1{1.0}, x2{4.5}, side1;
– side1 = x2 - x1;
– x1, x2 and side1 are examples of variables that can be modified.

©2017 Pearson Education, Inc. Hoboken, NJ. 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’.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Memory Snapshots
• Memory ‘snapshots’ are diagrams that
show the types and contents of variables
at a particular point in time.
double x1{1}, y1{5}, x2{4}, y2{7},
side1, side2, distance;

double x1 1.0 double y1 5.0

double x2 4.0 double y2 7.0

double side1 ? double side2 ? double distance ?

©2017 Pearson Education, Inc. Hoboken, NJ. 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.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
C++ Keywords

©2017 Pearson Education, Inc. Hoboken, NJ. 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.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Common C++ Data Types
• Keyword Example of a constant
– bool true
– char '5'
– int 25
– double 25.0
– string "hello" //#include<string>

©2017 Pearson Education, Inc. Hoboken, NJ. 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.
Syntax
[modifier] type specifier identifier [{initial value}];
[modifier] type specifier identifier [= initial value];
[modifier] type specifier identifier[(initial value)];
Examples
double x1, y1{0}; //C++11
int counter=0;
const int MIN_SIZE=0;
bool error(false);
char comma(',');

©2017 Pearson Education, Inc. Hoboken, NJ. 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.

©2017 Pearson Education, Inc. Hoboken, NJ. 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.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Examples

• auto x1 = 0; //x1 is type integer


• auto comma = ','; //comma is type char
• auto y1 = 0.5; //y1 is type double
• auto time = x1; //time is type integer

auto can be useful as data types become more complex,


and harder to determine.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Order of Types
• Because different data types have
different representations, it may be
necessary to convert between High: long double
double
data types. float
– Conversion from a lower type to a long integer
integer
higher type results in no loss of Low: short integer
information.(Example: double x{1};)
– Conversion from higher type to lower
type may loose information. (Example:
int x(7.7);) implicit conversion from 'double' to
'int' changes value from 7.7 to 7

©2017 Pearson Education, Inc. Hoboken, NJ. 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

©2017 Pearson Education, Inc. Hoboken, NJ. 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. };

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Class Implementation
– The class is typically written in a file named
“className.cpp”
– File should #include “className.h”
– Provides the code to implement class
methods.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Class Syntax

©2017 Pearson Education, Inc. Hoboken, NJ. 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.

©2017 Pearson Education, Inc. Hoboken, NJ. 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)
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Integrated Development
Environments (IDEs)
• IDEs are software packages designed
to facility the development of software
solutions.
• IDEs include:
– Code editors
– Compiler
– Debugger
– Testing tools
– Many additional helpful tools…
©2017 Pearson Education, Inc. Hoboken, NJ. 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/ .

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
C++ Operators

• Assignment Operator

• Arithmetic Operators

• Increment and Decrement Operators

• Abbreviated Arithmetic Operators

©2017 Pearson Education, Inc. Hoboken, NJ. 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.)
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Assignment Statements

Assignment operator(=) should not be


confused with equality operator(==).
©2017 Pearson Education, Inc. Hoboken, NJ. 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 compound
expressions involving arithmetic operators
(e.g. x1 = -3.4*x2 + 10.4).

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Arithmetic Operators
• Addition +
• Subtraction -
• Multiplication *
• Division /
• Modulus %
– Modulus returns remainder of division between two
integers
– Example
5%2 returns a value of 1

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Operator Basics
• 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.
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Integer Division
• Division between two integers results
in an integer.
• The result is truncated, not rounded
• Example:
The expression 5/3 evaluates to 1
The expression 3/6 evaluates to 0

©2017 Pearson Education, Inc. Hoboken, NJ. 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.

©2017 Pearson Education, Inc. Hoboken, NJ. 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.
• Example: Memory snapshot:
int count 10
int count{10}, sum{55};
double average; int sum 55

average = (double)sum/count; double average 5.5

©2017 Pearson Education, Inc. Hoboken, NJ. 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;

©2017 Pearson Education, Inc. Hoboken, NJ. 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.
• m = ++k; // m and k are 6 after execution
• n = k- -; // n is 5 and k is 4 after execution
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Abbreviated Assignment
Operators
operator example equivalent statement
+= x+=2; x=x+2;
-= x-=2; x=x-2;
*= x*=y; x=x*y;
/= x/=y; x=x/y;
%= x%=y; x=x%y;

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Operator Precedence

Precedence Operator Associativity


1 Parenthesis: () Innermost First
2 Unary operators: Right to left
+ - ++ -- (type)
3 Binary operators: Left to right
* / %
4 Binary operators: Left to right
+ -
5 Assignment Operators Right to left
= Hoboken,
©2017 Pearson Education, Inc. += -= NJ. All*= /= %=
Rights Reserved.
Standard Input/Output

cin Standard input, pronounced “c in”

cout Standard output, pronounced “c out”

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Standard 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:
cout << expression << expression;

Note: An expression is a C++ constant, identifier, formula, or


function call.
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Standard Input - cin
• cin is an istream object defined
in the header file iostream
• cin is defined to stream data from standard
input (the keyboard)
• We use the input operator >> with cin to
assign values to variables
– General Form
cin >> identifier >> identifier;
• Note: Data entered from the keyboard must be compatible with the
data type of the variable.
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Characters and Input
• The input operator >> skips all
whitespace characters.
• The get() method gets the next character.
• Example: Input stream:
45 c
int x; 39
char ch; b

cin >> x >> ch; Memory Snapshot


cin >> x; x 45 ch ‘c’
cin.get(ch);
x 39 ch ‘\n ’
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Manipulators and Methods
• endl – places a newline character in the
output buffer and flushes the buffer.
• setf() and unsetf()
Flag Meaning
ios::showpoint display the decimal point
ios::fixed fixed decimal notation
ios::scientific scientific notation
Ios::setprecision(n) set the number of significant digits to be printed to the
integer value n
Ios::setw(n) set the minimum number of columns for printing the
next value to the integer value n
ios::right right justification
ios::left left justification
©2017 Pearson Education, Inc. Hoboken, NJ. 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++.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Basic Functions in C++
Standard Library

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Math Functions
#include<cmath>
fabs(x) computes absolute value of x
sqrt(x) computes square root of x, where
x >=0
pow(x,y) computes xy
ceil(x) nearest integer larger than x
floor(x) nearest integer smaller than x
exp(x) computes ex
log(x) computes ln x, where x >0
log10(x) computes log10x, where x>0
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Trigonometric Functions
sin(x) sine of x, where x is in radians
cos(x) cosine of x, where x is in radians
tan(x) tangent of x, where x is in radians
asin(x) This function computes the arcsine, or inverse sine, of x, where x
must be in the range [−1, 1].
The function returns an angle in radians in the range [−π/2, π/2].
acos(x) This function computes the arccosine, or inverse cosine, of x,
where x must be in the range [−1, 1].
The function returns an angle in radians in the range [0, π].
atan(x) This function computes the arctangent, or inverse tangent, of x.
The function returns an angle in radians in the range [−π/2, π/2].
atan2(y,x) This function computes the arctangent or inverse tangent of the
value y/x.
The function returns an angle in radians in the range [−π, π].
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
Common Functions
Defined in <cctype>
isalpha(ch) Returns true if ch is an upper or lower case letter.

isdigit(ch) Returns true if ch is a decimal digit

isspace(ch) Returns true if ch is a whitespace character.

islower(ch) Returns true if ch is an lower case letter.

isupper(ch) Returns true if ch is an upper case letter.

tolower(ch) Returns the lowercase version of ch if ch is an uppercase


character, returns ch otherwise.
toupper(ch) Returns the uppercase version of ch if ch is a lowercase
character, returns ch otherwise.

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
Problem Solving Applied

©2017 Pearson Education, Inc. Hoboken, NJ. All


Rights Reserved.
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.
©2017 Pearson Education, Inc. Hoboken, NJ. 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.
©2017 Pearson Education, Inc. Hoboken, NJ. All
Rights Reserved.

You might also like