3-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.
3-2Chapter 3Chapter 3Function Calls and HeadingsFunction Calls and Headings
GoalsGoals Evaluate a few math functionsEvaluate a few math functions Use arguments in functions callsUse arguments in functions calls Appreciate why programmers divide software into Appreciate why programmers divide software into
functionsfunctions Use integer objectsUse integer objects Use quotient remainder divisionUse quotient remainder division Show the general categories of errors with examplesShow the general categories of errors with examples
– Exercises and Programming Projects to reinforce use of existing Exercises and Programming Projects to reinforce use of existing functions functions
3-3 3.1 cmath functions3.1 cmath functions
C++ defines a large collection of standard C++ defines a large collection of standard math and trig functions such asmath and trig functions such as
sqrt(x) sqrt(x) // return the square root of x// return the square root of x fabs(x) fabs(x) // return the absolute value of x// return the absolute value of x
Functions are called by specifying the Functions are called by specifying the function name followed by the argument(s) in function name followed by the argument(s) in parentheses:parentheses:
cout << sqrt(4.0) << " " << fabs(-2.34);cout << sqrt(4.0) << " " << fabs(-2.34); Output Output ?___________ ? ?___________ ?
3-4 The pow functionThe pow function
The The powpow function returns the first argument to function returns the first argument to the second argument's powerthe second argument's power
For example, pow(2.0, 3.0) returns 2 to the 3rd For example, pow(2.0, 3.0) returns 2 to the 3rd power (2power (233 = 8.0) = 8.0)
double base, power;double base, power; base = 2.0;base = 2.0; power = 4.0;power = 4.0; cout << pow(base, power); cout << pow(base, power); // Output ______?// Output ______?
The following table shows some of the other The following table shows some of the other cmath functionscmath functions
3-5 Some cmath functionsSome cmath functions
3-6 Evaluate some Function CallsEvaluate some Function Calls
Different arguments cause different return Different arguments cause different return valuesvalues
ceil(0.1) ______ ? sqrt(16.0) _____ ?ceil(0.1) ______ ? sqrt(16.0) _____ ? ceil(1.1) ______ ? sqrt(sqrt(16)) _____ ?ceil(1.1) ______ ? sqrt(sqrt(16)) _____ ? pow(2.0, 3)______ ? fabs(-1.2) _____ ?pow(2.0, 3)______ ? fabs(-1.2) _____ ? sqrt(4.0) ______ ? floor(3.99) _____ ?sqrt(4.0) ______ ? floor(3.99) _____ ?
To use mathematical functions, you mustTo use mathematical functions, you must #include <cmath>#include <cmath>
Optional DemoOptional Demo mathfuns.cppmathfuns.cpp
3-7 3.2 The rounding example3.2 The rounding example
Problem:Problem: Write a program that rounds any number to a Write a program that rounds any number to a given number of decimal places.given number of decimal places.
Code that will round x to n decimal places uses Code that will round x to n decimal places uses powpow and and floorfloor::
x = 456.789; x = 456.789;
n = 2;n = 2;
x = x * pow(10, n);x = x * pow(10, n); // x ________ ?// x ________ ?
x = x + 0.5;x = x + 0.5; // x ________ ?// x ________ ?
x = floor(x);x = floor(x); // x ________ ?// x ________ ?
x = x / pow(10, n);x = x / pow(10, n); // x ________ ?// x ________ ?
3-83.3 Calling Documented 3.3 Calling Documented FunctionsFunctions
C++ has many functions availableC++ has many functions available standard functions such asstandard functions such as
sqrt pow string::length ostream::widthsqrt pow string::length ostream::width
programmer-defined functions written for programmer-defined functions written for specific applicationsspecific applications
functions that are members of off-the-shelf functions that are members of off-the-shelf classes: bankAccount::withdraw classes: bankAccount::withdraw
Functions are more easily understood when Functions are more easily understood when documented with comments documented with comments see next slidesee next slide
3-93.3.1 Preconditions and 3.3.1 Preconditions and PostconditionsPostconditions
Preconditions and postconditions are C++ Preconditions and postconditions are C++ comments that represents a contract between the comments that represents a contract between the implementers of a function and the user (client) of implementers of a function and the user (client) of that functionthat function
PreconditionsPreconditions: What the function requires.: What the function requires. PostconditionsPostconditions: What the function will do if the : What the function will do if the
preconditions are met.preconditions are met.
3-10Pre: and Post: conditions Pre: and Post: conditions (cont.)(cont.)
The preconditions are the circumstances that The preconditions are the circumstances that must be true in order for the function to must be true in order for the function to successfully fulfill the postconditionssuccessfully fulfill the postconditions
Example Example Precondition abbreviates to Precondition abbreviates to pre:pre:
double sqrt(double x)double sqrt(double x) // pre: x >= 0// pre: x >= 0 // post: Returns square root of x // post: Returns square root of x
Note: On most systems now, sqrt(-1.0) returns not a Note: On most systems now, sqrt(-1.0) returns not a number number NaNNaN or infinity or infinity -1.#IND-1.#IND
3-11 3.3.2 Function Headings3.3.2 Function Headings
A A function heading function heading is the complete declaration is the complete declaration of a function without its implementation of a function without its implementation (sometimes called the function's (sometimes called the function's signature).signature).
For example, this signature tells us how to call For example, this signature tells us how to call the function, but not how it works:the function, but not how it works:
double sqrt(double x)double sqrt(double x)
3-12 Function headings Function headings continuedcontinued
General form of a function heading:General form of a function heading:
return-typereturn-type function-namefunction-name (( parameter-listparameter-list )) thethe return-type return-type is any C++ class is any C++ class e.g.e.g. doubledouble oror stringstring
the the function-namefunction-name is any valid identifier is any valid identifier the the parameter-listparameter-list is a set of 0 or more parameters is a set of 0 or more parameters
General form for declaring parameters:General form for declaring parameters:class-name identifier class-name identifier class-name class-name && identifieridentifierdouble f(double x) void init(grid& g)double f(double x) void init(grid& g)
int max(int j, int k) int roots(double a, int max(int j, int k) int roots(double a,
double b, double c,double b, double c,
double& r1, double& r2)double& r1, double& r2)
Note: No Semicolon!
3-133.3.3 Argument/Parameter 3.3.3 Argument/Parameter AssociationsAssociations
Example call to f (above) shows that arguments Example call to f (above) shows that arguments match parameters by positionmatch parameters by position
double f(double x, double y)double f(double x, double y) // post: return x-y;// post: return x-y;
cout << f(3.0, -5.32);cout << f(3.0, -5.32);
The value of the first argument is copied to the first The value of the first argument is copied to the first parameter, the value of the second argument to the parameter, the value of the second argument to the second parameter, and so on.second parameter, and so on.
Like these two assignments:Like these two assignments: x = 3.0; x = 3.0; y = -5.32;y = -5.32;
3-14 Active Learning Active Learning
Write the output generated by these function calls:Write the output generated by these function calls: cout << f( 1.0, 1.0) << endl; cout << f( 1.0, 1.0) << endl; // _____// _____
cout << f( 1.0, 1.5) << endl; cout << f( 1.0, 1.5) << endl; // _____// _____
cout << f( 3.0, 0.5) << endl; cout << f( 3.0, 0.5) << endl; // _____// _____
cout << f(-1.0, 1.0) << endl; cout << f(-1.0, 1.0) << endl; // _____// _____
Write valid for each valid function call or explain why Write valid for each valid function call or explain why the code is incorrect.the code is incorrect.
a.a. f(1.0) f(1.0) d. d. f(1, 2) f(1, 2)
b. b. f("Bob", "Sue")f("Bob", "Sue") e. e. f(1, 2, 3) f(1, 2, 3)
c. c. f(-0.001, +4.5)f(-0.001, +4.5) f. f. f((1, 2) f((1, 2)
3-15 SummarySummary
Documented function headings provide the Documented function headings provide the following information:following information:
The type (or class) of value returned by the function.The type (or class) of value returned by the function. The function name.The function name. The number of arguments to use in a call.The number of arguments to use in a call. The type (class) of arguments required in the function The type (class) of arguments required in the function
call.call. Pre- and post-conditions tell us what the function will Pre- and post-conditions tell us what the function will
do if the preconditions are met.do if the preconditions are met.
3-16
Given the following function heading:Given the following function heading: double larger(double a, double b)double larger(double a, double b) // post: return the larger of a and b// post: return the larger of a and b
What type (class) of value is returned when larger is What type (class) of value is returned when larger is called _______ ?called _______ ?
What is the function name _______ ?What is the function name _______ ? How many arguments are required to call the function How many arguments are required to call the function
___________ ?___________ ? What class of arguments are required in the function What class of arguments are required in the function
call __________ ?call __________ ?
Active Learning Active Learning
3-17
Given the following function heading :Given the following function heading : double foo(double a, double b)double foo(double a, double b) // pre: a is not equal to b // pre: a is not equal to b // post: Return the lesser of a and b// post: Return the lesser of a and b
write the return value of these function calls:write the return value of these function calls: foo( 3.0, 6.0) ________foo( 3.0, 6.0) ________ foo( 6.0, 3.0) ________foo( 6.0, 3.0) ________ foo(-3.0, -6.0) ________foo(-3.0, -6.0) ________ foo(-3.0, -3.0) ________foo(-3.0, -3.0) ________
Active Learning Active Learning
3-18 3.43.4 int Arithmeticint Arithmetic
int object are similar to double, except they int object are similar to double, except they store whole numbers (integers) onlystore whole numbers (integers) only
int anInt;int anInt;
anInt = 123;anInt = 123; // anInt ________ ?// anInt ________ ?
anInt = 1.99;anInt = 1.99; // anInt ________ ?// anInt ________ ?
Division with integer constants and int objects Division with integer constants and int objects is also a different operationis also a different operation
anInt = 9 / 2;anInt = 9 / 2; // anInt ________ ?// anInt ________ ?
anInt = anInt / 5;anInt = anInt / 5; // anInt ________ ?// anInt ________ ?
3-19 The integer % operationThe integer % operation
C++ has the %operator that returns the C++ has the %operator that returns the remainder in integer divisionremainder in integer division
anInt = 9 % 2;anInt = 9 % 2; // anInt ________// anInt ________ ??
anInt = 101 % 2;anInt = 101 % 2; // anInt ________ ?// anInt ________ ?
anInt = 5 % 11;anInt = 5 % 11; // anInt ________ ?// anInt ________ ?
anInt = 361 % 60; anInt = 361 % 60; // anInt ________ ?// anInt ________ ?
int quarter;int quarter;
quarter = 79 % 50 / 25; quarter = 79 % 50 / 25; // quarter ___ ?// quarter ___ ?
quarter = 57 % 50 / 25; quarter = 57 % 50 / 25; // quarter ___ ?// quarter ___ ?
3-20 Integer quotient/remainderInteger quotient/remainder
Some formulas using quotient and remainderSome formulas using quotient and remainder int total, hours, minutes, seconds;int total, hours, minutes, seconds; total = 3726; total = 3726; // Write formulas to compute:// Write formulas to compute:
hours = ______________________________ ;hours = ______________________________ ;
minutes = _______________________________ ;minutes = _______________________________ ;
seconds = _______________________________ ;seconds = _______________________________ ;
Also note: For int / float, first promote the integer Also note: For int / float, first promote the integer operand it's floating point equivalent operand it's floating point equivalent
ExampleExample 5 / 2.0 = _____ ?5 / 2.0 = _____ ?
3-21 3.5 Implementation Errors3.5 Implementation Errors
Categories of errors and warnings are detected Categories of errors and warnings are detected during program implementation during program implementation
1. Compiletime errors1. Compiletime errors2. Warning2. Warning3. Linktime errors3. Linktime errors4. Runtime errors (exceptions)4. Runtime errors (exceptions)5. Intent errors5. Intent errors
You've probably experienced many errors, You've probably experienced many errors, especially those detected at compiletimeespecially those detected at compiletime
3-22
#include <iostream>int main(){ double x(0.0); cout << "x? "; cin >> x; return 0;}
Compiler
010101010110010100101010010010101001001010100101010010
Machine Code
Linker
Machine Code
Machine Code
Machine Code
Executable
Program
iostream
Machine CodeSource Code
Compiling and Linking to Create Compiling and Linking to Create an Executable Programan Executable Program
3-233.5.1 Errors Detected at 3.5.1 Errors Detected at CompiletimeCompiletime
Generated while the compiler is processing the Generated while the compiler is processing the source codesource code
Compiler reports violations of syntax rules. For Compiler reports violations of syntax rules. For example, given these general forms:example, given these general forms:
object-declarationobject-declaration
class-name identifier-list class-name identifier-list ;; identifier-list: identifier-list:
identifieridentifier -or--or-
identifier-1, identifier-2, identifier-3, ..., identifier-nidentifier-1, identifier-2, identifier-3, ..., identifier-n
3-24 Pretend you are the compilerPretend you are the compiler
What should the compiler do when it is What should the compiler do when it is processing this source code?processing this source code?
int student Number;int student Number;
// ...// ...
cin >> student;cin >> student;
3-253.5.2 Warnings generated by 3.5.2 Warnings generated by the compilerthe compiler
The compiler generates warnings when it The compiler generates warnings when it discovers something that is legal, but discovers something that is legal, but potentially problematicpotentially problematic
Example:Example: double x, y, z ;double x, y, z ; y = 2 * x ;y = 2 * x ; // Warning: x used before being intialized// Warning: x used before being intialized // Warning: z declared but never used// Warning: z declared but never used
3-26 3.5.3 Linktime Errors 3.5.3 Linktime Errors
Errors that occur while trying to put together Errors that occur while trying to put together (link) an executable program(link) an executable program
For example, we must always have function For example, we must always have function main (Main or MAIN won't do).main (Main or MAIN won't do).
Optional Demo: linkerr.cpp
3-27 3.5.4 Runtime Errors3.5.4 Runtime Errors
Errors that occur at runtime, that is, while the Errors that occur at runtime, that is, while the program is runningprogram is running
Examples: Invalid numeric input, division by 0 Examples: Invalid numeric input, division by 0 (on older compilers), picking up a "cookie" that is (on older compilers), picking up a "cookie" that is not therenot there
Some systems return infinity orSome systems return infinity or NAN NAN (Not A Number) (Not A Number) or or -1.#IND-1.#IND this is not really a runtime errorthis is not really a runtime error
Some terminate the program prematurelySome terminate the program prematurely
Optional Demo: runerr.cpp
3-28 3.5.5 Intent Errors3.5.5 Intent Errors
When the program does what you typed, not When the program does what you typed, not what you intendedwhat you intended
Imagine this codeImagine this code cout << "Enter sum: ";cout << "Enter sum: "; cin >> n;cin >> n; cout << " Enter n: ";cout << " Enter n: "; cin >> sum;cin >> sum; average = sum / n;average = sum / n;
Whose responsibility is it to catch this error __ ? Whose responsibility is it to catch this error __ ?
3-293.5.6 When the software doesn't 3.5.6 When the software doesn't match the specificationmatch the specification
If none of the preceding errors occur, the program If none of the preceding errors occur, the program may still not be rightmay still not be right
The working program may not match the The working program may not match the specification because either specification because either
The programmers did not match, or understand the The programmers did not match, or understand the problem statementproblem statement
The problem statement may have been incorrectThe problem statement may have been incorrect Someone may have changed the problem statementSomeone may have changed the problem statement