Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Similar presentations


Presentation on theme: "Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== ======="— Presentation transcript:

1

2 Functions

3 A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== ======= to separate sections of output.

4 Solution #include int main (void) { /* produce some output */ /* print banner line */ printf(“==============\n”) ; /* produce more output */ printf(“==============\n”); /* produce even more output */ printf(“==============\n”); /* produce final output */ }

5 Critique Redundant code What if we want to change the display e.g. to print a blank line before and after each line with =’s ? What if we want to print banner lines in some other program?

6 The Solution: Functions Definition: A function is a named code sequence A function can be executed by using its name as a statement or expression. The function may have parameters - information that can be different each time the function is executed. The function may compute and return a value.

7 Why use functions ? Functions provide an abstraction when writing a program - allow low-level details to be packaged. Able to package a computation we need to perform at multiple spots within a program. Write once, use many times. If changes are needed, they only have to be done once, in one place.

8 Why use functions ? Allows the programmer to create a program from smaller, simpler sub-components. Many programs are far too large to understand all at once. Functions give us a way to break a large program into smaller pieces A function should perform a well-defined task.

9 Common functions main (void) {... } Function definition for main() printf (“%d + %d is %d\n”,x,y,z); scanf (“%d%d”, &x, &y) ; limit = sqrt ((double) num); Function calls

10 More common functions Every standard C compiler comes with a set of standard libraries. #include Tells the compiler you will use the standard IO library #include C’s standard math library functions: sqrt, pow, sin, cos, exp,... isspace,...

11 Defining your own functions You may define your own functions in your programs You define a function by giving its name and writing the code that is executed when the function is called.

12 Function definition /* print banner line */ void print_banner (void) { printf (“=========”); printf (“=========\n”); } heading comment function name function body (statements to be executed) A function can have ANY number of ANY kind of statements

13 /* print banner line */ void print_banner (void) { printf (“=========”); printf (“=========\n”); } void void has two different roles in this function definition. indicates that the function does not return (have) an output value. indicates that the function has no parameters.

14 Calling a function int main (void) { /* produce some output */... print_banner (); /* produce more output */... print_banner (); /* produce final output */... print_banner (); } To execute the function, it is called or invoked from within a program or another function. Note: A function that does not return a value can be called wherever a statement is allowed.

15 Terminology main () is the caller print_banner() is the callee. main() invokes / calls print_banner() 3 times. print_banner() is called from main()

16 Function Control Flow /* print banner line */ void print_banner (void) { printf(“************ **\n”); } int main (void) {... print_banner ();... print_banner (); return (0); } main (void) { print_banner (); print_banner (); } print_banner { } print_banner { }

17 Control Flow All C programs Start at main () /*no matter where main()is */ Continue in top-to-bottom order, statement by statement, unless the order is changed by: function call function return if loops

18 Function Type and Value A function can return a value. Like all values in C, a function return value has a type. The function has the type of its returned value. /* Get number from user */ int get_input (void) { int num; printf (“Enter a number:”); scanf (“%d”, &num); return (num); } function type return statement returned value

19 Calling a function A value-returning function is called by including it in an expression. int main (void) { int x, y; x = get_input() ; y = get_input() ; printf (“ %d + %d = %d\n”, x, y, x+y); return (0); } Note : A value returning function can be used anywhere an expression of the same type can be used.

20 return In a value-returning function (result type is not void) return does two distinct things : 1. specify the value returned by the execution of the function 2. terminate that execution of the function. In a void function: return is optional at the end of the function body. return may also be used to terminate execution of the function explicitly. No return value should appear following return.

