Está en la página 1de 31

Functions

Structural Decomposition
An approach used to handle complexity in
solving problems based on the divide and
conquer strategy
A larger problem (more complex) is broken up
into smaller problems (less complex)
The solution to the problem (a module) is a
combination of solutions of the smaller problems
(sub-modules)
Each sub-module also has its own input(s) and
output(s)

Structural Decomposition
Program

Function1

Function2

Function3

Functions
Modules in C
Programs combine user-defined functions with library functions
C standard library has a wide variety of functions

Function calls
Invoking functions
Provide function name and arguments (data)
Function performs operations or manipulations
Function returns results

Function call analogy:


Boss asks worker to complete task
Worker gets information, does task, returns result
Information hiding: boss does not know details

Hierarchical boss function/worker function relationship

main

worker1

worker4

worker2

worker5

worker3

Math Library Functions


Function

Description

Example

sqrt( x )

square root of x

sqrt( 900.0 ) is 30.0


sqrt( 9.0 ) is 3.0

exp( x )

exponential function ex

log( x )

natural logarithm of x
(base e)

exp(
exp(
log(
log(

log10( x )

logarithm of x (base 10)

fabs( x )

absolute value of x

ceil( x )

rounds x to the smallest


integer not less than x

floor( x )

rounds x to the largest


integer not greater than x

floor( 9.2 ) is 9.0


floor( -9.8 ) is -10.0

pow( x, y )

x raised to power y (xy)

fmod( x, y )

remainder of x/y as a
floating point number

pow( 2, 7 ) is 128.0
pow( 9, .5 ) is 3.0
fmod( 13.657, 2.333 ) is
1.992

sin( x )

trigonometric sine of x
(x in radians)

sin( 0.0 ) is 0.0

cos( x )

trigonometric cosine of x
(x in radians)

cos( 0.0 ) is 1.0

tan( x )

trigonometric tangent of x tan( 0.0 ) is 0.0


(x in radians)

1.0 ) is
2.0 ) is
2.718282
7.389056

2.718282
7.389056
) is 1.0
) is 2.0

log10( 1.0 ) is 0.0


log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
fabs( 5.0 ) is 5.0
fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0

Commonly used math library functions.

Functions
Functions
Modularize a program
All variables defined inside functions are local variables
Known only in function defined

Parameters
Communicate information between functions
Local variables

Benefits of functions
Divide and conquer
Manageable program development

Software reusability
Use existing functions as building blocks for new programs
Abstraction - hide internal details (library functions)

Avoid code repetition

User-Defined Functions
Functions designed, written or defined by programmers
Every user-defined function must have 3 elements

a) function definitions
b) function prototypes
c) function calls
A function must be called in order to execute the
statements contained in its definition

a) Function Definitions
Function definition format

return-value-type function-name( parameter-list )


{
declarations and statements
}

return-value-type
data type of the result (default int)
void indicates that the function returns nothing

function-name
any valid identifier

parameter-list
comma separated list, declares parameters received by the
function when it is called
a type must be listed explicitly for each parameter
if function does not receive any values, parameter-list is void

a) Function Definitions (continued)


Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}

declarations and statements


function body (block)
variables can be defined inside blocks (can be nested)
functions can not be defined inside other functions

returning control
If nothing returned :
return OR
until reaches right brace
If something returned
return expression;

b) Function Prototypes
Function-name
Parameters > what the function takes in
Return value type > data type function returns (default int)
Give the compiler the type of data returned by the function,
the number of parameters the function expects to receive,
the types of the parameters, and the order in which these
parameters are expected
Use to validate functions
Prototype only needed if function definition comes after use
in program
Example : The function with the prototype

int maximum( int x, int y, int z );

c) Function Calls
To execute a function, it must first be called with the
following information :
Stating the function name
Providing a certain information (parameter)

Syntax for a function call:


function-name (parameter-list );
function-name the function name that is to be called. The
way to name the function is same as to name the variable
parameter-list is a list of information which is required to
execute a function

