Download presentation
Presentation is loading. Please wait.
Published byAnn Neal Modified over 7 years ago
1
Function – I What is a function Why we need functions?
One named program module that does one primary task Consists of a set of statements Why we need functions? Chop up a long program for Better organization of code Use same code repetitively Each function acts as a building block
2
Function – II How to declare a function Parameter-list format
return_value_type function_name( parameter-list) { Definitions; Statements; } Parameter-list format type1 variable_name1, type2 variable_name2,…typeN variable_nameN
3
Example for Function Declaration
int main() { …;} double calcMax(double a, double b) {…;} Special cases Use void for return_value_type if no value is needed to be returned. Use void for parameter-list if no parameters are needed to pass to the function
4
Arguments Arguments: Example
Independent variables or input to a function Parameters Example double CalcMax(double a[10]) The values assigned to the array a are passed to the function at runtime Increase usefulness and flexibility
5
Function – III How to return a value in a function
return; // for void return type return expression; // to return the value to expression to the caller How to call/invoke a function function_name(…); // for function with no return value variable_name = function_name(…); // for function with return value
6
Example: Area Calculation
double CalcArea(double hight, double width) { return height * width; } int main() double h, w, area; printf(“Please input height and width\n”); scanf(“%f, %f”, &h, &w); area = CalcArea(h, w); printf(“The area is %f”, area); return 0;
7
Example – I Compute the square root of x Psudocode
Set the value of guess to 1 If |guess2 - x| < , proceed to step 4 Set the value of guess to (x / guess + guess) and return to 2 The guess is the approximation of the square root
8
Example I – code float squareRoot (float x) {
const float epsilon = ; float guess = 1.0; while ( guess * guess – x >= epsilon || guess * guess – x <= -epsilon ) guess = ( x / guess + guess ) / 2.0; return guess; }
9
Example – II Compute the factorials double factorial(int n) {
double result = 1; int i; for( i = 2; i <= n; i++) result = result * i; return result ; }
10
Example: factorials 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; factorial(5) = 5 * factorial(4);
11
Example: factorials factorial(n) = n * factorial(n-1);
double factorial(int n) { double result; if ( n <= 1 ) return 1; else { result = n * factorial(n – 1); return result ; } Does this code work?
12
Local Variables – I What is local variables Example:
Variables declared within a function Example: double CalcMax(double a[10]) { int i; double maxValue; …; } int main() double a[10] maxValue = CalcMax(a) ; Local variables Local variables
13
Local Variables – II Why need local variables?
To store temporary information Values are private to current function Can't be accessed by other functions Unless they are passed as arguments Arguments are local variables
14
Recursive Function Call
double factorial(int n) { if ( n <= 1 ) return 1; else return (n * factorial(n – 1)); } n=4 double factorial(int n) { if ( n <= 1 ) return 1; else return (n * factorial(n – 1)); } n=3 return (4 * factorial(4 – 1)); factorial( 3)); 6); return (3 * factorial(3 – 1)); factorial( 2)); 2); double factorial(int n) { if ( n <= 1 ) return 1; else return (n * factorial(n – 1)); } n=2 double factorial(int n) { if ( n <= 1 ) return 1; else return (n * factorial(n – 1)); } n=1 return 1; return (2 * factorial(2 – 1)); 1); factorial( 1));
15
Recursion Recursive functions Functions that call themselves
Can solve a base case or base cases Divide a problem up into Base case(s), which is what it can do Others The function launches a new copy of itself (recursion step), leading to base case(s) Eventually base case gets solved Gets plugged in, works its way up and solves whole problem
16
Recursive Approaches Recursive function is called to solve a problem
Know how to solve only the simplest case(s), or so-called base case(s) Resemble a complex problem in a simpler or smaller version of the same problem. Execution The recursion step execute while the original call to the function is still open, i.e., it has not yet finished. May be many recursive calls. All calls converge on the base case(s)
17
Example Function power(base, exponent) which returns baseexponent
Recursion relationship baseexponent = base * baseexponent-1; Base case: base1= base;
18
Code double power(float base, int exponent) { if (exponent == 1)
return base; else return( base * power(base, exponent-1)); }
19
Fibonacci series Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
Each number is the sum of the previous two Can be solved recursively: fib( n ) = fib( n - 1 ) + fib( n – 2 ) Code for the fibaonacci function long fib( int n ) { if (n == 0 || n == 1) // base case return n; else return( fib( n - 1) + fib( n – 2 ) ); }
20
Array as parameters Pass entire array to a function
Example: int minimum(int values[100]) int minimum(int values[ ], int numberOfElements) Only the location of array is passed to the function Not the value of all elements in the array
21
Array as parameters – cont.
Omitting size of array For one-dimension array int minimum(int array[ ]) For multi-dimensional array int minimum(int matrix[ ][10]) int minimum(int matrix[10][])
22
Pass by Value Passing a copy of the value as an argument Examples:
Parameters receive a distinct copy of the caller's arguments, as if the parameters were assigned from the arguments Changes made for parameters have no effect on the caller’s arguments Examples: h = 3; w = 4; area = CalcArea(h, w); double CalcArea(double hight, double width) { …; } height = 3, width = 4
23
Pass by Reference Passing the address itself rather than the value
Changes to parameters will affect the caller's arguments as well, for they are the same variable Used for array, variable address Use ‘&’ to get the location of a particular variable Example values a int values[100], minVal; minVal = minimum(values); double minimum(int a[100]) { …; } int b, c; swap(&b, &c); void swap(int *v1, int *v2) { …; }
24
Calculate the minimum value
In a recursive way: Base case: If only one number in the array Recursive Calculate the minimum value for the first half of the array Calculate the minimum value for the second half of the array Calculate the smaller value for these two values min min min
25
Code int minimum(int values[ ], int numberOfElements) { int sepLoc;
int v1, v2; if ( numberOfElements == 1) return values[0]; else { sepLoc = numberOfElements / 2; v1 = minimum(values, sepLoc); v2 = minimum(&(values[sepLoc]), numberOfElements - sepLoc); return ( (v1 < v2) ? v1 : v2 ); }
26
Global Variables What is a global variable Why need a global variable
A variable does not belong to any function A variable can be accessed by any function in a program Why need a global variable avoid passing frequently-used variables continuously throughout several functions, How to define a global variable Same as other variable declaration, except it is outside any function
27
Example int x; /* Global variable */
int y = 10; /* Initialized global variable */ int foo(int z) { int w; /* local variable */ x = 42; /* assign to a global variable */ w = 10; /* assign to a local variable */ return (x % y + z / w); }
28
Automatic and static variables
By default, all variables defined within function are automatic local variables Static variables Using keyword static Does not disappear after function call Initialized only once
29
Example void auto_static(void) { int autoVar = 1;
static int staticVar = 1; printf(“automatic = %i, static = %i\n”, autoVar, staticVar); autoVar++; staticVar++; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.