21 void compute_and_print_itax () { double income; scanf (“%f”, &income); if (income < 50000){ printf (“Income tax = Nil\n”); return; } if (income < 60000){ printf (“Income tax = %f\n”, 0.1*(income-50000); return; } if (income < 150000) { printf (“Income tax = %f\n”, 0.2*(income-60000)+1000); return ; } printf (“Income tax = %f\n”, 0.3*(income-150000)+19000); } Terminate function execution before reaching the end

22 Function parameters It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters. The function specifies its inputs as parameters in the function declaration. /* Find area of a circle with radius r */ double area (double r) { return (3.14159*r*r) ; } parameter

23 Arguments The function call must include a matching argument for each parameter. When the function is executed, the value of the argument is substituted for the parameter. int main (void) {... double circum;... area1 = area(circum/2.0);... } double area (double r) { return (3.14*r*r); } parameter passing

24 Control and data flow When a function is called: (1) control transfers to the function body (2) argument values are copied (3) the function executes (4) control and return value return to the point of call.

25 Control and data flow int main (void) { double x, y, z; y=6.0; x = area(y/2.0);... z = area(7.88);... return (0); } double area (double r) { return (3.14*r*r); } 3. 0 13.26 7.88 194.976

26 Style notes Put comments above a function body to specify completely what the function does, including the significance of all the parameters. /* Find area of a circle with radius r */ double area (double r) { return (3.14159*r*r) ; }

27 Multiple parameters a function may have more than one parameter arguments must match parameters in number, order and type. void main () { double x, y; int z; char op;... z = operate (x, y, op);... } arguments int operate (double x, double y, char op) { switch (op) { case ‘+’ : return x+y+0.5 ; case ‘~’ : if (x>y) return x-y + 0.5; return y-x+0.5; case ‘x’ : return x*y + 0.5; default : return –1; } parameters

28 Rules for using functions Arguments must match parameters: in number in order in type A function can only return one value. but it might contain more than one return statement. In a function with return type T, the return expression must be of type T. A function with return type T can be used anywhere an expression of type T can be used.

29 Local variables A function can define its own local variables. The locals have meaning only within the function. Each execution of the function uses a new set of locals Local variables cease to exist when the function returns Parameters are also local.

30 Local variables /* Find the area of a circle with diameter d */ double circle_area (double d) { double radius, area; radius = d/2.0; area = 3.14*radius*radius; return (area); } parameter local variables

31 Defining function prototypes Functions should be declared before they are used (invoked). Instead of writing the complete function, you can use function prototypes to declare a function so that it can be used. It is a good programming style to use function prototypes.

32 Function prototypes int operate (double x, double y, char op) ; int operate (double, double, char); void print_average (double, int); int get_intput (void); void print_banner (void); Write a function prototype near the top of the program Can use the function anywhere thereafter.

33 #define TRUE 1 #define FALSE 0 /* Find if x is a factor of y */ int isFactor (int x, int y) { if (y%x == 0) return TRUE; return FALSE; } /* Rteurns true if x is a prime number */ int isPrime (int x) { int factor; for (factor=2; factor <= sqrRt(x); factor++) if (isFactor(factor, x)) return FALSE; } /* Finds all prime numbers in acertain range */ void main (void) { int i, start, limit; scanf (“%d%d”, &start,&limit); for (i=start; i<=limit; i++) { if (isPrime (i)) printf (“%d “, i); } Example :

34 Back to Arrays

35 Arrays as parameters of functions An array passed as a parameter is not copied

36 Array operations #define MAXS 100 int insert (int[], int, int, int) ; int delete (int[], int, int) ; int getelement (int[], int, int) ; int readarray (int[], int) ; main (){ int a[MAXS]; int size; size = readarray (a, 10) ; size = insert (a, size, 4, 7) ; x = getelement (a, size, 3) ; size = delete (a, size, 3) ; }

37 Array operations #define MAXS 100 int insert (int[], int, int, int) ; int delete (int[], int, int) ; int getelement (int[], int, int) ; int readarray (int[], int) ; main (){ int a[MAXS]; int size; size = readarray (a, 10) ; size = insert (a, size, 4, 7) ; x = getelement (a, size, 3) ; size = delete (a, size, 3) ; } int readarray (int x[], int size){ int i; for (i=0; i<size; i++) scanf(“%d”, &x[i]) ; return size; } int getelement (int x[], int size, int pos){ if (pos <size) return x[pos] ; return -1; } int insert (int x[], int size, int pos. int val){ for (k=size; k>pos; k--) x[k] = x[k-1] ; x[pos] = val ; return size+1; }

38 void reverse (int x[], int size) { } int findmax (int x[], int size) { }

39 void reverse (int x[], int size) { int i; for (i=0; i< (size/2); i++) temp = x[size-i-1] ; x[size-1-1] = x[i] ; x[i] = temp; } int findmax (int x[], int size) { int i, max; max = x[0]; for (i=1; i< size; i++) if (x[i] > max) max = x[i] ; return max; }

40 Searching an Array: Linear and Binary Search

41 Searching Check if a given element (key) occurs in the array. If the array is unsorted : start at the beginning of the array inspect every element to see if it matches the key

42 Linear Search /* If key appears in a[0..size-1], return its location, pos, s.t. a[pos] == key. If key is not found, return -1 */ int search (int a[], int size, int key){ int pos = 0; while (pos < size && a[pos] != key) pos++; if (pos<n) return pos; return -1; }

43 Linear Search int x= {12,-3, 78,67,6,50,19,10} ; Trace the following calls : search (x, 8,6) ; search (x,8,5) ;

44 Searching a sorted array Binary search works if the array is sorted Look for the target in the middle If you don’t find it, you can ignore half of the array, and repeat the process with the other half.

45 Binary Search Strategy What we want : Find split betwen values larger and smaller than x : <=key>key <=key?>key x: 0 n LR 0nLR Situation while searching : Step : Look at [(L+R)/2]. Move L or R to the middle depending on test.

46 Binary Search /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while (_________________){ } ____________________ ; }

47 /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while (_________________){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } ____________________ ; } Binary Search mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid;

