Lecture 6
Lecture 6
Lectures 6&7
Masamba Benson
[email protected]
Lectures 6&7: Outline
• Functions [chap 8 – Kochan]
– Defining a Function
– Arguments and Local Variables
• Automatic Local Variables
– Returning Function Results
– Declaring a Function Prototype
– Functions and Arrays
• Arrays as parameters
• Sorting Arrays
• Multidimensional Arrays
– Global Variables
– Automatic and Static Variables
– Recursive Functions
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 !
• What kind of ―output‖ comes out from a function black box ?
– Some functions find a value for a program to use. Example: getchar()
returns to the program the next character from the standard input buffer.
– Some functions cause an action to take place. Example: printf() causes
data to be printed on the screen
– In general, a function can both produce actions and provide values.
Defining a function
#include <stdio.h>
main printf
printMesage
{ { {
} }
return-type arguments
void printMessage ( void )
{
printf ("Programming is fun.\n");
}
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)
Function prototype
{ {
10 n
20 i
50 triangularNb
Example: scope of local variables
#include <stdio.h>
void f1 (float x) {
int n=6;
printf(“%f \n”, x+n);
}
int f2(void) {
float n=10;
printf(“%f \n”,n);
}
int main (void)
{
int n=5;
f1(3);
f2();
return 0;
}
Arguments are passed by copying
values !
• In a function call, the actual argument is
evaluated, and its value is copied to the
corresponding formal parameter for the
function.
– Because the called function works with data
copied from the calling function, the original
data in the calling function is protected from
whatever manipulations the called function
applies to the copies
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;
}
Example: arguments are passed by
copying values !
#include <stdio.h>
void gcd (int u, int v)
{
int temp;
printf ("The gcd of %i and %i is ", u, v);
while ( v != 0 ) { The formal
temp = u % v; parameters u and v
u = v; are assigned new
v = temp; values in the
} function
printf ("%i\n", u);
}
The actual
int main (void)
parameters x and y
{
int x=10,y=15; are not changed !
gcd (x, y);
printf(“x=%i y=%i \n”,x,y);
return 0;
}
Example: arguments are passed by
copying values !
#include <stdio.h>
void multiplyBy2 (float x)
{
printf(“parameter at start: %.2f, at %p \n”,x, &x);
x*=2;
printf(“parameter at end: %.2f, at %p \n”,x, &x);
}
int main (void)
{
float y = 7;
printf (“y before call: %.2f, at %p \n", y, &y);
multiplyBy2 (y);
printf (“y after call: %.2f, at %p \n", y, &y);
return 0;
}
Arguments by copying
main multiplyBy2
{ {
y 7 x
714
Returning function results
• A function in C can optionally return a single value
• return expression;
• The value of expression is returned to the calling function. If the type of
expression does not agree with the return type declared in the function
declaration, its value is automatically converted to the declared type before
it is returned.
• A simpler format for declaring the return statement is as follows:
• return;
• Execution of the simple return statement causes program execution to be
immediately returned to the calling function.This format can only be used to
return from a function that does not return a value.
• If execution proceeds to the end of a function and a return statement is not
encountered, it returns as if a return statement of this form had been
executed. Therefore, in such a case, no value is returned.
• If the declaration of the type returned by a function is omitted, the C
compiler assumes that the function returns an int !
Return example
#include <limits.h>
int minValue, i;
minValue = INT_MIN;
for ( i = 0; i < 10; ++i )
if ( values[i] < minValue )
minValue = values[i];
Example: Passing arrays as
parameters
// Function to find the minimum value in an array
#include <stdio.h>
int minimum (int values[], int n) {
int minValue, i;
minValue = values[0];
for ( i = 1; i < n; ++i )
if ( values[i] < minValue )
minValue = values[i];
return minValue;
}
int main (void) {
int scores[10], i, minScore;
printf ("Enter 10 scores\n");
for ( i = 0; i < 10; ++i )
scanf ("%i", &scores[i]);
minScore = minimum (scores);
printf ("\nMinimum score is %i\n", minScore);
return 0;
}
Example: No size specified for
formal parameter array
// Function to find the minimum value in an array
#include <stdio.h>
int minimum (int values[], int numberOfElements)
{
int minValue, i;
minValue = values[0];
for ( i = 1; i < numberOfElements; ++i )
if ( values[i] < minValue )
minValue = values[i];
return minValue;
}
int main (void)
{
int array1[5] = { 157, -28, -37, 26, 10 };
int array2[7] = { 12, 45, 1, 10, 5, 3, 22 };
printf ("array1 minimum: %i\n", minimum (array1, 5));
printf ("array2 minimum: %i\n", minimum (array2, 7));
return 0;
}
Array parameters are passed by
reference !
• Parameters of non-array type: passed by copying values
• Parameters of array type: passed by reference
– the entire contents of the array is not copied into the formal
parameter array.
– the function gets passed information describing where in the
computer’s memory the original array is located.
– Any changes made to the formal parameter array by the function
are actually made to the original array passed to the function,
and not to a copy of the array.
– This change remains in effect even after the function has
completed execution and has returned to the calling routine.
Example: Array parameters are
passed by reference !
#include <stdio.h>
void multiplyBy2 (float array[], int n)
{
int i;
for ( i = 0; i < n; ++i )
array[i] *= 2;
}
int main (void)
{
float floatVals[4] = { 1.2f, -3.7f, 6.2f, 8.55f };
int i;
multiplyBy2 (floatVals, 4);
for ( i = 0; i < 4; ++i )
printf ("%.2f ", floatVals[i]);
printf ("\n");
return 0;
}
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;
}
}
Sorting arrays - continued
void sort (int a[], int n);
• Valid examples:
function(int array_values[100][50]);
function(int array_values[][50]);
• Invalid examples:
function(int array_values[100][]);
function(int array_values[][]);
Example: multidimensional array as
function parameter
The number of
columns must be specified !
No generic matrix display function possible !
int x;
void f1 (void) {
x++;
}
void f2 (void) {
x++;
}
int main(void) {
x=7;
f1();
f2();
printf(“x=%i \n”,x);
}
Automatic and static variables
• Automatic local variables (the default case of local vars) :
– an automatic variable disappears after the function where it is defined
completes execution, the value of that variable disappears along with it.
– the value an automatic variable has when a function finishes execution
is guaranteed not to exist the next time the function is called.
– The value of the expression is calculated and assigned to the automatic
local variable each time the function is called.
• Static local variables:
– If you place the word static in front of a variable declaration
– ―something that has no movement‖
– a static local variable—it does not come and go as the function is called
and returns. This implies that the value a static variable has upon
leaving a function is the same value that variable will have the next time
the function is called.
– Static variables also differ with respect to their initialization. A static,
local variable is initialized only once at the start of overall program
execution—and not each time that the function is called. Furthermore,
the initial value specified for a static variable must be a simple constant
or constant expression. Static variables also have default initial values
of zero, unlike automatic variables, which have no default initial value.
Example: Automatic and static
variables
// Program to illustrate static and automatic variables
#include <stdio.h>
void auto_static (void)
{
int autoVar = 1;
static int staticVar = 1;
printf ("automatic = %i, static = %i\n", autoVar, staticVar);
++autoVar;
++staticVar;
}
int main (void)
{
int i;
for ( i = 0; i < 5; ++i )
auto_static ();
return 0;
}
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)
Example: recursive function
// Recursive function to calculate the factorial of n
unsigned long int factorial (unsigned int n)
{
unsigned long int result;
if ( n == 0 )
result = 1;
else
result = n * factorial (n - 1);
return result;
}
factorial(3)=3 * factorial(2); =6
factorial(2) = 2 * factorial(1); =2
factorial(1)= 1 * factorial(0); =1
factorial(0)= 1
Recursive function calls
• Each time any function is called in C—be it
recursive or not—the function gets its own
set of local variables and formal
n: 0
parameters with which to work !
• These local automatic variables are stored result: 1
in a memory area called stack
• Each new function call pushes a new
activation record on the stack n: 1
• This activation record contains its set of result: 1
automatic local variables
• When a function call returns, its activation
record is removed from the top of the stack n: 2
result: 2
The local variable result and the
formal parameter n that exist when the
factorial function is called to calculate
the factorial of 3 are distinct from the n: 3
variable result and the parameter n
when the function is called to calculate result: 6
the factorial of 2.
Example: recursive function calls
void up_and_down(int n)
{
printf(“Start call %d: n location %p\n", n, &n);
if (n < 4)
up_and_down(n+1);
printf(“End call %d: n location %p\n", n, &n);
}
...
up_and_down(0);
Recursion pros and cons
• Tricky with recursion: programmer must make sure to get the
recursion to an end at some time !
– a function that calls itself tends to do so indefinitely unless the
programming includes a conditional test to terminate recursion.
• 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
Global variable
Automatic local
variable
Static local
variable