Download presentation
Presentation is loading. Please wait.
1
Functions
2
Introduction Divide and conquer
Construct a program from smaller pieces or components These smaller pieces are called modules Each piece more manageable than the original program
3
Program Modules in C Functions Function calls Invoking functions
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
4
Program Modules in C Fig Hierarchical boss function/worker function relationship.
5
Functions Functions allow us to group commonly used code into a compact unit that can be used repeatedly We have already encountered one function, main. It is a special function called at the beginning of the program. All other functions are directly or indirectly called from main Suppose we want to write a program to compute the area of three triangles. We could write out the formula three times, or we could create a function to do the work
6
Cont … The function proper begins with the line:
float triangle(float width, float height) float is the function type. The two parameters are width and height. They are of type float also. C uses a form of parameter passing called "Call by value". When our procedure triangle is called, with code such as: triangle(1.3, 8.3); The function computes the area with the statement: area = width * height / 2.0; What's left is to give the result to the caller. This step is done with the return statement: return (area);
7
The code float triangle(float width, float height) {
float area; /* Area of the triangle */ area = width * height / 2.0; return (area); }
8
Calling the function size = triangle(1.3, 8.3);
is a call to the function triangle. C assigns 1.3 to the parameter width and 8.3 to height. The return value of this function is 5.4, so our statement: size = triangle (1.3, 8.3) assigns size the value 5.4.
9
printf("Triangle #1 %f\n", triangle(1.3, 8.3));
Whole code float triangle(float width, float height) { float area; /* Area of the triangle */ area = width * height / 2.0; return (area); } int main() { printf("Triangle #1 %f\n", triangle(1.3, 8.3)); printf("Triangle #2 %f\n", triangle(4.8, 9.8)); printf("Triangle #3 %f\n", triangle(1.2, 2.0)); return (0); }
10
Using a function If we want to use a function before we define it, we must declare it just like a variable to inform the compiler about the function. We use the declaration: float triangle (float width, float height); for the triangle function. This declaration is called the function prototype. The variable names are not required when declaring a function prototype. Our prototype could have just as easily been written as: float triangle(float, float);
11
int main(int numParms, char *parms[])
{ int result, k; printf(“Enter a number ); Scanf(“%d”, &k) result = sum(k); printf("The sum is %d\n", result); return 0; } int sum(int n) int count; int result; result = 0; for (count=1; count<=n; count++) result += count; return result;
12
Math Library Functions
perform common mathematical calculations #include <math.h> Format for calling functions FunctionName( argument ); If multiple arguments, use comma-separated list printf( "%.2f", sqrt( ) ); Calls function sqrt, which returns the square root of its argument
13
Math Library Functions
14
5.4 Functions Functions Benefits of 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
15
5.5 Function Definitions Function definition format
return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier Return-value-type: data type of the result (default int) void – indicates that the function returns nothing Parameter-list: comma separated list, declares parameters A type must be listed explicitly for each parameter unless, the parameter is of type int
16
Function Definitions Function definition format (continued)
return-value-type function-name( parameter-list ) { declarations and statements } Definitions 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;
17
fig05_03.c (Part 1 of 2)
18
fig05_04.c (Part 1 of 2)
19
Function Prototypes Function prototype Promotion rules and conversions
Function name Parameters – what the function takes in Return type – data type function returns (default int) Used to validate functions Prototype only needed if function definition comes after use in program The function with the prototype int maximum( int x, int y, int z ); Takes in 3 ints Returns an int Promotion rules and conversions Converting to lower types can lead to errors
20
5.6 Function Prototypes
21
Header Files Header files Custom header files
Contain function prototypes for library functions <stdlib.h> , <math.h> , etc Load with #include <filename> #include <math.h> Custom header files Create file with functions Save as filename.h Load in other files with #include "filename.h" Reuse functions
22
5.7 Header Files
23
5.8 Calling Functions: Call by Value and Call by Reference
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
24
5.13 Recursion Recursive functions Functions that call themselves
Can only solve a base case Divide a problem up into What it can do What it cannot do What it cannot do resembles original problem The function launches a new copy of itself (recursion step) to solve what it cannot do Eventually base case gets solved Gets plugged in, works its way up and solves whole problem
25
5.13 Recursion Example: factorials Notice that
5! = 5 * 4 * 3 * 2 * 1 Notice that 5! = 5 * 4! 4! = 4 * 3! ... Can compute factorials recursively Solve base case (1! = 0! = 1) then plug in 2! = 2 * 1! = 2 * 1 = 2; 3! = 3 * 2! = 3 * 2 = 6;
26
5.13 Recursion
27
fig05_14.c (Part 1 of 2)
28
1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 10! = fig05_14.c (Part 2 of 2)
29
5.14 Example Using Recursion: The Fibonacci Series
Each number is the sum of the previous two Can be solved recursively: fib( n ) = fib( n - 1 ) + fib( n – 2 ) Code for the fibonacci function long fibonacci( long n ) { if (n == 0 || n == 1) // base case return n; else return fibonacci( n - 1) fibonacci( n – 2 ); }
30
5.14 Example Using Recursion: The Fibonacci Series
function fibonacci f( 3 ) f( 1 ) f( 2 ) f( 0 ) return 1 return 0 return +
31
fig05_15.c (Part 1 of 2)
32
5.14 Example Using Recursion: The Fibonacci Series
33
Recursion vs. Iteration
Repetition Iteration: explicit loop Recursion: repeated function calls Termination Iteration: loop condition fails Recursion: base case recognized Both can have infinite loops Balance Choice between performance (iteration) and good software engineering (recursion)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.