Download presentation
Presentation is loading. Please wait.
1
CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6
2
2/25/02 Program 3 questions –A heading of 90 could result in bearings of either N 90 E or S 90 E. Either is OK. Exam 2 - Mar 6 clearInput.cpp
3
Functions mathematical functions express a relationship between variables y = f(x) procedures use information given to them and perform some action functions provide a different kind of program flow
4
Functions we've seen already main is a function int main( void) {...} functions from math library z = sqrt( x);
5
Library Functions math.hcommon mathematical functions and constants ctype.hchar functions: tolower, isdigit, … stdlib.hutility functions string.hchar array functions - we'll see this later
6
user-defined functions when libraries don't provide what you need, write your own When do you need a function? –something that is done several times in your program –something that you want to do in different programs –a long and/or complicated series of operations that make the flow of the program difficult to follow
7
Function as Black Box means of hiding details can use them without knowing what is inside (details of how they work) output = function( input1, input2) arguments (input1 and input2) provide information to the program return value carries information back to calling function
8
Writing a function prototype –a template for calling the function used by the compiler to verify the function is being called correctly shows the user how to call the function definition –code that defines what the function does (and how) –executed when the program runs
9
function prototype The function prototype or declaration has the form returnType functionName( paramList); where: –returnType is the type of the value returned by the function –paramList is a comma separated list of zero or more parameter types
10
function definition The function definition has the form returnType functionName( paramList) { /* local variable declarations*/ /* code that defines what the function does*/ return someValue; } the first line (signature) must match the prototype exactly paramList must have types and names of parameters
11
Example - double to integer power prototype double power( double, int); definition double power( double x, int n) { double ans = 1; for (int j=0; j<n; j++) ans *= x; return ans; }
12
Using functions use a function by calling it x = sqrt( y); function call functionName( argList) argList is a comma separated list of values –must match the formal parameter list in type and number of values –values may be any expressions compatible with the type of the formal parameter –provides information the function needs to do its job
13
using functions, cont. can call a function anywhere that an expression of the type that the function returns can go variables passed to a function do NOT have to have the same name as the formal parameter –do you even know the name of the formal parameter for sqrt?
14
2/27/02 Program 3 due Friday Program 4 on the web Exam 2 - Wednesday Mar 6 office hours Thursday 9:30-10:30 labs will be unavailable Saturday afternoon
15
functions prototype returnType fnName( paramList); definition returnType fnName( paramList) { // function body return returnValue; } use var = fnName( argList);
16
functions with no arguments Functions do not have to have any arguments. example: rand from math.h – takes no input –returns a random number declared with either the keyword void or nothing in the argument list
17
Argument / Parameter List Correspondence –Functions can have more than 1 arg –Correspondence between Actual & Formal arguments Function call scale (3.0, z); Actual ArgumentFormal Argument 3.0x zn
18
return types function that needs to return information has a return type appropriate to the information being returned return statement is used to pass the information back to the calling function
19
types and functions Type of a value returned by a called function must be consistent with the type expected by the caller as identified in the prototype Type of an actual argument in a function call must be consistent with the type of its corresponding formal argument
20
void functions some functions don’t return a value –return type is void An example would be a function that prints its arguments out in a particular format. use return without any value following it to exit from the function function call is an independent statement –doThis( );
21
Type Conversion in function calls When you pass a variable to a function that is a different type than specified in the function declaration, the compiler will attempt to cast the variable to the appropriate type. This works for most pre-defined types but may not give what you expect. –Doubles will be truncated on conversion to an int.
22
Scope There are limits to where a variable is visible
23
3.6 Scope of Names Variable declared in a function has a local scope within the function Same for variables declared in the main Variable declared before main is global scope –Call anywhere in program Functions declared globally
24
Scope of Names Positional correspondence Type consistent is key because of positional correspondence –Argument types –Return types
25
Variable Scope Local Variables –Variables declared inside a function body are local to that function. –They cannot be seen outside the function. –The parameters of the function are also local variables Global variables –Variables that are declared outside of any function (including main). –They can be seen by all functions in the file in which they occur. –This is most useful for constants.
26
Order of Execution int main() { drawCircle(); drawTriangle(); drawIntersect(); return 0; } void drawCircle() { cout << “ * “ << endl; cout << “ * * “ << endl; }
27
Common errors –Re-declaring parameters inside function –stray code the only statements that are allowed outside of function bodies are declarations –semicolon after signature in function definition
28
3/1/02 CS department computer lab not availabe Saturday afternoon Program 3 Program 4 Exam 2
29
scope.cpp const int MAX = 100; double x; // global variable int p( double ); int k( int ); int main() { double m = 14.6; for (int x = 0; x < MAX; ++x) { int z= k( x ); if (z == 0) cout << x << endl; } cout << p(m) << endl; return 0; } int p( double k ) { x = k - 0.5; int i = k * 3; return i; } int k( int m ) { return (m % 10); }
30
Pass by value When you call a function, the function gets a value to associate with each parameter. A variable or expression passed to a function is evaluated and only the value is passed to the function. a variable passed to a function, that variable will not get modified by the function Pass by value is the default behavior for function parameters
31
Pass by reference pass the address of a variable instead of its value the function uses the original variable instead of a copy get a reference parameter by putting an & between the type and the name of a parameter in the function declaration reference argument must be a variable allows functions to return more than one value
32
Example - the swap function void swap( double & x, double & y) { double temp; temp = x; x = y; y = temp; }
33
function overloading can define multiple functions with the same name –signatures must be different number and/or types of the arguments must differ. example : absolute value function –int abs( int n); –long abs( long l); –double abs( double d); arithmetic and input/output operators are overloaded for all the standard types not all languages allow you to do this
34
header files either a prototype or function definition must appear in the file before the function can be called header files may contain prototypes for a group of related functions math.h declares all the functions in the math library include a header file at the beginning of a program file allows the compiler to recognize the functions when they are called.
35
user-defined header files to include your own header files, use #include "myHeader.h" the compiler will look for the file myHeader.h in the same directory as your program
36
Function Advantages –Program team on large project –Simplify tasks –Each Function is a separate unit –Top-down approach –Procedural abstraction –Information hiding –Reuse (drawTriangle)
37
Top-down programming Design your programs by breaking them down into smaller parts. Do this the way you might organize a paper. Start with a broad outline and then fill in more detail at each level until you have something that is complete.
38
3.1 Building Programs from Existing Information –Reuse of existing programs –Develop program in stages –Compile along the way –Keep it small –Comments to describe actions
39
Figures /\ ------ | ------ ** /\ ------ /\
40
Top-Down Design and Structure Charts Original Problem Detailed subproblem s Level 0 Level 1 Level 2
41
Abstraction –Abstraction: Refers to the act of ignoring details to concentrate on essentials. Allows us to use complicated things with little effort (CD players, automobiles, computers ).
42
Programming Style Guidelines Use comments to specify preconditions and postconditions for functions Use comments in formal parameter list to explain what they are Function names should reflect the purpose of the function.
43
Preconditions & Postconditions –Comments that represents a contract between the implementor of a function and the user (client) of that function. –We'll look at two such comments: Precondition: What the function requires. Postcondition: What the function will do if the precondition is met.
44
Preconditions and Postconditions –The preconditions are the circumstances that must be true before the function can successfully fulfill the promised postconditions. –Example (Precondition abbreviates to PRE: double sqrt(double x); // PRE: x >= 0 // POST: Returns square root of argument X
45
Style Guidelines Don't use global variables. Don't reuse variable names in different parts of the program
46
Function Return Functions must return a value unless declared as void Form:return expression; Example:return x * y;
47
Common Programming Errors –Semicolon in Function Prototype (Declaration) –Inconsistencies in Number of Arguments Too few arguments in a call Too many arguments in a call Incorrect number of arguments in call Extra argument in call –Argument Mismatch Correct position (formal & actual params)
48
Common Programming Errors –Function Prototype & Definition Mismatches Both are the same except for the ; –Return Statements “Return value expected” “Function should return value” –Missing #include
49
Recursive functions functions that call themselves
50
factorial function Consider the factorial function: –n! = n * (n-1) * (n-2) *... *2 * 1 The prototype or declaration for this function would look like int factorial (int n); To calculate 6! you might call the function as follows: cout << factorial(6);
51
factorial definition int factorial (int n) { int product = 1; while (n>1) { product = product * n; n--; } return product; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.