2-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...
-
Upload
harvey-snow -
Category
Documents
-
view
222 -
download
0
Transcript of 2-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...
2-1
Computing Fundamentals with C++Computing Fundamentals with C++Object-Oriented Programming and Design, 2nd EditionObject-Oriented Programming and Design, 2nd Edition
Rick MercerRick Mercer
Franklin, Beedle & Associates, 1999Franklin, Beedle & Associates, 1999
ISBN 1-887902-36-8ISBN 1-887902-36-8
Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Fundamentals with C++, Computing Fundamentals with C++, Object-Oriented Programming and Design Object-Oriented Programming and Design by Rick Mercer are welcome to use this by Rick Mercer are welcome to use this
presentation as long as this copyright notice remains intact.presentation as long as this copyright notice remains intact.
2-2Chapter 2Chapter 2ImplementationImplementation
Chapter ObjectivesChapter Objectives Understand how to reuse existing code in your Understand how to reuse existing code in your
programs programs with #includewith #include
Obtain input data from the user and display Obtain input data from the user and display information to the user information to the user with cin and coutwith cin and cout
Evaluate and create arithmetic expressions Evaluate and create arithmetic expressions 3*x3*x
Understand operations common to many objects Understand operations common to many objects such as int, double, and string: such as int, double, and string: Construction, Output, Assignment, and InputConstruction, Output, Assignment, and Input
– Exercises and Programming Projects to reinforce implementing Exercises and Programming Projects to reinforce implementing simple programssimple programs
2-32.1 The C++ Programming 2.1 The C++ Programming Language: A StartLanguage: A Start
A C++ program is a sequence of characters A C++ program is a sequence of characters created with a text editor and stored as a file.created with a text editor and stored as a file.
this is the source codethis is the source code
The file name have specific endings:The file name have specific endings: UNIX: UNIX: .cc.cc or or .C.C DOS or MS-Windows: DOS or MS-Windows: .cpp.cpp MacOS: MacOS: .cp .cp or or .cpp.cpp
2-4 General FormsGeneral Forms
General forms provide information to create General forms provide information to create syntactically correct programs syntactically correct programs
Anything in yellow boldface must be written Anything in yellow boldface must be written exactly as shown (exactly as shown (cout <<cout << for example) for example)
Anything inAnything in italic italic represents something that must represents something that must be supplied by the user be supplied by the user
The italicized portions are defined elsewhereThe italicized portions are defined elsewhere
2-5 General Form: A programGeneral Form: A program
// Comment #include-directive(s)using namespace std;int main(){ object-initializations statement(s) return 0;}
2-6 Example C++ programExample C++ program
// This C++ program gets a number from the // user and displays that value squared #include <iostream> // for cout cin endlusing namespace std;
int main(){ double x = 0.0;
cout << "Enter a number: "; cin >> x; cout << "x squared: " << (x * x) << endl;
return 0; }
2-7 The compilerThe compiler
The compiler The compiler reads source code in a character by character reads source code in a character by character
fashionfashion reports errors whenever possiblereports errors whenever possible reports warnings to help avoid errorsreports warnings to help avoid errors conceptually replaces #includes with the source conceptually replaces #includes with the source
code of the #included filecode of the #included file
2-8 #include directives#include directives
General form: General form: #include-directive#include-directive#include #include <<include-fileinclude-file>>
-or--or-
#include "#include "include-fileinclude-file"" < >< > causes a search of the system folder(s)causes a search of the system folder(s)
these files should be found automatically.these files should be found automatically. The form with The form with " "" " first searches the working folder first searches the working folder
before searching the system folder(s)before searching the system folder(s) the " " indicates an author supplied file name that you the " " indicates an author supplied file name that you
may need in your working folder.may need in your working folder.
2-92.1.1 The smallest pieces of a 2.1.1 The smallest pieces of a C++ ProgramC++ Program
A token is the smallest recognizable unit in a A token is the smallest recognizable unit in a programming languageprogramming language
There are four types of tokens:There are four types of tokens: special symbolsspecial symbols keywordskeywords identifiersidentifiers constantsconstants
2-10 A "tokenized program"A "tokenized program"
Each color represents either a different token Each color represents either a different token special special
symbolsymbol reserved word reserved word identifieridentifier constantconstant commentcomment (gray), or (gray), or #include directive#include directive (cyan) (cyan)
// Comment: This is a complete C++ program// Comment: This is a complete C++ program #include <iostream> #include <iostream> using namespace using namespace stdstd;; int main main()() { { coutcout << << "Hello World!""Hello World!";; return 00; ; } }
2-11 2.1.2 Special Symbols2.1.2 Special Symbols
One or two character sequences (no spaces)One or two character sequences (no spaces)
// < > ( ) { << ; } !=// < > ( ) { << ; } !=
Some special symbols mean different things in Some special symbols mean different things in different contextsdifferent contexts
2-12 2.1.3 Keywords2.1.3 Keywords
Word like tokens with a pre-defined meaning Word like tokens with a pre-defined meaning that can't be changed (reserved)that can't be changed (reserved)
double int double int
Some of the keywords in the text :Some of the keywords in the text : bool class for operator typedef bool class for operator typedef case do if return voidcase do if return void char else long switch whilechar else long switch while
2-13 2.1.4 Identifiers2.1.4 Identifiers
There are some standard (must be available There are some standard (must be available wth the C++ compiler) identifiers: wth the C++ compiler) identifiers:
endl sqrt string width stdendl sqrt string width std
The programmer can make up new identifiers The programmer can make up new identifiers (programmer-defined) (programmer-defined)
test1 x1 aNumber MAXIMUM A_1test1 x1 aNumber MAXIMUM A_1
Note: Note: mainmain is a is a programmer-defined programmer-defined identifier, identifier, coutcout is a is a standardstandard identifier identifier
2-14 Active LearningActive Learning
Identifiers have from 1 to 32 characters: Identifiers have from 1 to 32 characters: 'a'..'z', 'A'..'Z', '0'..'9', '_''a'..'z', 'A'..'Z', '0'..'9', '_'
Identifiers should start with a letter: Identifiers should start with a letter: a1a1 is legal, is legal, 1a1a is is not (can also start with underscore not (can also start with underscore __
C++ is case sensitive. C++ is case sensitive. AA and and aa are different. are different.
Which of these are valid identifiers?Which of these are valid identifiers? a) abca) abc e) ABC e) ABC i) a_1 i) a_1 b) m/hb) m/h f) 25or6to4 f) 25or6to4 j) student Number j) student Number c) main g) 1_time k) stringc) main g) 1_time k) string d) double h) first name l) ______ d) double h) first name l) ______
2-15 2.1.5 Constants2.1.5 Constants
floating-point constantsfloating-point constants1.234 -12.5 0.0 0. .0 1e10 0.1e-51.234 -12.5 0.0 0. .0 1e10 0.1e-5
string constantsstring constants"character between double quotes""character between double quotes"
integer constantsinteger constants -1 0 1 -32768 +32767-1 0 1 -32768 +32767
character constants (see Chapter 7)character constants (see Chapter 7) 'A' 'b' '\n' '1''A' 'b' '\n' '1'
2-16 2.1.6 Comments2.1.6 Comments
Example commentsExample comments // on one line or // on one line or /* /* between slash star and star slashbetween slash star and star slash */*/
Provide internal documentationProvide internal documentation Helps us understand program that we must read--Helps us understand program that we must read--
including our own.including our own. Can be used as "pseudocode" within a program Can be used as "pseudocode" within a program
and later changed into C++ or left as is to provide and later changed into C++ or left as is to provide documentation documentation
2-172.2 Common Operations on 2.2 Common Operations on ObjectsObjects
Common Operations for many classes of objects Common Operations for many classes of objects include these fourinclude these four
Declaration Declaration Construct an objectConstruct an objectInitializationInitialization or optionally initialize its state or optionally initialize its state
AssignmentAssignment Modify the state of an objectModify the state of an object InputInput Modify the state of an objectModify the state of an object OutputOutput Inspect the state of an objectInspect the state of an object
2-18 2.2.1 Object Constructions2.2.1 Object Constructions
Use default initial state: Use default initial state: double is garbagedouble is garbage
class-name identifierclass-name identifier;-or--or-
class-name identifierclass-name identifier , identifier identifier , … , identifier identifier ;
Allow client to supply initial state:Allow client to supply initial state: class-name identifierclass-name identifier = initial-state initial-state ;
-or --or - class-name identifierclass-name identifier ( initial-state initial-state ) ; -or --or - class-name identifierclass-name identifier = initial-state initial-state , identifieridentifier ( initial-stateinitial-state ) , … … , identifier identifier = initial-stateinitial-state ;
2-19Examples Object Examples Object ConstructionsConstructions
Construct seven objectsConstruct seven objects qualityPoints is undefinedqualityPoints is undefined
double credits = 15.5, qualityPoints;double credits = 15.5, qualityPoints; string firstName, lastName("Harrison");string firstName, lastName("Harrison"); double x = 0.0, y = 0.0;double x = 0.0, y = 0.0; double z; double z; // garbage state (unknown)// garbage state (unknown)
Note: strings have the default value of the null Note: strings have the default value of the null string string """", which has 0 characters., which has 0 characters.
A A doubledouble object has no default value--it's object has no default value--it's garbage unless an initial value is supplied.garbage unless an initial value is supplied.
2-20 2.2.2 Output with 2.2.2 Output with coutcout
Programs must communicate with usersPrograms must communicate with users This can be done with keyboard input This can be done with keyboard input
statements and screen output statementsstatements and screen output statements A C++ statement is composed of several A C++ statement is composed of several
components properly grouped together to components properly grouped together to perform some operationperform some operation
Here is the first statement used to display Here is the first statement used to display constants and object state to the screen:constants and object state to the screen:
2-21 The cout statementThe cout statement
The general form of a cout statement: The general form of a cout statement:
cout <<cout << expression-1expression-1 <<<< expression-2expression-2 <<<< expression-n expression-n ; ;
Example Example
cout << "Grade: " << courseGrade << endl;cout << "Grade: " << courseGrade << endl;
2-22 What happens with cout?What happens with cout?
When a cout statement is encountered, the When a cout statement is encountered, the expressions are displayed on the screen in a manner expressions are displayed on the screen in a manner appropriate to the expressionappropriate to the expression
New Lines with endlNew Lines with endl When encountered in a cout statement, endl generates When encountered in a cout statement, endl generates
a new line on the monitora new line on the monitor To properly use cout and endl, your program must To properly use cout and endl, your program must
have this code at the top of the file:have this code at the top of the file: #include <iostream>#include <iostream> // for cout and endl// for cout and endl
using namespace std;using namespace std;
2-23 Active Learning: Active Learning: Write the output generated by this programWrite the output generated by this program
#include <iostream> #include <iostream> // for cout// for coutusing namespace std; using namespace std; // so we don’t need std::// so we don’t need std::
int main()int main(){{ double aDouble = 0.0;double aDouble = 0.0; cout << "12345678" << endl;cout << "12345678" << endl; cout << (2.5 * 3) << (2*3) << endl;cout << (2.5 * 3) << (2*3) << endl; cout << aDouble;cout << aDouble; return 0;return 0;}}Output?:Output?:
2-24 2.7.2 Assignment2.7.2 Assignment
Certain objects have undefined stateCertain objects have undefined state double dunno, do_you;double dunno, do_you; cout << dunno << endl; cout << dunno << endl; // Output? ______// Output? ______
The programmer can set the state of objects with The programmer can set the state of objects with assignment operations of this form:assignment operations of this form:
object-nameobject-name == expressionexpression ; ; Examples:Examples: dunno = 1.23;dunno = 1.23; do_you = dunno - 0.23;do_you = dunno - 0.23;
2-25 Memory before and afterMemory before and after
Object Object Old Old Modified Modified NameName StateState StateState
dunnodunno ?? 1.231.23
do_youdo_you ?? 1.01.0
The expression must be a value that the object can The expression must be a value that the object can store (assignment compatible)store (assignment compatible)
dunno = "Ohhh no, you can't do that"; dunno = "Ohhh no, you can't do that"; // <-Error// <-Error string s; string s; s = 1.23; s = 1.23; // <-Error// <-Error
2-26 Active Learning:Active Learning:
Write the values for bill and name:Write the values for bill and name: double bill;double bill; string name;string name; bill = 10.00;bill = 10.00; bill = bill + (0.06 * bill); bill = bill + (0.06 * bill); name = "Bee Bop"; name = "Bee Bop"; name = "Hip Hop";name = "Hip Hop";
// bill is ___________?// bill is ___________?
// name is now ________?// name is now ________?
2-27 2.2.3 Input with 2.2.3 Input with cincin
General forms :General forms :
cin >>cin >> object-1object-1 ;; -or--or-
cin >> cin >> object-1 object-1 >> >> object-2 object-2 >> >> object-nobject-n ;; Example: Example: cin >> test1; cin >> test1;
When a cin statement is encounteredWhen a cin statement is encountered the program pauses for user input.the program pauses for user input. the characters typed by the user are processedthe characters typed by the user are processed the object's state is changed to the value of the inputthe object's state is changed to the value of the input
2-28Input is separated with blanks, Input is separated with blanks, tabs, and newlinestabs, and newlines
#include <iostream> #include <iostream> // for cout, cin, endl// for cout, cin, endl #include <string>#include <string> // for class string// for class string using namespace std;using namespace std; int main()int main() {{ string name;string name; cout << "Enter your name: ";cout << "Enter your name: "; cin >> name;cin >> name; cout << "Hello " << name;cout << "Hello " << name; return 0;return 0; }}
Dialogue when the user enters Kim McPhee Dialogue when the user enters Kim McPhee McPhee is still waiting to be processed by a non-existent future cin statementMcPhee is still waiting to be processed by a non-existent future cin statement
Enter your name: Enter your name: Kim McPheeKim McPhee Hello KimHello Kim
2-29 2.3 Arithmetic Expressions2.3 Arithmetic Expressions
Arithmetic expressions consist of Arithmetic expressions consist of operators such asoperators such as + - / * %+ - / * % and and operands such as operands such as 1.01.0,, payRatepayRate,, andand hoursWorkedhoursWorked
Example expression used in an Example expression used in an assignment:assignment:
grossPay = payRate * hoursWorked;grossPay = payRate * hoursWorked;
Another example expression:Another example expression: (40*payRate) + 1.5*payRate*(hoursWorked-40)(40*payRate) + 1.5*payRate*(hoursWorked-40)
The previous expression has how many The previous expression has how many operators ?___ ? operators ?___ ? operandsoperands ?___ ??___ ?
2-30 Arithmetic ExpressionsArithmetic Expressions
a numeric object a numeric object x xor a numeric constantor a numeric constant 100 or 99.5 100 or 99.5or expression + expressionor expression + expression 1.0 + x 1.0 + xor expression - expressionor expression - expression 2.5 - x 2.5 - x
or expression * expressionor expression * expression 2 * x 2 * xor expression / expressionor expression / expression x / 2.0 x / 2.0or ( expression )or ( expression ) (1 + 2.0) (1 + 2.0)
An arithmetic expression can be written in these forms
2-31Precedence of Arithmetic Precedence of Arithmetic OperatorsOperators
Expressions with more than one operator Expressions with more than one operator require some sort of precedence rules:require some sort of precedence rules:
* / * / // evaluated left to right order// evaluated left to right order - +- + // evaluated left to right order// evaluated left to right order
What isWhat is 2.0 + 4.0 - 6.0 * 8.0 / 6.02.0 + 4.0 - 6.0 * 8.0 / 6.0 ____? ____?
Use (parentheses ) for readability or to Use (parentheses ) for readability or to intentionally alter an expression:intentionally alter an expression:
double C;double C; double F = 212.0;double F = 212.0; C = 5.0 / 9.0 * (F - 32); C = 5.0 / 9.0 * (F - 32); // C = _____?// C = _____?
2-32
#include <iostream> #include <iostream> // for cin, cout, and endl// for cin, cout, and endlusing namespace std;using namespace std;int main() int main() { { // Declare Objects// Declare Objects double x, y, z, average;double x, y, z, average; // Prompt for and get input from the user// Prompt for and get input from the user cout << "Enter three numbers: "; cout << "Enter three numbers: "; cin >> x >> y >> z; cin >> x >> y >> z; // Process:// Process: average = (x + y + z) / 3.0; average = (x + y + z) / 3.0; // Output:// Output: cout << "Average: " << average << endl; cout << "Average: " << average << endl; return 0;return 0;}}
Active Learning: Write the Active Learning: Write the complete dialogue with input complete dialogue with input 2.3 2.3 5.0 2.05.0 2.0
2-33 2.42.4 const objectsconst objects
It is sometimes convenient to have objects that It is sometimes convenient to have objects that cannot have altered statecannot have altered state
const const class-name class-name identifieridentifier = = expressionexpression ; ; // use this form
-or- const const class-name class-name identifieridentifier ( ( expression expression )) ; ;
Examples:Examples: const double PI = 3.1415926;const double PI = 3.1415926; const string ERROR_MESSAGE = "Nooooooo";const string ERROR_MESSAGE = "Nooooooo";
Errors:Errors: PI = 9.8; PI = 9.8; cin >> ERROR_MESSAGE;cin >> ERROR_MESSAGE;
2-34 2.5 Another Algorithm Pattern: 2.5 Another Algorithm Pattern: Prompt then InputPrompt then Input
The The Input/Process/OutputInput/Process/Output programming programming pattern can be used to help design many pattern can be used to help design many programs in the first several chaptersprograms in the first several chapters
The The Prompt then InputPrompt then Input pattern also occurs pattern also occurs frequentlyfrequently
The user is often asked to enter dataThe user is often asked to enter data The programmer must make sure the user is told The programmer must make sure the user is told
what to enterwhat to enter
2-35 Prompt then Input PatternPrompt then Input Pattern
Pa tte rn Prompt then Input
Pro b le m The user must enter somethingO utline 1) Prompt the user for input
2) Obtain the input
C o d eExa m p le
cout << "Enter your first name: " ;cin >> firstName ;
2-36 ExamplesExamples
Instances of the Instances of the Prompt then InputPrompt then Input pattern: pattern: cout << "Enter your first name: ";cout << "Enter your first name: "; cin >> firstName;cin >> firstName;
cout << "Enter accumulated credits: ";cout << "Enter accumulated credits: "; cin >> credits;cin >> credits;
Write code that gets the current temperature from the userWrite code that gets the current temperature from the user
? ________ ?? ________ ?
Optional Demo average3.cpp
to see prompt then input used three times