Calling Functions: Call by Value and Call by Reference


Call by value
Copy of argument passed to function
Changes in function do not effect original
Use when function does not need to modify argument
Avoids accidental changes
Call by reference
Passes original argument
Changes in function effect original
Only used with trusted functions
For now, we focus on call by value

/* Creating and using a programmer-defined function */

2
3

#include <stdio.h>

4
5

int square( int y );

/* function prototype */

6
7

/* function main begins program execution */

int main()

{
int x; /* counter */

10
11
12

/* loop 10 times and calculate and output square of x each time */

13

for ( x = 1; x <= 10; x++ ) {


printf( "%d ", square( x ) ); /* function call */

14

} /* end for */

15
16

printf( "\n" );

17
18

return 0; /* indicates successful termination */

19
20

21 } /* end main */
22
23 /* square function definition returns square of an integer */

24 int square( int y ) /* y is a copy of argument to function */


25 {
return y * y; /* returns square of y as an int */

26
27

28 } /* end function square */

16

25

36

49

64

81

100

/* Fig. 5.4:
Finding the maximum of three integers */

2
3

#include <stdio.h>

4
5

int maximum( int x, int y, int z ); /* function prototype */

6
7

/* function main begins program execution */

int main()

10

int number1; /* first integer */

11

int number2; /* second integer */

12

int number3; /* third integer */

13
14

printf( "Enter three integers: " );

15

scanf( "%d%d%d", &number1, &number2, &number3 );

16
17
18
19

/* number1, number2 and number3 are arguments


to the maximum function call */
printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) );

20
21

return 0; /* indicates successful termination */

22
23 } /* end main */
24

25 /* Function maximum definition */


26 /* x, y and z are parameters */
27 int maximum( int x, int y, int z )
28 {
29

int max = x;

/* assume x is largest */

30
31

if ( y > max ) { /* if y is larger than max, assign y to max */

32

max = y;

33

} /* end if */

34
35

if ( z > max ) { /* if z is larger than max, assign z to max */

36

max = z;

37

} /* end if */

38
39

return max;

/* max is largest value */

40
41 } /* end function maximum */

Enter three
Maximum is:
Enter three
Maximum is:
Enter three
Maximum is:

integers: 22 85 17
85
integers: 85 22 17
85
integers: 22 17 85
85

E
X
A

M
P

L
E

