Tutorial One - PowerPoint PPT Presentation

1 / 58
About This Presentation
Title:

Tutorial One

Description:

What benefits are offered by procedural abstraction. How to create global ... Local variables cease to exist when that block ends. Global Versus Local Variables ... – PowerPoint PPT presentation

Number of Views:60
Avg rating:3.0/5.0
Slides: 59
Provided by: jun6
Category:
Tags: cease | one | tutorial

less

Transcript and Presenter's Notes

Title: Tutorial One


1
Tutorial One
  • C
  • Functions

2
Lesson A
Functions
3
Lesson A Objectives
  • To Learn
  • What a Function is
  • What benefits are offered by procedural
    abstraction
  • How to create global and local variables

4
Lesson A Objectives
  • To Learn
  • How to create a function prototype
  • How to return values from functions
  • How to pass values from functions

5
What Is a Function?
  • Functions
  • Sub-programs that perform some task or group of
    tasks
  • When a function is called, program control is
    transferred to the function
  • A function has two parts
  • Header
  • Body

6
What Is a Function?
  • The header of a function consists of three parts
  • The type of the function which determines what
    type of value the function return
  • The name of the function
  • In parentheses, the type and names of any
    variables that will be passed to the function
  • The body of a function consists of any C
    statement between a pair of curly brackets

7
What Is a Function?
  • Examples

includeltlogo.hgt void main() displayLogo()
Definition of displayLogo() is inside the logo.h
file
8
What Is a Function?
  • Examples

includeltiostream.hgt include "myheader.h" void
main() coutltlt"Minimum wage is
"ltltminimumWageltltendl coutltlt"Minimum retirement
age is " ltltminRetireAgeltltendl
double minimumWage4.75 int minRetireAge60
myheader.h
9
What Is a Function?
includeltiostream.hgt include "myheader.h" void
main() double minimumWage99.9
//overrides constant in header file
coutltlt"Minimum wage is "ltltminimumWageltltendl
coutltlt"Minimum retirement age is
"ltltminRetireAgeltltendl
10
Procedural Abstraction
  • Abstraction
  • The process of extracting the relevant attributes
    of an object
  • Simplifies your concept of the object, allowing
    you to ignore essential details
  • Using functions is one way to employ procedural
    abstractions in C
  • Use an object without knowing how it is made of

11
Global Versus Local Variables
  • Global variables
  • Variables known to all functions in a program
  • Local variables
  • Only known to a certain block
  • A variable with a given name inside a function
    overrides any global variable with the same name,
    unless special action is taken to specify use of
    the global variable

12
Global Versus Local Variables
  • Functions such as
  • computeGroos()
  • deductFederalTaxes()
  • deductLocalTaxes()
  • deductInsurance()
  • printPaycheck()
  • You only need to know how to use

13
Global Versus Local Variables
includeltiostream.hgt void main() int b 2
coutltlt"b"ltltbltltendl int b,c c3
b5 coutltlt"b"ltltbltltendl
  • Example

14
Global Versus Local Variables
  • Variables that are declared in a block (that is,
    between curly brackets) are local to that block
    and have the following characteristics
  • Local variables are created when they are
    declared within a block
  • Local variables are known only to that block
  • Local variables cease to exist when that block
    ends

15
Global Versus Local Variables
  • In scope
  • In the area where a variable is alive, it is in
    scope
  • No variable can be accessed outside of its scope

16
Global Versus Local Variables
  • Global variables
  • Values declared outside a block
  • Known to all functions in the file in which they
    are declared
  • It is a better style to use local variables than
    global ones
  • This strategy represents a preliminary example of
    a type of encapsulation

17
Show scope of variable
includeltiostream.hgt void main() int b2
coutltltbltltendl // coutltltc // doesn't work
int c3 coutltltbltlt" "ltltcltltendl
coutltltbltltendl //coutltltc //doesn't
work // coutltltb //doesn't work
18
includeltiostream.hgt void sayHello() int
x12 coutltlt"Hello"ltltendl coutltltxltltendl v
oid main() int y13, x77 coutltltxltltendl sayHel
lo() coutltltyltlt" "ltltxltltendl
19
Global Versus Local Variables
  • Disadvantages to using global variables
  • If variables are global in a program and you
    reuse any functions in a new program, the
    variables must be re-declared in the latter
    program
  • Global variables can be affected by any function,
    leading to errors
  • You may use a global variable even when a local
    variable with the same name exists, by using the
    scope resolution operator

20
Global Versus Local Variables
  • Example

