Professional Documents
Culture Documents
Functions
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-1
Functions
Function Definition
A function is a single unit of computation Other words for function
Procedure Method Subprogram (that returns a value)
9/2010 John A. Rohr All Rights Reserved
JAR 3-2
Functions
Function Characterization
Accomplishes one thing May use other functions May produce a result Sequence of statements
JAR 3-3
Functions
Function Inputs
Called arguments or actual parameters Provides values for calculation Not needed by all functions
Display text Generate random number
JAR 3-4
Functions
Function Outputs
Called the return value Reports the results of the processing Not produced by all functions
Functions that perform an action only
JAR 3-5
Functions
Function Processing
Apply defined algorithm Use inputs Generate outputs
JAR 3-6
Functions
Function Example
Square Root Input: Value: Processing: Calculate square root Output: Square root of value:
9 3
JAR 3-7
Functions
Functions
Functions
Functions
JAR 3-11
Functions
Stream input and output Mathematical functions Some standard functions Character operations String capabilities
9/2010 John A. Rohr All Rights Reserved JAR 3-12
Functions
Stream input Stream output Stream precision Stream width Stream formatting
9/2010 John A. Rohr All Rights Reserved JAR 3-13
Functions
Square root Exponential (ex) Trigonometric sine Natural logarithm (ln) Floor
JAR 3-14
Functions
JAR 3-15
Functions
Functions
Functions
Function Call
Invokes the use of a function Specifies input arguments Return result value, if any
void function: Typed function: No return value Return value
Exactly one value Value is function type
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-18
Functions
Functions
Function Calls
void function: No value is returned typed function: One value is returned
Cannot be no value Cannot be more than one value Must be exactly one value
JAR 3-20
Functions
Type Conversion
Input arguments: For literals only
Will be converted if necessary and possible
Return values
Always returned as function type May be converted by an assignment statement after return
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-21
Functions
Function Example
root = sqrt(value);
Function name: Library location: Function action: Argument: Output:
CS 31: Introduction To CS I Topic 3: Functions
sqrt cmath Square root value (e.g. 25) Square root of value (e.g.5)
9/2010 John A. Rohr All Rights Reserved JAR 3-22
Functions
Literal Argument
root = sqrt(64);
Argument is an integer Parameter is a double Automatic upconversion of literal value from integer to double
JAR 3-23
Functions
Variable Argument
double value = 64; root = sqrt(value);
Argument is a double Argument must match type No conversion
JAR 3-24
Functions
Function Use
#include <cmath> #include <iostream> using namespace std; int main() { double value; double root;
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-25
Functions
Function Use
cout << "Enter a value:"; cin >> value; root = sqrt(value); cout << "The square root of \"" << value << "\" is \"" << root << "\"" << endl; return 0; }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-26
Functions
Function Execution
Enter a value:5.76 The square root of "5.76" is "2.4"
JAR 3-27
Functions
Exit Function
exit(integer);
Useful for stopping program early on error Takes integer value for identification
0 for special exit without error 1 or other for error exit
In library cstdlib
9/2010 John A. Rohr All Rights Reserved
JAR 3-28
Functions
Exit Use
#include <cstdlib> using namespace std; int main() { exit(0); }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-29
Functions
Time Function
now = time(0);
Returns current time Seconds since January 1, 1970 Useful to obtain a random number In library ctime
JAR 3-30
Functions
Time Use
#include <ctime> #include <iostream> using namespace std; int main() { cout << "Time:" << time(0) << endl; return 0; }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-31
Functions
Initialized by an integer seed number Will repeat same sequence for same seed Use random seed for random sequence
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-32
Functions
JAR 3-33
Functions
Functions
Functions
Scaling Example
Find result of throwing two dice Minimum value is 2 Maximum value is 12 count = (rand() % 11) + 2;
JAR 3-36
Functions
Functions
Functions
srand(time(0)); cout << "Random #:" << rand() << endl; return 0;
}
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-39
C++ Strings
string Library
#include <string> Provides C++ strings Not part of language itself Cannot be used without #include <string> One of many extensions to the language
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-40
C++ Strings
JAR 3-41
C++ Strings
C++ Strings
C++ Strings
C++ Strings
C++ Substring
string st = "Example text"; st.substr(8) (String "text") Part of the string Position can be any integer expression Must not begin past last character Result is string from position specified
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-45
C++ Strings
C++ Substring
string st = "Example text"; st.substr(2, 5) (String "ample") Part of the string Start can be any integer expression Length can be any integer expression Must not extend past last character Result string from position with length given
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-46
C++ Strings
JAR 3-47
C++ Strings
JAR 3-48
C++ Strings
C++ Strings
C++ Strings
C++ Strings
C++ Strings
C++ Strings
C++ Strings
C++ Strings
Digit Value
Characters are represented by integers The code is defined by the hardware Several code standards are used Each character has a different code
JAR 3-56
C++ Strings
C++ Strings
C++ Strings
Functions
Programmer-Defined Functions
Custom functions for specific uses Can be used to provide needed capability Can be used to modularize programs
Limit size of each module Organize in hierarchy of modules
JAR 3-60
Functions
Programmer-Defined Functions
Three required items
Function prototype (declaration) Function definition (code) Function call (use)
JAR 3-61
Functions
Functions
Function Name
Valid C++ identifier Uniquely identifies function Should indicate the action of the function Used to call the function
JAR 3-63
Functions
Function Parameters
Called parameters or formal parameters Are placeholders for arguments of calls Specify the type & number of parameters Specify the name of each parameter
Name not required in prototype Should be included for completeness Are required in the function header
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-64
Functions
Prototype Example
void aFunction(int p1, float p2, char p3);
Return type (None) Name (aFunction) Parameters
p1 p2 p3 (Integer) (Float) (Character)
Functions
Prototype Example
int anotherFunction(double value);
Return type (Integer) Name (anotherFunction) Parameter
value (Double)
Functions
Function Call
Same as for predefined functions
Function name Arguments
Must match the number of prototype parameters Must match the types prototype parameters Must be in the correct order Exception: Automatic upconversion
9/2010 John A. Rohr All Rights Reserved JAR 3-67
Functions
JAR 3-68
Functions
Function Definition
Not required for predefined functions
Provided by #include statement
JAR 3-69
Functions
Function Header
Same format as prototype
Specifies type, name, and parameters Does not have terminating semicolon Must have names for parameters
JAR 3-70
Functions
Function Body
Defines the action of the function Can include declarations Must include statements No return statement if void Must return value if not void
Value must match type of function Value is returned with a return statement
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-71
Functions
Functions
Functions
Function Return
Void functions
Return statement is optional If used, return cannot return any value Will return at final close brace if no return
Typed functions
Return statement is required Must return value of function type
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-74
Functions
Functions
Preconditions
Specify conditions which must be true when a function is called Guarantee correct results if all true Result not guaranteed if not all true Provide limits for arguments Use assert() to check (in cassert library)
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-76
Functions
Postconditions
Describes the value returned by a function Valid only if all preconditions are true
JAR 3-77
Functions
Pre/postcondition Example
For square root function Precondition
Argument is a real number >= 0
Postcondition
Result will be the square root of the argument
JAR 3-78
Functions
Pre/postcondition Example
For sin function (in cmath) Precondition
Argument is a real number in radians
Postcondition
Result will be the sine of the angle Result will be be in the range -1.0 to +1.0
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-79
Functions
Scope Rules
Define the valid range of a variable Minimize variable name conflicts Provide for global variables Provide for local variables
JAR 3-80
Functions
Local Variables
Define within a function Exist between opening and closing braces Do not exist outside the function except Static variables are preserved call to call Cannot conflict with local variables in other functions, even if the name is the same
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-81
Functions
Global Variables
Exist for an entire program Defined before the first function Good use is for global constants Use of global variables should be limited
Use function parameters to pass data Use function returns to return data
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-82
Functions
Blocks
Define scopes for variables Delimited by open and close brace Variables defined in block are local to the block in which they are defined Block may be an entire function
JAR 3-83
Functions
Nested Blocks
Blocks defined inside other blocks Resolves variables names Based on static structure Variable name redefined
New instance valid within new block Old instance revived when the new block ends
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-84
Functions
int var = 5;
{
float var = 2.4; cout << "Inner var:" << var << endl; (2.4)
}
(5)
JAR 3-85
Functions
Mathematical Induction
Concept
Mathematical induction is a method that can be used to prove numerical formulas. A proof requires two parts:
Show the formula is true for an initial value; Show that if the formula is true for some value, then it is also true for the next value.
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-87
Mathematical Induction
Example
The formula for the sum of the positive integers from 1 to n is as follows:
i=1
S i = n * (n + 1) / 2
JAR 3-88
Mathematical Induction
Proof
Step 1: Show that the sum of the integers 1 from 1 to 1 is 1: iS i = 1. =1
Proof:
i=1
S i = 1 * (1 + 1) / 2
= 1*2/2 = 1 which is true.
JAR 3-89
Mathematical Induction
Proof
Step 2: Proof:
Show that if the sum of the integers from 1 to m is m * (m + 1) / 2 then the sum of the integers from m to m+1 is (m + 1) * (m + 2) / 2.
m+1
i=1
Si=
1 * (1 + 1) / 2
m
Recursion
Concept
Recursion is a method where an algorithm is defined in terms of itself. There must be two cases in the algorithm:
A base case that does not use the algorithm; A recursive case that uses the algorithm.
JAR 3-91
Recursion
Example
The formula for the product of the positive integers from 1 to n is as follows:
i=1
pi = 1
n
for n = 0;
n-1 i=1
= n *
p for n > 0
JAR 3-92
Recursion
Recursion
Recursion vs.Iteration
Recursion
Function calls itself Must have base case Must be supported by the language used
Iteration
Function does not call itself Computation is based on a loop Does not require any special language support
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-94
Recursion
Recursion vs.Iteration
Recursion
More elegant Less efficient Not practical for production use
Iteration
More common More efficient Usually used instead of recursion
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-95
Recursion
UPDATES
More Examples
JAR 3-97