#include <stdio.h>
int computeArea(int width, int height);
void outputArea(int area);
int main() {
int rectWidth, rectHeight, rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeArea(rectWidth, rectHeight);
outputArea(rectArea);
return 0;
}
int computeArea(int width, int height) {
return width * height;
}
void outputArea(int area) {
printf(Rectangle area: %d\n", area);
}

#include <stdio.h>
int computeArea(int width, int height);
void outputArea(int area);
int main() {
int rectWidth, rectHeight, rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeArea(rectWidth, rectHeight);
outputArea(rectArea);
return 0;
}
int computeArea(int width, int height) {
return width * height;
}
_
void outputArea(int area) {
printf(Rectangle area: %d\n", area);
}

???
rectWidth
???
rectHeight
???
rectArea

#include <stdio.h>
int computeArea(int width, int height);
void outputArea(int area);
int main() {
int rectWidth, rectHeight, rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeArea(rectWidth, rectHeight);
outputArea(rectArea);
return 0;
}
int computeArea(int width, int height) {
return width * height;
}
7 11
void outputArea(int area) {
_
printf(Rectangle area: %d\n",
area);
}

7
rectWidth
11
rectHeight
???
rectArea

#include <stdio.h>
int computeArea(int width, int height);
void outputArea(int area);
int main() {
int rectWidth, rectHeight, rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
77
rectArea = computeArea(rectWidth, rectHeight);
outputArea(rectArea);
return 0;
}
7
int computeArea(int width, int height) {
width
return width * height;
}
7 11
void outputArea(int area) {
_
printf(Rectangle area: %d\n",
area);
}

7
rectWidth
11
rectHeight
???
rectArea

11
height

#include <stdio.h>
int computeArea(int width, int height);
void outputArea(int area);
int main() {
int rectWidth, rectHeight, rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeArea(rectWidth, rectHeight);
outputArea(rectArea);
return 0;
}
int computeArea(int width, int height) {
return width * height;
}
7 11
void outputArea(int area) {
printf(Rectangle area: _%d\n", area);
}

7
rectWidth
11
rectHeight
77
rectArea

#include <stdio.h>
int computeArea(int width, int height);
void outputArea(int area);
int main() {
int rectWidth, rectHeight, rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeArea(rectWidth, rectHeight);
outputArea(rectArea);
}
11
77 11
int computeArea(int width, intRectangle
height) { area: 77
_
return width * height;_
}
void outputArea(int area) {
printf(Rectangle area: %d\n", area);
}
77
area

7
rectWidth

#include <stdio.h>
int computeArea(int width, int height);
11
void outputArea(int area);
rectHeight
int main() {
int rectWidth, rectHeight, rectArea;
77
scanf("%d%d", &rectWidth, &rectHeight);
rectArea
rectArea = computeArea(rectWidth, rectHeight);
outputArea(rectArea);
}
7 11
int computeArea(int width, int height) {
Rectangle area: 77
return width * height;
_
}
void outputArea(int area) {
printf(Rectangle area: %d\n", area);
}

SCOPE RULES OF VARIABLES


Local Variables
Variables which are defined in a function can only be
used within that function
it cannot be accessed from main() or other function

Global Variables
Global variables can be accessed or known by
any function comprising the program
Global variables must be declared outside of any function
even outside of the main function

Local Variables
int computeRectArea(int, int);
int main() {
int rectWidth, rectHeight, rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeRectArea(rectWidth, rectHeight);
printf(Rectangle area: %d", area);
}
int computeRectArea(int width, int height) {
int area;
area = width * height;
return area;
}

Local Variables
int computeRectArea(int, int);
int main() {
The local variable area is only
int rectWidth, rectHeight,used
rectArea;
within the function The function which defines it
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeRectArea(rectWidth, rectHeight);
printf(Rectangle area: %d", area);
}
int computeRectArea(int width, int height) {
int area;
area = width * height;
return area;
}

Local Variables
int computeRectArea(int, int);
Variable area in function
int main() {
computeRectArea()
int rectWidth, rectHeight;
cannot be accessed here.
int rectArea;
scanf("%d%d", &rectWidth, &rectHeight);
rectArea = computeRectArea(rectWidth, rectHeight);
printf(Rectangle area: %d", area);
ERROR!
}
int computeRectArea(int width, int height) {
int area;
area = width * height;
return area;
}

Recursive Function
Is a function that can call itself and when a
function calls itself, a new copy of that
function is run.
The recursive function must have a stop
condition
Body of function must have 3 components
Recursive part contains a call to itself
Termination part a value to stop the recursive
function
A decision construct that will eventually select
the termination part

Recursive Function : Factorials

5!

5!

5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
( a ) Se q u en c e o f re c ursive c a lls.

Fin a l va lue = 120

5! = 5 * 24 = 120 is re turn ed
5 * 4!
4! = 4 * 6 = 24 is re turne d
4 * 3!
3! = 3 * 2 = 6 is re tu rn e d
3 * 2!
2! = 2 * 1 = 2 is re turne d
2 * 1!
1 re turne d
1
( b ) Va lue s re turne d fro m e a c h re cu rsive c a ll.

Example: calculate the factorial number


#include<stdio.h>
void faktorial(int);
void main(){
int n,nilai;
printf(Masukkan nilai faktorial\n)
scanf(%d,&n);
nilai=faktorial(n);
printf ( nilai bagi faktorial %d ialah %d ,n, nilai);
}
int faktorial (int n)
{
int c;
if ( n <= 1)
return (1);
else
return (n * faktorial (n -1));
}

End of Lecture

También podría gustarte