Computing Fundamentals with C++
Download
Report
Transcript Computing Fundamentals with C++
2-1
Computing Fundamentals with C++
Object-Oriented Programming and Design, 2nd Edition
Rick Mercer
Franklin, Beedle & Associates, 1999
ISBN 1-887902-36-8
Presentation Copyright 1999, Franklin, Beedle & Associates
Students who purchase and instructors who adopt Computing Fundamentals with C++,
Object-Oriented Programming and Design by Rick Mercer are welcome to use this
presentation as long as this copyright notice remains intact.
Chapter 2
Implementation
2-2
Chapter
Objectives
Understand how to reuse existing code in your
programs with #include
Obtain input data from the user and display
information to the user with cin and cout
Evaluate and create arithmetic expressions 3*x
Understand operations common to many objects
such as int, double, and string:
Construction, Output, Assignment, and Input
– Exercises and Programming Projects to reinforce
implementing simple programs
2.1 The C++ Programming
Language: A Start
2-3
A C++
program is a sequence of characters
created with a text editor and stored as a file.
this is the source code
The
file name have specific endings:
UNIX: .cc or .C
DOS or MS-Windows: .cpp
MacOS: .cp or .cpp
2-4
General Forms
General
forms provide information to create
syntactically correct programs
Anything in yellow boldface must be written
exactly as shown (cout << for example)
Anything in italic represents something that must
be supplied by the user
The italicized portions are defined elsewhere
2-5
General Form: A program
// Comment
#include-directive(s)
using namespace std;
int main()
{
object-initializations
statement(s)
return 0;
}
2-6
Example C++ program
// This C++ program gets a number from the //
user and displays that value squared
#include <iostream> // for cout cin endl
using namespace std;
int main()
{
double x = 0.0;
cout << "Enter a number: ";
cin >> x;
cout << "x squared: " << (x * x) << endl;
}
return 0;
The compiler
2-7
The
compiler
reads source code in a character by character
fashion
reports errors whenever possible
reports warnings to help avoid errors
conceptually replaces #includes with the source
code of the #included file
#include directives
2-8
General
form: #include-directive
#include <include-file>
-or-
#include
< > causes a search of the system folder(s)
"include-file"
these files should be found automatically.
The form with " " first searches the working
folder before searching the system folder(s)
the " " indicates an author supplied file name that you
may need in your working folder.
2-9
2.1.1 The smallest pieces of a
C++ Program
A token
is the smallest recognizable unit in a
programming language
There are four types of tokens:
special symbols
keywords
identifiers
constants
2-10
Each
A "tokenized program"
color represents either a different token
symbol
reserved word
identifier
special
constant
comment (gray), or #include directive (cyan)
// Comment: This is a complete C++ program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
2.1.2 Special Symbols
2-11
One
or two character sequences (no spaces)
// <
Some
>
(
)
{
<<
;
}
!=
special symbols mean different things in
different contexts
2.1.3 Keywords
2-12
Word
like tokens with a pre-defined meaning
that can't be changed (reserved)
double
Some
bool
case
char
int
of the keywords in the text :
class
do
else
for
if
long
operator
return
switch
typedef
void
while
2-13
2.1.4 Identifiers
There
are some standard (must be available
wth the C++ compiler) identifiers:
endl sqrt string width std
The
programmer can make up new identifiers
(programmer-defined)
test1
x1
Note: main
aNumber
MAXIMUM
A_1
is a programmer-defined
identifier, cout is a standard identifier
2-14
Active Learning
Identifiers
have from 1 to 32 characters:
'a'..'z', 'A'..'Z', '0'..'9', '_'
Identifiers should start with a letter: a1 is legal, 1a is
not (can also start with underscore _
C++ is case sensitive. A and a are different.
Which
a)
b)
c)
d)
of these are valid identifiers?
abc
m/h
main
double
e) ABC
i) a_1
f) 25or6to4
j) student Number
g) 1_time
k) string
h) first name
l) ______
2.1.5 Constants
2-15
floating-point constants
1.234
-12.5
0.0
0.
.0
1e10
string constants
"character between double quotes"
integer constants
-1
0
1
-32768
+32767
character constants (see Chapter 7)
'A'
'b'
'\n'
'1'
0.1e-5
2-16
2.1.6 Comments
Example
comments
// on one line or
/*
between slash star and star slash
*/
Provide internal documentation
Helps us understand program that we must read-including our own.
Can be used as "pseudocode" within a program
and later changed into C++ or left as is to provide
documentation
2-17
2.2 Common Operations on
Objects
Common Operations
for many classes of objects
include these four
Declaration
Initialization
Assignment
Input
Output
Construct an object
or optionally initialize its state
Modify the state of an object
Modify the state of an object
Inspect the state of an object
2-18
Use
2.2.1 Object Constructions
default initial state:
class-name identifier;
double is garbage
-or-
class-name identifier , identifier , … , identifier ;
Allow client to supply initial state:
class-name identifier = initial-state ;
-or -
class-name identifier ( initial-state ) ;
-or -
class-name identifier = initial-state , identifier ( initial-state )
, … , identifier = initial-state ;
Examples Object
Constructions
2-19
Construct seven
double
string
double
double
objects
qualityPoints is undefined
credits = 15.5, qualityPoints;
firstName, lastName("Harrison");
x = 0.0, y = 0.0;
z; // garbage state (unknown)
Note: strings have the default value of the null
string "", which has 0 characters.
A double object has no default value--it's
garbage unless an initial value is supplied.
2-20
2.2.2 Output with cout
Programs
must communicate with users
This can be done with keyboard input
statements and screen output statements
A C++ statement is composed of several
components properly grouped together to
perform some operation
Here is the first statement used to display
constants and object state to the screen:
2-21
The
The cout statement
general form of a cout statement:
cout << expression-1 << expression-2 << expression-n ;
Example
cout << "Grade: " << courseGrade << endl;
2-22
When a cout statement is encountered, the
expressions are displayed on the screen in a manner
appropriate to the expression
New
What happens with cout?
Lines with endl
When encountered in a cout statement, endl generates
a new line on the monitor
To properly use cout and endl, your program must
have this code at the top of the file:
#include <iostream> // for cout and endl
using namespace std;
2-23
Active Learning:
Write the output generated by this program
#include <iostream> // for cout
using namespace std; // so we don’t need std::
int main()
{
double aDouble = 0.0;
cout << "12345678" << endl;
cout << (2.5 * 3) << (2*3) << endl;
cout << aDouble;
return 0;
}
Output?:
2-24
Certain
2.7.2 Assignment
objects have undefined state
double dunno, do_you;
cout << dunno << endl;
The
// Output? ______
programmer can set the state of objects with
assignment operations of this form:
object-name = expression ;
Examples:
dunno = 1.23;
do_you = dunno - 0.23;
2-25
Memory before and after
Object
Name
dunno
do_you
Old
State
?
?
Modified
State
1.23
1.0
The
expression must be a value that the object can
store (assignment compatible)
dunno = "Ohhh no, you can't do that"; // <-Error
string s;
s = 1.23; // <-Error
Active Learning:
2-26
Write the values for bill and name:
double bill;
string name;
bill
bill
name
name
=
=
=
=
10.00;
bill + (0.06 * bill);
"Bee Bop";
"Hip Hop";
// bill is
___________?
// name is now ________?
2-27
2.2.3 Input with cin
General
forms :
cin >> object-1 ;
-or-
cin >> object-1 >> object-2 >> object-n ;
Example: cin >> test1;
When a cin statement is encountered
the program pauses for user input.
the characters typed by the user are processed
the object's state is changed to the value of the input
2-28
Input is separated with blanks,
tabs, and newlines
#include <iostream> // for cout, cin, endl
#include <string>
// for class string
using namespace std;
int main()
{
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello " << name;
return 0;
}
Dialogue when the user enters Kim McPhee
McPhee is still waiting to be processed by a non-existent future cin statement
Enter your name:
Hello Kim
Kim McPhee
2-29
2.3 Arithmetic Expressions
Arithmetic expressions consist of operators
such as + - / * % and operands such as 1.0,
payRate, and hoursWorked
Example expression used in an assignment:
grossPay = payRate * hoursWorked;
Another example expression:
(40*payRate) + 1.5*payRate*(hoursWorked-40)
The previous expression has how many
operators ?___ ?
operands ?___ ?
2-30
Arithmetic Expressions
An arithmetic expression can be written in these forms
or
or
or
or
or
or
a numeric object
a numeric constant
expression + expression
expression - expression
expression * expression
expression / expression
( expression )
x
100 or 99.5
1.0 + x
2.5 - x
2*x
x / 2.0
(1 + 2.0)
2-31
Precedence of Arithmetic
Operators
Expressions with
more than one operator
require some sort of precedence rules:
*
-
/
+
What is
// evaluated left to right order
// evaluated left to right order
2.0 + 4.0 - 6.0 * 8.0 / 6.0
____?
Use
(parentheses ) for readability or to
intentionally alter an expression:
double C;
double F = 212.0;
C = 5.0 / 9.0 * (F - 32);
// C = _____?
2-32
Active Learning: Write the
complete dialogue with input 2.3
5.0 2.0
#include <iostream> // for cin, cout, and endl
using namespace std;
int main()
{ // Declare Objects
double x, y, z, average;
// Prompt for and get input from the user
cout << "Enter three numbers: ";
cin >> x >> y >> z;
// Process:
average = (x + y + z) / 3.0;
// Output:
cout << "Average: " << average << endl;
return 0;
}
2-33
2.4 const objects
It
is sometimes convenient to have objects that
cannot have altered state
const class-name identifier = expression ; // use
-orconst class-name identifier ( expression ) ;
this form
Examples:
const double PI = 3.1415926;
const string ERROR_MESSAGE = "Nooooooo";
Errors:
PI = 9.8;
cin >> ERROR_MESSAGE;
2-34
2.5 Another Algorithm Pattern:
Prompt then Input
The
Input/Process/Output programming
pattern can be used to help design many
programs in the first several chapters
The Prompt then Input pattern also occurs
frequently
The user is often asked to enter data
The programmer must make sure the user is told
what to enter
2-35
Prompt then Input Pattern
Pa tte rn
Prompt then Input
Pro b le m
O u tlin e
The user must enter something
1) Prompt the user for input
2) Obtain the input
Code
Exa m p le
cout << "Enter your first name: " ;
cin >> firstName ;
2-36
Examples
Instances
of the Prompt then Input pattern:
cout << "Enter your first name: ";
cin >> firstName;
cout << "Enter accumulated credits: ";
cin >> credits;
Write code that gets the current temperature from the user
? ________ ?
Optional Demo average3.cpp
to see prompt then input used three times