Unformatted text preview:

Function – IFunction – IIExample for Function DeclarationArgumentsFunction – IIIExample: Area CalculationExample – IExample I – codeExample – IIExample: factorialsSlide 11Local Variables – ILocal Variables – IIRecursive Function CallRecursionRecursive ApproachesExampleCodeFibonacci seriesArray as parametersArray as parameters – cont.Pass by ValuePass by ReferenceCalculate the minimum valueSlide 25Global VariablesSlide 27Automatic and static variablesSlide 29Function – I•What is a function–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 blockFunction – II•How to declare a functionreturn_value_type function_name( parameter-list){Definitions;Statements;}•Parameter-list formattype1 variable_name1, type2 variable_name2,…typeN variable_nameNExample for Function Declaration•Example: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 functionArguments•Arguments:–Independent variables or input to a function–Parameters•Exampledouble CalcMax(double a[10]) –The values assigned to the array a are passed to the function at runtime –Increase usefulness and flexibilityFunction – 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 valueExample: Area Calculationdouble 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;}Example – I•Compute the square root of x•Psudocode1. Set the value of guess to 12. If |guess2 - x| < , proceed to step 43. Set the value of guess to (x / guess + guess) and return to 24. The guess is the approximation of the square rootExample I – codefloat squareRoot (float x){const float epsilon = 0.0001;float guess = 1.0;while ( guess * guess – x >= epsilon || guess * guess – x <= -epsilon ) guess = ( x / guess + guess ) / 2.0;return guess;}Example – II•Compute the factorialsdouble factorial(int n){double result = 1;int i;for( i = 2; i <= n; i++) result = result * i;return result ;}Example: factorials5! = 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);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?Local Variables – I•What is local variables–Variables declared within a function •Example:double CalcMax(double a[10]) {int i;double maxValue;…;}int main() {int i;double a[10]double maxValue;maxValue = CalcMax(a) ;}Local variablesLocal variablesLocal 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 variablesRecursive Function Calldouble factorial(int n){if ( n <= 1 )return 1;else return (n * factorial(n – 1));}double factorial(int n){if ( n <= 1 )return 1;else return (n * factorial(n – 1));}double factorial(int n){if ( n <= 1 )return 1;else return (n * factorial(n – 1));}double factorial(int n){if ( n <= 1 )return 1;else return (n * factorial(n – 1));}n=4 n=3n=2n=1return (4 * factorial(4 – 1));factorial( 3));return (3 * factorial(3 – 1));factorial( 2));return (2 * factorial(2 – 1));factorial( 1));return 1;1);2);6);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 problemRecursive 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)Example•Function power(base, exponent) which returns baseexponent–Recursion relationship•baseexponent = base * baseexponent-1;–Base case:•base1= base;Codedouble power(float base, int exponent){if (exponent == 1)return base;elsereturn( base * power(base, exponent-1));}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 functionlong fib( int n ){if (n == 0 || n == 1) // base case return n;else return( fib( n - 1) + fib( n – 2 ) );}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 arrayArray 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][])Pass by Value•Passing a copy of the value as an argument –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 = 4Pass by Reference •Passing the address itself rather than the value–Changes to parameters will affect the caller's


View Full Document

UF CGS 3460 - Function

Download Function
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Function and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Function 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?