Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 9-13 Functions.

Similar presentations


Presentation on theme: "Lecture 9-13 Functions."— Presentation transcript:

1 Lecture 9-13 Functions

2 Outline Standard (Predefined) Functions User-Defined Functions
Function Definition Flow of Execution

3 Introduction Until now, we learned to develop simple algorithms
Interactions, Mathematics, Decisions, and Loops Real problems: very complex Calculator Games, MS Word, Firefox, … Cannot be developed at once Divide the problem into smaller sub-problems Solve the sub-problems Put the solutions altogether to get the final solution

4 Introduction Divide and conquer
Construct a program from smaller pieces or components Smaller pieces sometimes called functions Each piece more manageable than the original program Divide and Conquer

5 Modular programming Solving a large and complex problem
Design the overall algorithm Some portions are black-box We know it does something But we don't worry how Later, we think about the black-boxes and develop them Black-boxes are implemented by functions

6 Why? Helps manage complexity Encourages re-use of code
Smaller blocks of code Easier to read Encourages re-use of code Within a particular program or across different programs Provides a layer of ‘abstraction’

7 Building Programs from Existing Programs
Programmers seldom start off with an empty program. Reasons: Most basic or frequently used functions have been written by other programmers. If you write every function by yourself, the source code may be messy and hard to maintained. Less code, less bugs. Many existing libraries have tune the performance, and thus are more reliable and robust.

8 Functions - Mathematical View
X Function Returned value

9 Function Input and Output

10 Functions Every C program starts with main() function
Functions could be Pre-defined library functions e.g., printf, sin, tan Programmer-defined functions e.g., my_printf, area int main() { }

11 Pre-defined library functions
<math.h> Defines common mathematical functions e.g. sin, cos. sqrt, pow <stdio.h> Defines core input and output functions e.g. printf, scanf <time.h> Defines date and time handling functions e.g. time, clock <stdlib.h> Defines pseudo-random numbers generation functions e.g. rand, srand

