Beruflich Dokumente
Kultur Dokumente
Lectures 6&7
What is a function
A function in C: is a self-contained unit of program code designed to accomplish a particular task. The concept has some equivalent in all high-level programming languages: functions, subroutines, and procedures The use of a function: a "black box"
defined in terms of the information that goes in (its input) and the value or action it produces (its output). what goes on inside the black box is not your concern, unless you are the one who has to write the function. Think on how you used functions printf, scanf, getchar !
Defining a function
#include <stdio.h> void printMessage (void) { printf ("Programming is fun.\n"); } Function Definition -occurs ONE time for all -outside other functions
Function calls (invocations) -occurs ANY (0-N) times -statement inside (other) functions body
printf
{
When a function call is executed, program execution is transferred directly to the indicated function. After the called routine is finished (as signaled by the closing brace) the program returns to the calling routine, where program execution continues at the point where the function call was executed.
Function definitions
General form of function definition: return-type function-name(argument declarations) { declarations and statements }
Function prototype
The first line of the function definition Contains everything that others (other functions) need to know about the function in order to use it (call it) void printMessage (void) void calculateTriangularNumber (int n)
Function prototype return-type function-name(argument declarations) { declarations and statements }
Function arguments
arguments (parameters): a kind of input for the function blackbox In the function definition: formal arguments (formal parameters)
Formal parameter: a name that is used inside the function body to refer to its argument
Example: arguments
// Function to calculate the nth triangular number #include <stdio.h> formal argument void calculateTriangularNumber ( int n ) { int i, triangularNumber = 0; local variables for ( i = 1; i <= n; ++i ) triangularNumber += i; printf ("Triangular number %i is %i\n", n, triangularNumber); } int main (void) { actual argument calculateTriangularNumber (10); calculateTriangularNumber (20); calculateTriangularNumber (50); return 0; }
Formal parameters: behave like local variables, private to the function. Lifetime: Period of time when memory location is allocated Scope: Region of program text where declaration is visible Scope: local variables and formal parameters => only in the body of the function
Local variable i in function calculateTriangularNumber is different from a variable i defined in another function (including main) Formal parameter n in function calculateTriangularNumber is different from a variable n defined in another function
10
20
50
i
triangularNb
Example: arguments
#include <stdio.h> void gcd (int u, int v) { int temp; printf ("The gcd of %i and %i is ", u, v); while ( v != 0 ) { temp = u % v; u = v; v = temp; } printf ("%i\n", u); } int main (void) { gcd (150, 35); gcd (1026, 405); gcd (83, 240); return 0; }
Arguments by copying
main { multiplyBy2 {
7 14
Return example
void printMessage (void) { printf ("Programming is fun.\n"); return; }
Function declaration
a function prototypea declaration that states the return type, the number of arguments, and the types of those arguments. Useful mechanism when the called function is defined after the calling function The prototype of the called function is everything the compiler needs in order to be able to compile the calling function In order to produce the executable program, of course that also the whole definition of the function body is needed, but this occurs later, in the process of linking
Function calls
#include explained
#include <stdio.h> #include <filename> is a preprocessor directive Preprocessor: a first step in the C compilation process Preprocessor statements are identified by the pound sign # that must be the first nonspace character of a line The #include directive will insert in place the contents of the specified file
These files usually have names that end with .h (header files) Header files usually contain declarations and definitions that are used by several programs <stdio.h> contains the declarations for the standard input output functions printf, scanf, getchar, etc. This is why any program that uses these functions has to include <stdio.h>
}
void printMessage (void) { printf ("Programming is fun.\n"); }
Example: a function that returns the minimum value from an array given as parameter
int minimum (int values[10]);
We must modify the function definition if a different array size is needed !
#include <limits.h> int minValue, i; minValue = INT_MIN; for ( i = 0; i < 10; ++i ) if ( values[i] < minValue ) minValue = values[i];
Sorting arrays
// Program to sort an array of integers // into ascending order #include <stdio.h> void sort (int a[], int n) { int i, j, temp; for ( i = 0; i < n - 1; ++i ) for ( j = i + 1; j < n; ++j ) if ( a[i] > a[j] ) { temp = a[i]; a[i] = a[j]; a[j] = temp; } }
Global variables
A global variable declaration is made outside of any function. It does not belong to any particular function. Any function in the program can then access the value of that variable and can change its value. The primary use of global variables is in programs in which many functions must access the value of the same variable. Rather than having to pass the value of the variable to each individual function as an argument, the function can explicitly reference the variable instead. There is a drawback with this approach: Because the function explicitly references a particular global variable, the generality of the function is somewhat reduced ! Global variables do have default initial values: zero
Recursive functions
C permits a function to call itself. This process is named recursion. Useful when the solution to a problem can be expressed in terms of successively applying the same solution to subsets of the problem Example: factorial: recursive definition: n! = n * (n-1)!
factorial(n) factorial(n-1)
factorial(3)=3 * factorial(2); =6
factorial(2) = 2 * factorial(1); =2
factorial(1)= 1 * factorial(0); =1 factorial(0)= 1
n: 1
result: 1
n: 2
result: 2
n: 3 result: 6
Recursion often can be used where loops can be used. Sometimes the iterative solution is more obvious; sometimes the recursive solution is more obvious. Recursive solutions tend to be more elegant and less efficient than iterative solutions.
Functions - Summary
We distinguish between Function definition, function declaration and Function call Function definition general format: returnType name ( type1 param1, type2 param2, ... ) { variableDeclarations programStatement programStatement ... return expression; } The function called name is defined, which returns a value of type returnType and has formal parameters param1, param2,... . The formal parameter param1 is declared to be of type type1, param2 is declared to be of type type2, etc.
Global variable
Automatic local variable Static local variable