25-09-2013, 12:45 PM
Introduction to Functions
Functions.ppt (Size: 1.97 MB / Downloads: 26)
INTRODUCTION
A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.
This is called structured programming.
These parts are sometimes made into functions in C.
main() then uses these functions to solve the original problem.
C Functions
C allows the use of both internal (user-defined) and external functions.
External functions (e.g., abs, ceil, rand, sqrt, etc.) are usually grouped into specialized libraries (e.g., iostream, stdlib, math, etc.)
Using Predefined Functions
Math functions very plentiful
Found in library <cmath.h>
Most return a value (the "answer")
Example: theRoot = sqrt(9.0);
Components:
sqrt = name of library function
theRoot = variable used to assign "answer" to
9.0 = argument or "starting input" for function
In I-P-O:
I = 9.0
P = "compute the square root"
O = 3, which is returned & assigned to theRoot
Using functions –
Math Library functions
C includes a library of Math functions you can use.
You have to know how to call these functions before you can use them.
You have to know what they return.
You don’t have to know how they work!
Function parameters
The parameters are local variables inside the body of the function.
When the function is called they will have the values passed in.
The function gets a copy of the values passed in (we will later see how to pass a reference to a variable).
Understanding Scope
Some variables can be accessed throughout an entire program, while others can be accessed only in a limited part of the program
The scope of a variable defines where it can be accessed in a program
To adequately understand scope, you must be able to distinguish between local and global variables
Declaring Reference Variables
There are two differences between reference variables and pointers:
Pointers are more flexible
Reference variables are easier to use
You assign a value to a pointer by inserting an ampersand in front of the name of the variable whose address you want to store in the pointer
Figure 4-30 shows that when you want to use the value stored in the pointer, you must use the asterisk to dereference the pointer, or use the value to which it points, instead of the address it holds