12 C mathematical functions
double      fmod( double x, double y ); Computes the remainder of the division operation x/y double      exp( double arg ); Computes the e (Euler's number,  ) raised to the given power arg double      log( double arg ); Computes the natural (base e) logarithm of arg double      log10( double arg ); Computes the common (base 10) logarithm of arg double      sqrt( double arg ); Computes square root of arg

13 C mathematical functions
double      pow( double base, double exp); Computes the value of base raised to the power exp double      sin( double arg ); Computes sine of arg (representing angle in radians) double      cos( double arg ); Computes cosine of arg (representing angle in radians) double      tan( double arg ); Computes tangent of arg (representing angle in radians) ...

14 An example #include <stdio.h> #include <math.h>
int main(void) { double angle; printf("Input angle in radians: \n"); scanf("%lf", &angle); printf("The sine of the angle is %f\n", sin(angle) ); return 0; }

15 An example #include <stdio.h> #include <math.h>
int main(void) { double x1,y1,x2,y2, dist; printf("Enter x1 y1 x2 y2 :"); scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2); dist = sqrt(pow((x2-x1),2) + pow((y2-y1),2)); // printf("Distance is %lf\n", dist); return 0; }

16 Random numbers generation functions
int rand(); Returns a uniformly distributed pseudo-random integral value between ​0​ and RAND_MAX (0 and RAND_MAX included) RAND_MAX : Expands to an integer constant expression equal to the maximum value returned by the function rand(). This value is implementation dependent. #define RAND_MAX /*implementation defined*/ srand() should be called before any calls to rand() to initialize the random number generator void srand( unsigned seed ); Initializes the built-in random number generator used to generate values for rand() with the seed value seed

17 An Example #include <stdio.h> #include <stdlib.h> int main(void) { unsigned int seed; /* Declare variables. */ int k; /* Get seed value from the user. */ printf("Enter a positive integer seed value: \n"); scanf("%u",&seed); srand(seed); /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

18 An Example #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(0)); //use current time as seed for random generator /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

19 Random Numbers in [a b] Generate a random number [0 .. 7]
x = rand() % 8; Generate a random number [ ] x = 10 + rand() % 8; rand() % (b-a+1) + a;

20 2.1 Use srand to change random sequence
1 /* Fig. 5.9: fig05_09.c 2 Randomizing die-rolling program */ 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 int main() 7 { 8 int i; 9 unsigned seed; 10 11 printf( "Enter seed: " ); 12 scanf( "%u", &seed ); 13 srand( seed ); 14 15 for ( i = 1; i <= 10; i++ ) { printf( "%10d", 1 + ( rand() % 6 ) ); 17 if ( i % 5 == 0 ) printf( "\n" ); 20 } 21 22 return 0; 23 } 1. Initialize seed 2. Input value for seed 2.1 Use srand to change random sequence 2.2 Define Loop 3. Generate and output random numbers Enter seed: 67 Enter seed: 867

21 Time Example /*This is a simple program that illustrates that calling the time function at distinct moments and noting the different times is a simple method of timing fragments of code:*/ #include <stdio.h> #include <sys/types.h> #include <time.h> int main(){ int i; time_t t1,t2; time(&t1); for (i=1;i<=300;++i) printf("%d %d %d\n",i, i*i, i*i*i); time(&t2); printf("\n Time to do 300 squares and cubes= %d seconds\n", (int) t2-t1); return 0; }

22 Functions in C Queries: Return a value
sin(), fabs() Commands: do some tasks, do not return any value or we don’t use the value printf(...) scanf(...)

23 User- defined OR Programmer-defined function

24 Functions in C Three steps to use functions in C
Function prototype (declaration) Introduce the function to compiler Function definition What the function does Function call Use the function

25 Functions - Definition Structure
Function 'header' Return data type (if any) Name Descriptive Arguments (or parameter list) Notice: data type and name Statements Variable declaration Operations Return value (if any) type function_name (type arg1, type arg2 ) { statements; } A function that calculates the product of two numbers double product(double x, double y) { double result; result = x * y; return result; } The function definition declares the return data type, its name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Contrast this with the function prototype.

26 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 void – indicates that the function returns nothing Parameter-list: comma separated list, declares parameters A type must be listed explicitly for each parameter No input: empty parameter list () or void

27 Function Definitions Function definition format (continued)
return-value-type function-name( parameter-list ) { declarations and statements } Declarations and statements: function body (block) Variables can be declared inside blocks Functions can not be defined inside other functions

28 Producing output Function definition format (continued)
return-value-type function-name( parameter-list ) { declarations and statements } Query functions Produce output To produce an output Declare output type Generate the output by return

29 The return command To generate a result by a function
return <value>; return <expression>; Only one value can be returned If noting returned return; Or until reaches right brace

30 The return command return finishes running the function
Function can have multiple return Only one of them runs each time The type of the returned value = the result type Otherwise, cast

31 Functions that do not return a value
Use the return type of void void functionName( DataType arg_1,…) void functionName() void functionName( void)

32 Function – An Example Write a function named 'sum' sums two integers
returns the sum Steps Function header return data type function name argument list with data types Statements in function definition variable declaration operations return value int sum_int(int x, int y) { int result; result = x + y; return result; }

33 Function call Command function Query function
<function name> (inputs); Query function <variable> = <function name>(inputs); Inputs should match by function definition Functions are called by another function Function call comes inside in a function

34 Example void my_info(void){
printf("My name is Ahmad Ahmadi\n"); printf("My student number: \n"); } int main(void){ my_info(); printf(" \n"); my_info(); return 0;

35 Function Call – An Example
If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored int GetUserInput (void); /* function prototype*/ int main(void) { int input; input = GetUserInput( ); return(0); /* return 0; */ } However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value We can also call a function inside another function printf("User input is: %d", GetUserInput( ));

36 N = f(pi*pow(r,2), b+c) + d;
Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used, N = f(pi*pow(r,2), b+c) + d;

37 Using Functions (continued)
This is a parameter Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used , N = f(pi*pow(r,2), b+c) + d; This is an argument This is also an argument

38 Definitions Parameter:– a declaration of an identifier within the '()' of a function declaration Used within the body of the function as a variable of that function Argument:– an expression passed when a function is called; becomes the initial value of the corresponding parameter

39 Using Functions (continued)
Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used, N = f(pi*pow(r,2), b+c) + d; The second argument expression is evaluated, converted to int, and assigned to parameter a The first argument expression is evaluated, converted to double, and assigned to parameter x

40 Using Functions (continued)
Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used, N = f(pi*pow(r,2), b+c) + d; Sum is assigned to N Function f is executed and returns a value of type int Result of f is added to d

41 Formal and Actual Parameters
Formal parameter Variables declared in the formal list of the function header (written in function prototype & function definition) Actual parameter Constants, variables, or expression in a function call that correspond to its formal parameter The number of actual parameters in a function call must be the same as the number of formal parameters in the function definition A one-to-one correspondence must occur among the actual and formal parameters. The first actual parameter must correspond to the first formal parameter and the second to the second formal parameter, an so on The type of each actual parameter must be the same as that of the corresponding formal parameter

42 An Example If the function requires some arguments to be passed along, then the arguments need to be listed in the bracket ( ) according to the specified order void Calc(int …, double …, char…, int…){…} int main(void) { int a, b; double c; char d; Calc(a, c, d, b); return (0); } Function Call

43 Function Call – An Example
1 2 3 4 #include <stdio.h> //function prototype //global variable declaration int main(void) { local variable declaration; statements; fn1( ); fn2( ); return (0); } void fn1(void) { local variable declaration; statements; } void fn2(void) return;

44 Function prototype <output type>
<output type> <functionname>(<input parameter types>); <output type> Queries: int, float,… Command: void <function name> is an identifier <input parameter list> <type>, <type>, … int, float, … Void

45 Function declaration is optional if program is developed in a single file
void my_info(void){ printf("My name is Ahmad Ahmadi\n"); printf("My student number: \n"); } int main(void){ my_info(); printf(" \n"); my_info(); return 0;

46 printf("Student number: 9522222\n");
Example /* Function declaration */ void my_info(void); int main(void){ printf("This is my info"); my_info(); /* Function call */ printf("============="); return 0; } /* Function definition */ void my_info(void){ printf("Student name is Ali Hosseini\n"); printf("Student number: \n");

47 An Example #include <stdio.h>
int calSum(int,int); /*function prototype*/ int main(void) { ….. sum = calSum(num1,num2); /* function call */ } int calSum(int val1, int val2) /*function header*/ …… Formal Parameters Actual Parameters Formal Parameters

48 Purposes of Function Prototype
So compiler knows how to compile calls to that function, i.e., number and types of arguments type of result As part of a “contract” between developer and programmer who uses the function As part of hiding details of how it works and exposing what it does. A function serves as a “black box.” Prototype only needed if function definition comes after use in program Introduction to Functions CS-2301, B-Term 2009 48

49 An Example printf("var1 = %.2f\n" #include <stdio.h>
/* function prototype */ double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0; } /* function definition */ double product(double x, double y) double result; result = x * y; return result; Function prototype Like a variable declaration Tells compiler that the function will be defined later Note semicolon!! Function definition See previous slide Note, NO semicolon Function return return statement terminates execution of the current function Control returns to the calling function if return expression; then value of expression is returned as the value of the function call Only one value can be returned this way Function call main() is the 'calling function' product() is the 'called function' Control transferred to the function code Code in function definition is executed The function prototype declares the return data type, the function's name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Function prototype helps reduce program errors, because by using it, the compiler can then detect the wrong number or the wrong type of data items that are passed to the function

50 Flow of Control First statement executed in any program is the first statement in the function main( ) When another function called logical control passed to first statement in that function’s body program proceeds through sequence of statements within the function When last statement of function executed control returns to where function was called control given to next command after the call

51 1. Function prototype (3 parameters)
1 /* Fig. 5.4: fig05_04.c 2 Finding the maximum of three integers */ 3 #include <stdio.h> 4 5 int maximum( int, int, int ); /* function prototype */ 6 7 int main() 8 { 9 int a, b, c; 10 11 printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %d\n", maximum( a, b, c ) ); 14 15 return 0; 16 } 17 18 /* Function maximum definition */ 19 int maximum( int x, int y, int z ) 20 { 21 int max = x; 22 23 if ( y > max ) max = y; 25 26 if ( z > max ) max = z; 28 29 return max; 30 } 1. Function prototype (3 parameters) 2. Input values 2.1 Call function Function definition Program Output Enter three integers: Maximum is: 85

52 Receive nothing and return nothing
#include <stdio.h> void greeting(void); /* function prototype */ int main(void) { greeting( ); return(0); } void greeting(void) printf("Have fun!! \n"); Have fun!! Press any key to continue

53 Receive nothing and return int
#include <stdio.h> int getInput(void) /* ignore function prototype */ { int number; printf("Enter a number:"); scanf("%d",&number); return number; } int main(void) int num1, num2, sum; num1 = getInput( ); num2 = getInput( ); sum = num1 + num2; printf("Sum is %d\n",sum); return(0); Enter a number: 5 Enter a number: 4 Sum is 9 Press any key to continue

54 Receive parameter(s) and return nothing
#include <stdio.h> int getInput(void); void displayOutput(int); int main(void) { int num1, num2, sum; num1 = getInput(); num2 = getInput(); sum = num1 + num2; displayOutput(sum); return(0); } int getInput(void) int number; printf("Enter a number:"); scanf("%d",&number); return number; void displayOutput(int sum) printf("Sum is %d \n",sum); Enter a number: 5 Enter a number: 4 Sum is 9 Press any key to continue

55 Exmaple: my_fabs (Version 1)
double my_fabs(double x){ double res; if(x >= 0) res = x; else res return = -1 * x; res; } void main(void){ double d = -10; double b; b = my_fabs(d); printf("%f\n", b); printf("%f\n", my_fabs(-2 } 10 20 * b));

56 Exmaple: my_fabs (Version 2)
double my_fabs(double x){ if(x >= 0) return x; return (-1 * x); } void main(void){ double d = -10; double b; b = my_fabs(d); printf("b = %f\n", b); b = my_fabs(-2 * d); printf("b = %f\n", b); }

57 Output of functions A function can produce at most one output
Output of functions can be dropped sin(f); //we drop the output of sin

58 Casting in functions Cast for input Cast for output Prototype: void
f(int a, double b);  Call: f(10.1, 20.2); Cast for output Prototype: int Call: double d Cast in return int f(int a){ f(int a); = f(10); ... return 10.20 }

59 Scope of Variables Until now, Variables Scope of variable
Are declared in the start of functions Are used any where in the function after declaration Can we used them outside of function? Can we used them in other functions? Scope of variable A range of code that the variable can be used  Variable cannot not be used outside of its scope Compile error

60 Scopes vs. Blocks Scopes are determined by Blocks Variables
Start with { and finished by } Example: statements of a function, statement of a if or while, … Variables Can be declared in a block Can be used in the declared block Cannot be used outside the declared block The Declared block is the scope of the variable

61 Variables in Blocks #include <stdio.h> int main(void){ int i;
for(i = 1; i <= 10; i++){ int number; printf("Enter %d-th number: scanf("%d", &number); if((number % 2) == 0) ", i); printf("Your number is even\n"); else printf("Your number is odd\n"); } /* compile error printf("The last number is %d\n", number); */ return 0;

62 Nested Scopes/Blocks Scopes can be nested
Example: Nested if, nested for, … int main(){ //block 1 int i; { //block 2 int j; { //block 3 int k; } int m; return 0;

63 Variables in Nested Blocks
All variables from outer block can be used inner blocks Scope of outer block contains the inner block Variables in inner block cannot be used in outer block Scope of the inner block does not contains the outer block

64 Variables in Nested Blocks: Example
int k; for(int i = 0; i < 10; i++){ /* block 1 */ if(i > 5){ /* block 2 */ int j = i; ... } while(k > 10){ /* block 3 */ int l = i; /* int m = ... j; compile error */ /* k = l; compile error */ }

65 Same Variables in Nested Block
If a variable in inner block has the same identifier of a variable in outer block The inner variable hides the outer variable Changing inner variables does not change outer variable int i=10 ,j = 20; printf("outer i =%d, %d\n",i,j); if(true){ int i=100; j = 25; }

66 Local Variables All defined variables in a function are the local variable of the function Can ONLY be used in the function, not other functions void func(void){ int i, j; float f; /* These are local variables */ } int main(void){ i = 10; /* compile f = 0; /* compile error, error, why? */ why? */

67 Global Variables Global variables are defined outside of all functions
Global variables are initialized to zero Global variables are available to all subsequent functions void f(){ i = 0; // compile error } int i; void g(){ int j = i; // g can use i

68 Global Variables: Example
int i, j; float f; void func(void){ printf("i = %d printf("f = %f i = 20; } void f(){ \n", i); \n", f); printf("%d", i); } int main(void){ f = 1000; func(); f(); return 0;

69 Exmaple: my_fabs (Version 1)
double my_fabs(double x){ double res; if(x >= 0) res = x; else res return = -1 * x; res; } void main(void){ double d = -10; double b; b = my_fabs(d); printf("%f\n", b); printf("%f\n", my_fabs(-2 } 10 20 * b));

70 Exmaple: my_fabs (Version 2)
double my_fabs(double x){ if(x >= 0) return x; return (-1 * x); } void main(void){ double d = -10; double b; b = my_fabs(d); printf("b = %f\n", b); b = my_fabs(-2 * d); printf("b = %f\n", b); }

71 Parameter Passing by Global Variables: my_fabs (V.3)
double x; void my_fabs(void){ x = (x > 0) ? x : -1 * x; } Don’t use this method. Parameters should be passed by input parameter list. Global variable are used to define (large) variables that are used in many functions void main(void){ double b, d x = d; = -10; my_fabs(); b = x; printf("b = %f\n", b); }

72 Prototype Example #include <stdio.h> int max(int x,int y); int main(void) { int a = 10, b = 20; int m = max(a, b); printf("m is %d", m); return 0; } int max(int x, int y) if (x > y) return x; else return y;

73 Prototype Example #include <stdio.h> int max(int,int); int main(void) { int a = 10, b = 20; int m = max(a, b); printf("m is %d", m); return 0; } int max(int x, int y) if (x > y) return x; else return y;

74 Prototype Example #include <stdio.h> int max(int a,int b); int main(void) { int a = 10, b = 20; int m = max(a, b); printf("m is %d", m); return 0; } int max(int x, int y) if (x > y) return x; else return y;

75 How Function Call Works
Function call is implemented by “stack” Stack is a part of main memory When a function calls Its variables including the inputs are allocated in stack The value of input parameters from caller function is pushed to stack of called function When function finished, its stack is freed

76 Example: print_sub function
#include <stdio.h> void print_sub(double a, double b){ double res; res = a - b; printf("Sub of %f and %f is %f\n", a, b, res); } int main(void){ double d1 = 10, d2 = 20; print_sub(56.0,6.0); //What is the output? print_sub(d1,d2); //output? print_sub(d1,d2 + d2); //output? return 0;

77 print_sub: What happen?
56.0 is copied the memory location a 6.0 is copied to memory location b double a = 56.0; b 6.0; double res; res = a - b;

78 print_sub: What happen?
print_sub(d1, d2); Value of d1 is copied the memory location a Value of d2 is copied to memory location b double a = 10; b 20; double res; res = a - b; Call by Value

79 Call by value In call by value mechanism
The values are copied to the function Only the copy of variable’s value (copy of actual parameter’s value) is passed to the function. If we change values in the function The copied version is changed The original value does not affected Any modification to the passed value inside the function will not affect the actual value

80 Call by value – An Example
#include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double A, double B) double result; result = A * B; return result; How are the arguments passed into functions? 'Pass by value' function arguments are expressions In the function call: Expressions are evaluated and copies of their values are put into temporary memory locations The names of the corresponding parameters in the function definition are made to be the names of the copies The values of the expressions in the function call are not changed

81 Call by value – An Example
#include <stdio.h> int calSum(int,int); /*function protototype*/ int main(void) { int sum, num1, num2; printf("Enter two numbers to calculate its sum:\n"); scanf("%d%d",&num1,&num2); sum = calSum(num1,num2); /* function call */ printf("\n %d + %d = %d", num1, num2, sum); return(0); } int calSum(int val1, int val2) /*function definition*/ int sum; sum = val1 + val2; val2 = 100; return sum; 4 num2 9 num1 13 sum 4 num2 9 num1 ? sum ? num2 num1 sum 100 val2 9 val1 13 sum 4 val2 9 val1 13 sum 4 val2 9 val1 ? sum Enter two numbers to calculate its sum: 4 9 4 + 9 = 13 Press any key to continue

82 Example: print_sub function
#include <stdio.h> void print_sub(double a, double b){ double res; res = a - b; printf("Sub of %f and %f is %f\n", a, b, res); } int main(void){ double d1 = 10, d2 = 20; print_sub(56.0,6.0); //What is the output? print_sub(d1,d2); //output? print_sub(d1,d2 + d2); //output? return 0;

83 add function (wrong version)
void add(double a, double b, double res = a + b; res){ return; } int main(void){ double d1 = double 10.1, d2 = 20.2; result = 0; add(56.0, 6.7, result); = %f\n", printf("result result); result = 0 add(d1, d2, result); printf("result = %f\n", result); result = 0 }

84 Call by reference Call by reference
In this method, the reference (memory address) of the variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value

85 Call by reference 10 b a 5 b 1 a b a main -5 b a main 5 b 1 a CalByVal
#include <stdio.h> void CalByVal(a, b) { a = 0; b = 10; } void CalByRef(int *a, int *b) // CalByRef(int *p, int *q) *a = 0; *b = -5; int main(void) int a = 1, b = 5; printf("Before cal CalByVal: a = %d, b = %d\n", a, b); CalByVal(a, b); printf("After cal CalByVal: a = %d, b = %d\n", a, b); printf("Before cal CalByRef: a = %d, b = %d\n", a, b); CalByRef(&a, &b); printf("After cal CalByRef: a = %d, b = %d\n", a, b); return 0; /* Exit program. */ CalByVal 10 b a CalByVal 5 b 1 a CalByRef b a main -5 b a main 5 b 1 a

86 Call by reference Instead of product()
#include <stdio.h> void prod_sum(double x, double y, double *ptr1, double *ptr2); int main() { double var1 = 3.0, var2 = 5.0; double prod, sum; prod_sum(var1, var2, &prod, &sum); printf("var1= %g\n" "var2= %g\n",var1, var2); printf("prod= %g\n" "sum= %g\n", prod, sum); } /* function definition */ void prod_sum(double A, double B, double *rslt_prod, double *rslt_sum) *rslt_prod = A * B; *rslt_sum = A + B; Instead of product() prod_sum() How can I get the function to give both product and sum? put * in front of variable name in prototype and function definition put & in front of variable names in function call Called 'Pass by Reference'

87 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type A recursive function is a function invoking itself, either directly or indirectly Recursion: A → B → C → D → A Concept of recursive function (generally): A recursive function is called to solve a problem The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer if (stopping case) solve it else reduce the problem using recursion

88 Recursion Recursive Algorithm
An algorithm uses itself to solve the problem There is a basic problem with known solution Recursive Algorithms are implemented by recursive functions Recursive function A function which calls itself There is a condition that it does not call itself

89 Recursion Any problem that can be solved recursively can also be solved iteratively (using loop) Recursive functions are slow and takes a lot of memory space compared to iterative functions So why bother with recursion? There are 2 reasons: Recursion approach more naturally resembles the problem and therefore the program is easier to understand and debug Iterative solution might not be apparent

90 An Example: xy In this example, we want to calculate x to the power of y i.e. xy If we analyze the formula for xy, we could see that xy could be written as (x being multiplied to itself, y times) An example is 24, which can be written as 24 = 2 x 2 x 2 x 2 (in this case, x = 2, y = 4) 24 could also be rewritten as 24 = 21 x where 21 = 2 (i.e the number itself) Therefore, we could divide the problem into two stage: Simplest case: when y = 1, the answer is x Recursive case, we need to solve for x * x(y-1)

91 Introduction Factorial GCD n! = n x n-1 x … x 2 x 1
GCD(a, b) = Euclidean Algorithm GCD(a, b) = GCD(b, a mod b) There is a simple (basic) problem which we can solve it directly (without recursion) Factorial: 1! = 1 GCD: b == 0

92 Euclid’s algorithm in C
int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n;

93 Recursion solution of xy
#include <stdio.h> double XpowerY(double, int); int main(void) { double power, x; int y; printf("Enter the value of x and y:\n"); scanf("%f%d", &x, &y); power = XpowerY(x, y); printf("%.2f to the power of %d is %.2f\n\n", x, y, power); return(0); } double XpowerY(double x, int y) if (y ==1) return x; else return x * XpowerY(x, y-1); Enter the value of x and y: 2 3 2.00 to the power of 3 is 8.00 Press any key to continue

94 #include <stdio.h>
int factorial(int n){ int res, tmp; if(n == 1) /* The basic problem */ res = 1; else{ /* recursive call */ tmp = factorial(n - 1); res = n * tmp; } return res; } void main(void){ int i = 4; int fac = factorial(i); printf("%d! = %d\n", i, } fac);

95 Factorial int fact(int n) { int factres = 1; while(n>1)
#include <stdio.h> double fact(double); int main(void) { double n, result; printf("Please enter the value of n:"); scanf("%lf", &n); result = fact(n); printf(" %.f! = %.2f\n", n, result); return(0); } double fact(double n) if (n <= 1) return 1; else return n * fact(n-1); int fact(int n) { int factres = 1; while(n>1) factres = factres*n; n--; } return (factres); Enter the value of n: 3 3! = 6.00 Press any key to continue

96 How C Maintains the Recursive Steps
C keeps track of the values of variables by the stack data structure. Recall that stack is a data structure where the last item added is the first item processed There are two operations (push and pop) associated with stack a b c b c d b c pop push d

97 How C Maintains the Recursive Steps
Each time a function is called, the execution state of the caller function (e.g., parameters, local variables, and memory address) are pushed onto the stack When the execution of the called function is finished, the execution can be restored by popping up the execution state from the stack

98 #include <stdio.h>
int factorial(int n){ int res, tmp; if(n == 1) /* The basic problem */ res = 1; else{ /* recursive call */ tmp = factorial(n - 1); res = n * tmp; } return res; } void main(void){ int i = 4; int fac = factorial(i); printf("%d! = %d\n", i, } fac);

99 Function Call Graph factorial(4) n = 4, tmp = ?, res = ? factorial(3)
factorial(1) n = 1, res = ?

100 Function Call Graph factorial(4) n = 4, tmp = ?, res = ? factorial(3)
1 factorial(1) n = 1, res = 1

101 Function Call Graph factorial(4) n = 4, tmp = ?, res = ? factorial(3)
2 factorial(2) n = 2, tmp = 1, res = 2 1 factorial(1) n = 1, res = 1

102 Function Call Graph factorial(4) n = 4, tmp = ?, res = ? 6
2 factorial(2) n = 2, tmp = 1, res = 2 1 factorial(1) n = 1, res = 1

103 Function Call Graph factorial(4) n = 4,tmp = 6,res = 24 6 factorial(3)
1 factorial(1) n = 1, res = 1

104 Recursive Steps of xy x = 2; y = 1; return x; x = 2; y = 2; 2
#include <stdio.h> double XpowerY(double, int); int main(void) { double power, x; int y; printf("Enter the value of x and y:\n"); scanf("%lf%d", &x, &y); power = XpowerY(x, y); printf("%.2f to the power of %d is %.2f\n\n", x, y, power); return(0); } double XpowerY(double x, int y) if (y ==1) return x; else return x * XpowerY(x, y-1); 2 x = 2; y = 2; x * XpowerY(2, 1) 2 * 2 x = 2; y = 3; x * XpowerY(2, 2) 2 * 4 x = 2; y = 4; x * XpowerY(2, 3) 2*8

105 Examples Print digits: left-to-right and right-to-left
Recursive version of GCD? Recursive version of Fibonacci numbers Fibonacci numbers  1, 1, 2, 3, 5, 8, ... Print digits: left-to-right and right-to-left

106 #include <stdio.h>
int GCD(int a, int b){ if(b == 0) return a; else return GCD(b, a % b); } int main(void){ printf("GCD(1, 10) printf("GCD(10, 1) = %d \n", GCD(1, 10)); GCD(10, 1)); printf("GCD(15, 100) printf("GCD(201, 27) = %d \n", GCD(15, 100)); = %d \n", GCD(201, 27)); return 0; }

107 #include <stdio.h>
int fibo(int n){ if(n == 1) return 1; if(n == 2) else else return fibo(n - 1) + fibo(n - 2); } int main(void){ printf("fibo(1) printf("fibo(3) printf("fibo(5) printf("fibo(8) = %d\n", fibo(1)); fibo(3)); fibo(5)); fibo(8)); return 0; }

108 Fibonacci /* Iterative Version */ int fibonacci(int k) { int a,b,c,i; if (k <= 1) return 1; else a = 1; b = 1; i = 2; while (i <= k) c = a + b; a = b; b = c; i++; } return(c); int Fib (int n) { int temp = 1; /* handles base cases */ if (n > 2) temp = Fib(n-1) + Fib(n-2); return temp; }

109 Fibonacci x = 5; temp = 1; temp = 1 + Fib(1); return temp;
temp = Fib(2) + Fib(1); return temp; x = 5; temp = 1; temp = ; return temp; x = 5; temp = 1; temp = 1 + Fib(1); return temp; x = 1; temp = 1; return temp; x = 5; temp = 1; temp = 1 + Fib(1); return temp; x = 5; temp = 1; temp = Fib(2) + Fib(1); return temp; x = 5; temp = 1; temp = ; return temp; int Fib (int x) { /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (x > 2) /* other cases */ temp = Fib(x-1) + Fib(x-2); return temp; } x = 4; temp = 1; temp = 2 + 1; return temp; x = 4; temp = 1; temp = 2 + Fib(2); return temp; x = 4; temp = 1; temp = Fib(3) + Fib(2); return temp; x = 5; temp = 1; temp = 3 + 2; return temp; x = 5; temp = 1; temp = Fib(4) + Fib(3); return temp; x = 5; temp = 1; temp = 3 + Fib(3); return temp;

110 Fibonacci 5 fib(5) fib(3) fib(4) fib(3) fib(2) fib(2) fib(1) fib(2)
int Fib (int n) { /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (n > 2) /* other cases */ temp = Fib(n-1) + Fib(n-2); return temp; } fib(5) 3 2 fib(3) fib(4) 1 1 2 1 fib(3) fib(2) fib(2) fib(1) 1 1 fib(2) fib(1)

111 #include <stdio.h>
76 #include <stdio.h> void print_digit_right_left(int n){ int digit = n % 10; printf("%d ", digit); if(n >= 10) print_digit_right_left(n / 10); } int main(void){ printf("\n print_digit_right_left(123): "); print_digit_right_left(123); printf("\n print_digit_right_left(1000): "); print_digit_right_left (1000); return 0; }

112 #include <stdio.h>
void print_digit_left_right(int n){ if(n >= 10) print_digit_left_right(n / 10); int digit = n % 10; printf("%d ", digit); } int main(void){ printf("\n print_digit_left_right(123): "); print_digit_left_right(123); printf("\n print_digit_left_right(1000): "); print_digit_left_right (1000); return 0; }

113 Indirect recursion What we have seen are direct recursion
A function calls itself directly Indirect recursion A function calls itself using another function Example: Function A calls function B Function B calls function A

114 #include <stdio.h>
#include <stdbool.h> bool bool is_even(int n); is_odd(int n); bool is_even(int n){ if(n == 0) return if(n == 1) return else true; false; is_odd(n - 1); } bool is_odd(int n){ if(n == 0) return false; if(n == 1) return true; else return is_even(n - 1); }

115 int main(void){ if(is_even(20)) printf("20 else is even\n"); is odd\n"); if(is_odd(23)) printf("23 else is odd\n"); is even\n"); return 0; }

116 Bugs & Avoiding Them Recursion must finish, be careful a bout basic problem in the recursive functions No base problem  Stack Overflow

117 Exercise What is the output of the following program
#include <stdio.h> void function3() { printf("In function 3\n"); function2(); } int main() function1(); function3(); return 0; void function2() { printf("In function 2\n"); } void function1() function2(); printf("In function 1\n"); In function 2 In function 1 In function 3

118 Storage Classes Variables have attributes Have seen name, type, value
Scope Where variable can be referenced in program Storage class How long variable exists in memory Linkage For multiple-file program, which files can use it

119 Organizing Multi-File Programs
A large C program should be divided into multiple files // main.c #include <stdio.h> void Test() { // … } int main() // … return 0; } // math.c double mathVar; double sin() { double tempSin; // … return tempSin; }

120 Scope of Identifiers Scope of a declaration of an identifier
The region of the program that the declaration is active (i.e., can access the variable, function, label, etc.) Five types of scope: Program (global scope) File Function prototype Function Block ("between the { } scope")

121 Scope of Identifiers - Program Scope
Program (global) scope if declared outside of all functions "Visible" to all functions from point of declaration Use only when necessary and then very carefully!! If there exist a local variable and a global variable with the same name, the compiler will refer to the local variable Visible to functions in other source files #include <stdio.h> int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // … } /* function definition */ double product(double x, double y) double result; a = 20; result = x * y; return result; a = 10 a = 20 Switch to ChIDE and show a modified version of the program with printf() statements included (var_scope.c) that show variable a is 'visible' throughout the program. Assign a new value in function to show how variable a is accessible and changeable. Beware!! Try to avoid using global variables. The temptation is that the variable is visible to all modules - simple and fast … But, it makes maintenance more difficult. Enables potential conflicts between modules where two programmers working on separate modules might use the same name for different global variables. Can introduce bugs that are hard to find. Any time you see a source file with global variables defined, you need to go through all source files that are part of the program to make sure there are no conflicts. Adds other restrictions like the ANSI standard only guaranteeing that a compliant compiler recognize the first 6 characters of a global variable, and may suspend case sensitivity. Better to pass data directly or via pointers.

122 An Example extern int a = 10; // File name: main.c
#include <stdio.h> int a = 10; /* function definition */ double product(double x, double y) { double result; // … a = 70; return result; } int main() a = 80; // File name: ExternFile.c extern int a = 10; /* function definition */ void TestExtern() { // … a = 90; }

123 Scope of Identifiers - File Scope
#include <stdio.h> static int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // … } /* function definition */ double product(double x, double y) double result; result = x * y; return result; File scope Keyword static Makes variable a ‘visible’ only within this source file Use file scope to avoid naming conflict if multiple source files are used

124 An Example extern int a = 10; static int a = 10; // File name: main.c
#include <stdio.h> static int a = 10; /* function definition */ double product(double x, double y) { double result; // … a = 70; return result; } int main() a = 80; // File name: ExternFile.c extern int a = 10; /* function definition */ void TestExtern() { // … a = 90; }

125 Scope of Identifiers - Function Prototype Scope
#include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double A, double B) double result; result = A * B; return result; Function prototype scope Identifiers x and y are not visible outside the prototype Thus, names in the prototype do not have to match names in the function definition MUST match types, however! double product(double x, double x); will produce an error double product(double, double); will also work

126 Scope of Identifiers - Function Scope
Active from the beginning to the end of a function #include <stdio.h> int main() { int a; // … return 0; } int FunctionScopeTest() int b;

127 Scope of Identifiers - Block Scope
Block (local) scope A block is a series of statements enclosed in braces { } The identifier scope is active from the point of declaration to the end of the block ( } ) Nested blocks can both declare the same variable name and not interfere #include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // … } /* function definition */ double product(double x, double y) double result; // a = 60; Error result = x * y; return result; Show how this works in ChIDE using var_scope_block.c Show also scope_nested_blocks.c Note: a variable declared in a block that also contains a block (nested block) is active within the contained block, but not vice-versa.

128 Storage Classes Storage class(Refers to the lifetime of a variable)
How memory is allocated for the variable Until when the variable exists How it is initialized Storage classes in C  Automatic External  Static Register

129 Storage Classes Refers to the lifetime of a variable
Local variables only exist within a function by default. When calling a function repeatedly, we might want to Start from scratch – reinitialize the variables The storage class is ‘auto’ Continue where we left off – remember the last value The storage class is ‘static’ Another two storage classes (seldomly used) register (ask to use hardware registers if available) extern (global variables are external)

130 How use? storage_classes variable_type variable_name int auto float
double char auto register static extern

131 Storage Classes: Automatic
Automatic storage class Variable created when program enters its block Variable destroyed when program leaves block Only local variables of functions can be automatic Automatic by default keyword auto explicitly declares automatic

132 Storage Classes: Automatic
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables. auto is the default storage class for local variables. { int Count; auto int Month; }

133 Auto - Example #include <stdio.h> void auto_example(void); int main(void) { int i; printf("Auto example:\n"); auto_example( ); return(0); } void auto_example(void) auto int num = 1; printf(" %d\n",num); num = num + 2; Auto example: 1 Press any key to continue

134 Storage Classes: External
All global variables are external by default Are generated when program starts Are destroyed when program finishes Usage of keyword “extern” To use global variables in other files To emphasize that variable is global This usage is optional

135 Storage Classes: Static
Keyword “static” comes before them For local variables: 1) Generated in the first run of the block 2) Destroyed when program finishes 3) Initialized If no value  initialized by 0 Only initialized in the first run of the block

136 Static storage class However the static keyword can be applied to a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds

137 Static - Example #include <stdio.h> void auto_example(void); int main(void) { int i; printf("Static example:\n"); static_example( ); return(0); } void static_example(void) static int num = 1; printf(" %d\n",num); num = num + 2; Static example: 1 3 5 Press any key to continue

138 Storage Classes: Static
Keyword “static” comes before them For global variables: 1) Generated when program starts 2) Destroyed when program finishes 3) Always initialized If no value  initialized by 0 4) Is not accessible for other files

139 Storage Classes: Register
Keyword “register” comes before them Can be used for local variables Compiler tries to allocated the variable in registers of CPU But does not guaranteed Registers are very fast and small memories Improve performance

140 The register Storage Class
The register storage class is used to define local variables that should be stored in a register instead of RAM. The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. { register int miles; }

141 Storage Classes, Register: Examples
int i; for(i = 0; i < 100; i++)

142 Storage Classes: Examples
int i; void func(void){ int j; printf("i = %d \n", i); printf("j = %d \n", j); i = 20; } int main(void){ func(); i = 30; return 0; i =??? j =??? i =??? j =??? i = 0 j = 0 i = 20 j = 0 i = 30

143 Storage Classes, Static:Examples
void func(void){ int j; static int i; printf("i = %d \n", i); printf("j = %d \n", j); i = 20; } int main(void){ func(); /* i = 30; compile error, why? */ return 0; i = ??? j = ??? i = ??? j = ??? i = 0 j = 0 i = 20

144 Storage Classes, Static:Examples
void func(void){ int j; static int i=10; printf("i = %d \n", i); printf("j = %d \n", j); i = 20; } int main(void){ func(); return 0; i = ??? j = ??? i = ??? j = ??? i = 10 j = 0 i = 20

145 Storage Classes, Extern: Examples
int i = 10, j = 20; void print(void){ printf("i = %d, j = %d\n", i, j); } int main(void){ extern int i; // i refers the global int j; j is new variable print(); i = ?, j = ? i = 10, j = 20 i = 1000; j = 2000; print(); i = ?, j = ? i = 1000, j = 20 return 0; }

146 Inline Functions & Macro
Function call using stack has its overhead 2 approaches to reduce the overhead inline function  To ask from compiler to compile it as inline, but no guarantee inline Macros #define int f(float x) PRINT_INT(X) printf("%d\n", X)

147 Inline Functions If the same sequence of steps or instructions is required in several different places in a program, you will normally write a function for the steps and call the function whenever these steps are required.  But this involves time overhead. Also can place the actual sequence of steps wherever they are needed in the program, but this increase the program size and memory required to store the program.  Also need retyping process or copying a block of program. Use function if the sequence of steps is long.  If small, use macros or inline function, to eliminate the need for retyping and time overhead.

148 Example: GCD #define PRINT_INT(x) printf("%d\n",x)
inline int gcd(int a, int temp; while(b != 0){ temp = a % b; a = b; b = temp; } return a; void main(void){ int i = 20, j = 35, g; g = gcd(i, j); int b){ /* return gcd of a and b */ printf("GCD of %d and %d = PRINT_INT(g); ", i , j); g = gcd(j, i); printf("GCD of %d and %d = PRINT_INT(g); ", j , i); }

149 Macros Need #define compiler directive.  For example, to obtain just the area of a triangle, we could create a macro,

150 C FUNCTIONS Example for finding an average of 4 numbers (a, b, c and d), #define avg(x, y) (x + y)/2.0 Then in the program we can define something like this, avg1 = avg(avg(a, b), avg(c, d)) Doing the substitution, avg4 = ((a + b)/2.0 + (c + d)/2.0) / 2.0 The drawback: nesting of macros may result in code that difficult to read.

151 Header Files Header files contain Header files ending with .h
Function prototypes Definitions of data types and constants Header files ending with .h Programmer-defined header files #include “myheader.h”

152 Typical C Programming Style
A lot of small C programs, rather than a few large ones Each .c file contains closely related functions Usually a small number of functions Header files to tie them together

153 Header files In applications with multiple C programs, function prototypes are typically provided in header files I.e., the ‘.h’ files that programmers include in their code Grouped by related functions and features To make it easier for developers to understand To make it easier for team development To make a package that can be used by someone else


Download ppt "Lecture 9-13 Functions."

Similar presentations


Ads by Google