Presentation is loading. Please wait.

Presentation is loading. Please wait.

9. FUNCTIONS.

Similar presentations


Presentation on theme: "9. FUNCTIONS."— Presentation transcript:

1 9. FUNCTIONS

2 Example: Printing a Message
/* Illustrates functions with no arguments */ #include <stdio.h> void print_pun(void) { printf("To C, or not to C: "); printf("that is the question.\n"); } int main(void) print_pun(); return 0;

3 Example: Counting Down
/* Illustrates functions with arguments */ #include <stdio.h> void print_count(int n) { printf("T minus %d and counting\n", n); } int main(void) int i; for (i = 10; i > 0; --i) print_count(i); return 0;

4 Example: Finding the Larger of Two Numbers
/* Illustrates functions that return a value */ #include <stdio.h> int max(int a, int b) { if (a > b) return a; else return b; } int main(void) int i, j; printf("Enter two numbers: "); scanf("%d%d", &i, &j); printf("The larger number is %d\n", max(i, j)); return 0;

5 Defining a Function • A function definition has the following appearance: result-type function-name ( parameters ) { declarations statements } • If a function does not return a value, its result type should be specified to be void. • If the result type is omitted, the function is assumed to return a value of type int. • If a function has no parameters, the word void should appear between the parentheses.

6 Calling a Function • To call a function, give the function name followed by a list of arguments (in parentheses). • A call of a void function must be a statement: print_pun(); print_count(i); • A call of a non-void function returns a value that can be stored in a variable, tested, printed, or used in some other way: k = max(i, j); if (max(i, j) > 10) ... printf("The larger number is %d\n", max(i, j));

7 Calling a Function • The value returned by a non-void function can always be discarded if desired: max(i, j); /* return value is discarded */ To make it clear that the return value is deliberately being discarded, it is possible to put (void) before the call: (void) max(i, j); /* return value is discarded */ • Warning: A call of a function with no arguments must include a pair of empty parentheses. Without the parentheses, the function is not called: f; /* wrong; f is not called */

8 Arguments • All arguments are passed by value. In other words, changing the value of a parameter affects only the function’s local copy. void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } ... swap(x, y); /* the values of x and y are not changed */

9 Arguments • If the type of an argument doesn’t match the type of the matching parameter, the argument will be converted to the proper type automatically: #include <stdio.h> float square(float x) { return x * x; } int main(void) int i; i = 5; printf("The answer is %g\n", square(i)); return 0;

10 Arguments • Warning: Automatic conversion of arguments takes place only if the compiler has previously seen a definition of the function.

11 Array Arguments • When a parameter is a one-dimensional array, the length of the array need not be specified: int find_largest(int a[], int n) { int i, max; max = a[0]; for (i = 1; i < n; i++) if (a[i] > max) max = a[i]; return max; }

12 Array Arguments • find_largest is called in the following way:
#define N 100 int i, b[N]; i = find_largest(b, N); Array arguments are passed by reference: a copy of the array argument is not made Functions cannot return arrays

13 Array arguments If a parameter is a multidimensional array, only the length of the first dimension may be omitted. #define LEN 10 int sum_two_dimensional_array(int a[][LEN], int n) { int i, j, sum = 0; for (i = 0; i < n; i++) for (j = 0; j < LEN; j++) sum += a[i][j]; return sum; }

14 return Statement • The return statement in a non-void function has the form return expression ; The expression is often just a constant or variable, but may be more complicated. • Executing a return statement has two effects: The function immediately returns to where it was called. The value of the specified expression is returned as the value of the function. • If the type of the expression doesn’t match the function’s return type, the expression will be implicitly converted to the return type.

15 return Statement • A function may contain more than one return statement: int max(int a, int b) { if (a > b) return a; else return b; }

16 Returning from main • main is a function like any other. Its return type, by default, is int. • The value returned by main is a status code that can be tested when the program terminates. This feature is useful in batch files and shell scripts. • By convention, main returns 0 if the program terminates normally. To indicate abnormal termination, main returns a value other than 0 (typically 1).

17 The exit Function • Another way to terminate a program is to call the exit function. The argument to exit should be either EXIT_SUCCESS or EXIT_FAILURE: exit(EXIT_SUCCESS); /* normal termination */ exit(EXIT_FAILURE); /* abnormal termination */ Calling exit with 0 as the argument has the same effect as calling exit with EXIT_SUCCESS as the argument.

18 The exit Function • Inside main, the call is equivalent to
exit(expression); is equivalent to return expression; The difference between exit and return is that exit can be called from any function, not just from main. • Note: Programs that use exit should contain the following line: #include <stdlib.h>

19 Function declaration Header Prototype Signature

20 Function declaration #include <stdio.h>
double average(double a, double b); /* DECLARATION */ int main(void) { double x, y, z; printf("Enter three numbers: "); scanf("%lf%lf%lf", &x, &y, &z); printf("Average of %g and %g: %g\n", x, y, average(x, y)); printf("Average of %g and %g: %g\n", y, z, average(y, z)); printf("Average of %g and %g: %g\n", x, z, average(x, z)); return 0; } double average(double a, double b) /* DEFINITION */ return (a + b) / 2;

21 Use functions A program can be divided into small pieces that are easier to understand and modify. We can avoid duplicating code that’s used more than once. A function that was originally part of one program can be reused in other programs

22 Recursion A function is recursive if it calls itself. Examples:

23 Quicksort Divide and conquer Quicksort algorithm
1. Choose an array element e (the “partitioning element”), then rearrange the array so that elements 1, …, i – 1 are less than or equal to e, element i contains e, and elements i + 1, …, n are greater than or equal to e. 2. Sort elements 1, …, i – 1 by using Quicksort recursively. 3. Sort elements i + 1, …, n by using Quicksort recursively.

24 /* Sorts an array of integers using Quicksort algorithm */
#include <stdio.h> #define N 10 void quicksort(int a[], int low, int high); int split(int a[], int low, int high); int main(void) { int a[N], i; printf("Enter %d numbers to be sorted: ", N); for (i = 0; i < N; i++) scanf("%d", &a[i]); quicksort(a, 0, N - 1); printf("In sorted order: "); printf("%d ", a[i]); printf("\n"); return 0; }

25 void quicksort(int a[], int low, int high)
{ int middle; if (low >= high) return; middle = split(a, low, high); quicksort(a, low, middle - 1); quicksort(a, middle + 1, high); }

26 int split(int a[], int low, int high)
{ int part_element = a[low]; int part_low[N],part_high[N], n_low = 0, n_high = 0, i; for (i = low+1; i <= high; i++) if (a[i] <= part_element) part_low[n_low++]=a[i]; else part_high[n_high++]=a[i]; for (i = 0; i < n_low; i++) a[i+low] = part_low[i]; a[i+low]=part_element; for (i = 0; i < n_high; i++) a[i+low+n_low+1] = part_high[i]; return low+n_low; }


Download ppt "9. FUNCTIONS."

Similar presentations


Ads by Google