48 /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while (_________________){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } ____________________ ; } Binary Search: loop termination L+1 != R

49 /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while ( L+1 != R){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } Binary Search: Return result if (L>=0 && x[L]==key) return L; else return -1;

50 /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while ( L+1 != R){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } if (L>=0 && x[L]==key) return L; else return -1; } Binary Search: Initialization L=-1; R=size;

51 Binary Search Examples -17 -5 3 6 12 21 45 63 50 Trace : binsearch (x, 9, 3); binsearch (x, 9, 145); binsearch (x, 9, 45);

52 Is it worth the trouble ? Suppose you had 1000 elements Ordinary search (if key is a member of x) would require 500 comparisons on average. Binary search after 1st compare, left with 500 elements after 2nd compare, left with 250 elements After at most 10 steps, you are done. What if you had 1 million elements ?

53 Sorting Given an array x[0], x[1],..., x[size-1] reorder entries so that x[0]<=x[1]<=... <=x[size-1]

54 Sorting Problem What we want : Data sorted in order sorted : x[0]<=x[1]<=... <=x[size-1] x: 0 size Initial conditions : unsorted x: 0 size

55 Selection Sort General situation : remainder, unsortedsmallest elements, sorted 0size k Step : Find smallest element, mval, in x[k..size-1] Swap smallest element with x[k], then increase k. x: smallest elements, sorted 0sizek x: mval

56 Subproblem : : /* Yield location of smallest element int[x] in x[0.. size-1];*/ int min_loc (int x[], int, int size) int j, pos; /* x[pos] is the smallest element found so far */ pos = k; for (j=k+1; j<size; j++) if (x[i] < x[pos]) pos = j; return pos; }

57 Selection Sort /* Sort x[0..size-1] in non-decreasing order */ int selsort (int x[], int size){ int k, m; for (k=0; k<size-1; k++){ m = min_loc(x, k, size); temp = a[k]; a[k] = a[m]; a[m] = temp; }

58 Example -1712-5614221345 x: 312-5614221-1745 x: -17-512614221345 x: -17-536142211245 x: -17-536122114245 x: -17-536122114245 x: -17-536122145142 x:

59 Analysis How many steps are needed to sort n things ? Total number of steps proportional to n 2

60 Insertion Sort #define MAXN 100 void InsertSort (int list[MAXN], int size) ; main (){ int index, size; int numbers[MAXN]; /* Get Input */ size = readarray (numbers) ; printarray (numbers, size) ; InsertSort (numbers, size) ; printarray (numbers, size) ; }

61 void InsertSort (int list[], int size){ for (i=1; i<size; i++) item = list[i] ; for (j=i-1; (j>=0)&& (list[j] > i); j--) list[j+1] = list[j]; list[j+1] = item ; }

62 Common pitfalls with arrays in C Exceeding the array bounds int array[10]; for (i=0; i<=10; i++) array[i] = 0; C does not support array declaratiions with variable expressions. void fun (int array, int size){ int temp[size] ;... }

63 Local variables of main : i, start, limit Parameters of isPrime : x Local variables of isPrime : factor Parameters of isFactor : x, y

64 Local Variables Formal parameters and variables declared in a function are local to it. cannot be accessed or used by other functions directly Allocated (created) on function entry. De-allocated (destroyed) on function return. Formal parameters initialized by copying value of actual parameter. (“Call by value”)

65 Call by value void printDouble (int x) { printf (“Double of %d “, x); x *= 2; printf (“is %d\n”, x) ; } void main () { int num=15; printDouble (num); printf (“ num = %d\n”, num); } Note : The parameter of a function can be a constant, variable, expression – anything that has a value. Only the value is passed to the function.


Download ppt "Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== ======="

Similar presentations


Ads by Google