includeltiostream.hgt int someNum44 void
main(void) int someNum32
coutltltsomeNumltltendl coutltltsomeNumltltendl
includeltiostream.hgt int WorldlyOne44 void
main() coutltltWorldlyOneltltendl WorldlyOne1732

Scope resolution operator
21
Prototyping
  • Creating a sample function outline or a
    description of how the actual function will look
  • A prototype indicates three features about a
    function
  • The type of variable that the function will
    return to the function that calls it
  • The name of the function
  • In parentheses, the types of any variable that
    will be passed to the function

22
Returning Values from Functions
  • The type of value a function returns is also
    known as the functions type
  • A severe limitation of functions is that each
    function may have only one type
  • Consequently, it may return only one value

23
Returning Values from Functions
  • Example of void function

void displayDirections() coutltlt"This program
will ask you for two numbers" ltltend coutltlt"try
to guess their sum"ltltendl
24
Returning Values from Functions
  • Example of return value function

includeltiostream.hgt void main() char
usersInitial char askUserForInitial(void)
//prototype usersInitialaskUserForInitial()
coutltlt"Your initial is "ltltusersInitialltltendl
25
Returning Values from Functions
  • Example of return value function

char askUserForInitial(void) char
letter coutltlt"Please type your initial and press
enter"ltltendl cingtgtletter return(letter)
26
Returning Values from Functions
  • Example of return value function, int type

int getFirstNum(void) int num
coutltlt"Enter the first number "ltltendl
cingtgtnum return num
27
Passing Values to Functions
  • Used to passing information between calling
    function and called functions
  • Parameters
  • hold the values that will actually be used by a
    function
  • Arguments
  • The list of variable types and names in the
    function header

28
Passing Values to Functions
  • There are three passing methods
  • passing by value
  • passing by reference
  • passing by address
  • Examples to show how to passing by value

29
includeltiostream.hgt void main() int hours
double hourlyRate void netPay(int hours,
double rate) //function
prototype coutltlt"Enter hours
worked"ltltendl cingtgthours coutltlt"Enter
rate perhour"ltltendl cingtgthourlyRate
netPay(hours, hourlyRate)
30
void netPay(int time, double money) const
double withholdingPct0.15 double
withholdingAmount, netAmount
netAmounttimemoney withholdingAmountnetAmou
ntwithholdingPct netAmount-withholdingAmoun
t coutltlt"Net pay is "ltltnetAmountltltendl
31
Lab Exercises and Homework
  • Do Exercises 1 on page 58
  • Do Exercises 2 on page 58
  • Do Exercises 3 on page 58
  • Do Exercises 4 on page 58
  • Do Exercises 5 on page 58
  • Due date Feb. 10, 2001

32
Lesson B
Working with Functions
33
Lesson B Objectives
  • To learn how to
  • Work with pointers
  • Pass addresses to functions
  • Use reference variables with functions

34
Lesson B Objectives
  • To learn how to
  • Create inline functions
  • Use default arguments with functions
  • Overload functions

35
Passing by addresses to Functions
  • You can view the memory address of any variable
    by using the address operator,
  • Pointers
  • Variables that can hold memory addresses
  • Indirection operator
  • The asterisk, "", can be used to access the
    contents held by a pointer

36
Passing by addresses to Functions
  • Review the address operator

includeltiostream.hgt void main() int myValue
16 coutltlt"myValue is "ltltmyValueltltendl
coutltlt"It is stored at address "ltltmyValueltltendl

37
Passing by addresses to Functions
  • Review example to show how to use pointer
  • define an pointer, e.g., int ptr
  • use a pointer to direct or point to the same type
    of data variable, e.g., ptrnum
  • indirect or dereference the value of the variable
    where the pointer points, e.g, ptr43
  • Example to show how to use passing by address

38
includeltiostream.hgt void main() int a19,
b7, dividend, modulus void results(int a,
int b, int d, int m) results(a, b,
dividend, modulus) coutltlt"Dividend is
"ltltdividendltlt" and modulus is "
ltltmodulusltltendl void results(int oneNumber,
int anotherNumber, int
oneAddress, int anotherAddress)
oneAddressoneNumber/anotherNumber
anotherAddressoneNumberanotherNumber
39
Using Reference Variables with Functions
  • Alias
  • A second name
  • Reference variable
  • Acts as an alias for a second variable
  • A reference variable is declared with a type and
    an ampersand in front of its name

40
Using Reference Variables with Functions
  • Example of reference variable, alias name

double someMoney34.78 double cashsomeMoney c
ash6.57 coutltltsomeMoeny someMoney1.245 coutltlt
cash
41
Using Reference Variables with Functions
  • A reference variable refers to the same memory
    address as a variable
  • A pointer holds the memory address of a variable
  • Differences between a reference variable and a
    pointer
  • Pointers are more flexible
  • Reference variables are easier to use

42
Using Reference Variables with Functions
  • Example of reference variable, alias name

includeltiostream.hgt void main() int x8
void someFunction(const int refx)
someFunction(x) coutltlt"value x is "ltltxltltendl
43
Using Reference Variables with Functions
void someFunction(const int refx) //
refx99 illegal assignment coutltlt"value of
refx is "ltltrefxltltendl
44
Working with Arrays
  • Array
  • List of individual scalar items that all have the
    same data type
  • Holds two or more variables with the same name
    and in adjacent memory positions
  • Subscripts
  • Number that indicates the position of the
    particular variables being used

45
Working with Arrays
  • Array Size
  • Number of variables in an array
  • Array name represents a memory address
  • array name is a static pointer

46
Working with Arrays
FIGURE 1-1 How sums 533,45,67,78,99 appears
in memory
47
Working with Arrays
  • When passing an array name to a function, you are
    actually passing an address
  • Therefore, any changes made to the array within
    the function will also affect the original array
  • When an array name is passed to a function, the
    function knows the starting address of the
    array
  • Therefore, you dont need to indicate a size for
    the array in the function header
  • Example

48
includeltiostream.hgt void addoneToEach(int
funcArray ) void main() int
someNumbers42,5,8,7 addoneToEach(someNumb
ers) for (int i0ilt4i) coutltlt"
"ltltsomeNumbersi coutltltendl void
addoneToEach(int funcArray ) for (int
j0jlt4j) funcArrayj
49
Inline Functions
  • Each time you call a function in a C program,
    the computer must do the following
  • Remember where to return when the function
    eventually ends
  • Provide memory for the functions variables
  • Provide memory for any value returned the function

50
Inline Functions
  • Each time you call a function in a C program,
    the computer must do the following
  • Pass control to the function
  • Pass control back to the calling program
  • This extra activity constitutes the overhead (or
    the cost of doing business) involved in calling a
    function

51
Inline Functions
  • Use an inline function in the following
    situations
  • When grouping statements together so that you can
    use a function name
  • When the number of statements is small
  • When the function is called on few occasions

52
includeltiostream.hgt inline double
computeGross(double hours, double rate) return
hoursrate void main() double
hrsWorked7.5, rateOfPay12.45, gross
grosscomputeGross(hrsWorked, rateOfPay)
coutltlt"\nGross pay is "ltltgrossltltendl
53
Using Default Arguments
  • When not providing enough arguments in a function
    call, you usually want the compiler to issue a
    warning message for this error
  • Sometimes it useful to create a function that
    supplies a default value for any missing
    parameters
  • Functions may include default parameters and
    mandatory parameters

54
Using Default Arguments
  • Two rules apply to default parameters
  • If you assign a default value to any variable in
    a function prototypes parameter list, then all
    parameters to the right of that variable must
    also have default values
  • If you omit any arguments when you call a
    function that has default parameters, then you
    must leave out all arguments to the right of that
    argument
  • Example

55
includeltiostream.hgt void main() void
functionWithDefaults(int var1, int var22, int
var33) // functionWithDefaults() //
illegal functionWithDefaults(4) functionWithDefau
lts(4,5) functionWithDefaults(4,5,6) void
functionWithDefaults(int one, int two, int
three) coutltltoneltlttwoltltthreeltltendl
56
Overloading Functions
  • Different functions share with same function name
    function
  • The functions should have common feature and
    functionality
  • Example

57
includeltiostream.hgt void squareValue(int x)
coutltltxxltltendl void squareValue(float x)
coutltltxxltltendl void squareValue(double x)
coutltltxxltltendl void main() int j2 float
a4.3f double b32.45 squareValue(j) squareValu
e(a) squareValue(b)
58
Lab Exercises and Homework
  • Do Exercises 1 on page 79
  • Do Exercises 2 on page 79
  • Do Exercises 3 on page 80
  • Do Exercises 4 on page 80
  • Do Exercises 5 on page 80
  • Do Exercises 6 on page 80
  • Do Exercises 7 on page 80
  • Due date Feb. 17, 2001
Write a Comment
User Comments (0)
About PowerShow.com