You are on page 1of 41

CSE 4201

Computer Programming and Application


Aeronautical Engineering (Avionics)

CSE4201 1
Functions

CSE4201 2
Functions
•Functions serve three purpose in a program:
•They make it easy to use code written by someone else;
•They make it possible to reuse your own code in a new context ; most
important,
•They permit breaking a large program into small pieces.
•A programmer may (and generally does) modularize his program by
dividing the entire job into smaller tasks and writing a user-defined
function for each task.
•Another functions are called standard library functions that defined
by C system.

CSE4201 3
Function Definition
• The general form of defining functions without parameters:
type-identifier function-name ()
{ declaration section;
statements;
}
• Here, the “Type identifier” is the type of a value returned from the
function after it is called.

CSE4201 4
Example
printstar() {
printf("****************\n");
}
print_message() {
printf(“How do you do !\n");
}
main(){
printstar();
print_message();
printstar();
}

CSE4201 5
Function Definition
• The general form of defining functions with parameters:
type-id function-name (formal parameter-list with
their type declaration)
{ Declaration section;
Statements;
}
• In the “formal parameter-list”, parameters are separated by comma
“,”.

CSE4201 6
Example
int max(int x, int y)
{ int z;
if(x>y)z=x;
else z=y;
return(z);
}
main()
{ int a,b,c;
scanf("%d %d",&a,&b);
c=max(a,b);
printf("max=%d",c);
}

CSE4201 7
Function Definition
• Another general form of defining functions with parameters:
type-id function-name (formal parameter-list without
their type declaration)
formal parameter type declaration;
{ Declaration section;
Statements;
}
• Here “formal parameter type declaration” is to give the data type of
each formal parameter.

CSE4201 8
Example
int max(x,y)
int x,y;
{ int z;
if(x>y)z=x;
else z=y;
return(z);
}
main()
{ int a,b,c;
scanf("%d %d",&a,&b);
c=max(a,b);
printf("max=%d",c);
}

CSE4201 9
Function Parameters
• Each function has a defined interface, which include a “parameters-
list” through which it receives information from the caller. Then,
information can be returned to the caller through either the
parameters-list or the function’s return value.
• Formal Parameters: be in the “parameters-list” of definition of
called functions.
• Actual Parameters: be in the “parameters-list” of called functions
which is in program of caller (calling function).

CSE4201 10
Example
int max(int x, int y)/* x,y are formal para*/
{ int z;
z=x>y?x:y; /* condition expression*/
return(z);
/*In the example, the main() is caller, and
} max(x, y) is called function. The x, y in
main() max(x,y) are Formal Parameters, and the
{ int a,b,c; a, b appeared in the statement c=max(a,b)
are Actual Parameters.*/
scanf("%d,%d",&a,&b);
c=max(a,b); /* a and b are actual para*/
printf("Max is %d",c);
}

CSE4201 11
Data Transfer
• Data transfer between Formal Parameters and Actual Parameters
– During the calling process, the data of actual parameters are sent into formal
parameters of a called function.
– This transfer is one to one correspondence in order and types of parameters,
and must be from actual parameters to formal parameters.

CSE4201 12
Data Transfer
• During a function call, the C run-time system allocates memory for the formal
parameter variables and stores the variable values from actual parameter
variables in these locations.
• After the calling, these locations are released.
a b a b
2 3 2 3

x y x y
2 3 10 5

CSE4201 13
Data Transfer
• Based on above analysis, the change of formal parameter values can’t
influence the values of actual parameters.
• So, the locations of actual parameters and formal parameters are different.
• Here, actual parameters might be constants, variables and expression (must
have definite values).
• The declaration about formal parameter types may be given in “formal
parameter-list”.

CSE4201 14
Data Transfer
• Function values / Returning results from a Functions
– A “return” statement is used to send a result from a called function back to a
caller. But, there might be no “return” statement in the called function, thus,
the returning value is not definite and it is not used by the caller.
– In a parentheses of return statements there might be an expression. See the
following:
int max(int x, int y){
return (x>y? x: y);
}

CSE4201 15
Data Transfer
• When a function is defined, the type of the function value should be
given. If the type is not given, the C system consider it integer type.
• The type of a function return value should correspond with the type
of the function. If they are not correspondent, the type conversion
will automatically be used.
• The void before a function-name means that the function does not
bring back a value. So, if a function need not bring back a value, the
function should be defined as void type.

CSE4201 16
Calling Functions
• The General Form of calling
function-name (actual parameter-list);
• The parentheses can not be omitted even if calling a function without
parameters.
• Although correspondence between actual and formal parameters is
maintain, the transfer from caller to called function is either “from
left to right” or from right to left”.
• The Tur-bo C is just “from right to left”.

CSE4201 17
Calling Functions
• The Concrete Forms of calling (3 forms)
• Form 1: Function Statements, example prinstar();
• Form 2: Function Expressions. Here is “a returning value”, and the
value is stored into variable c, example: c=2*max(a, b);
• Form 3: Function Parameters
Use a function as a parameter of another function.
example : printf(“%d”, max(a, b));
Use a function as a parameter of itself.
example: m=max(a, max(a, b));

CSE4201 18
Calling Functions
• The called functions must exist.
• If calling “library functions”, the “#include” should be written at the
beginning of a file
• If calling “user-defined functions”, function must be declared before
caller function calls the called functions.
• Form 1. Function declared with parameters only (variable names may be
ommitted)
• Form 2. Function defined with full body

CSE4201 19
Declaring Functions
• Form 1:
type-id called-function-name(para_type_1,
para_type_2, …);

Example:
int max(int,int)
void main(){
//statements
}
int max(x, y){
return (x>y? x: y);
}

CSE4201 20
Declaring Functions
• Form 2:
type-id called-function-name(para_type_1 var_1,
para_type_2 var_2 …);

Example:
int max(int x, int y){
return (x>y? x: y);
}

void main(){
//statements
}

CSE4201 21
Nested Calling of Functions
• The function definition of C-programs is independent and parallel, i.e.
the definition of a function can not include the definition of another
function.
• But, the function calling of C programs can be nested , i.e. during
calling a function, the called function can call another function.
• The following is a sketch:
main() a() b() c()
1 2 3 4 5 6
call func a call func b call func c 7
13 12 11 10 9 8

end

CSE4201 22
Data Transfer by Reference
• A whole array can be one parameter in a function
• 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.

CSE4201 23
Passing Array to Function
• 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.

CSE4201 24
Passing Array to Function
• 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 !
• int minimum (int values[]);
• Syntactically OK, but how will the function know the actual size
of the array ?!
• int minimum (int values[], int numberOfElements);

CSE4201 25
Passing Array to Function
• The arrays in a formal parameter-list should be defined in the called
function; the arrays in an actual parameter-list should be defined in the
caller. The arrays in an actual parameter-list must have definite values.
• The type of formal and actual parameters should be same.
• According to grammar, the length of two arrays might be different. But if
they are different, sometimes, some data would be lost. So, making they
same is better.
• Can transfer the number of array elements by means of setting up a special
parameter in a formal parameter-list.

CSE4201 26
Example
int minimum (int values[], int numOfElements)
{
int minValue, i;
minValue = values[0];
for ( i = 1; i < numOfElements; ++i )
if ( values[i] < minValue )
minValue = values[i];
return minValue;
}

CSE4201 27
Example (contd)
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;
}

CSE4201 28
Example: Sorting Arrays
#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]; /* Program to
a[i] = a[j]; sort an array
a[j] = temp; of integers
} into
} ascending
order */
CSE4201 29
Local Variables
• Local Variables
• Local variables are defined inside a function, are also named inside variables.
• They are effective only in the function where they are defined. A variable
defined inside main function is only effective in main function.
• The variable is not effective in other functions even though they are in a
same file and are called by the main function.

CSE4201 30
Local Variables
• Variables defined by different functions may be same names, and they do
not interfere with each other.
• Formal parameters of a function are also local variables, which are only
effective in the function.
• If some variables are defined inside a compound statement, then the
variables are only effective in the compound statement.

CSE4201 31
Example
main()
{int a, b;
• • • • • /* a and b are
{ int c; effective */
c=a+b; /* c is
• • • • effective */
}
• • • • •
}

CSE4201 32
Global Variables
• Global variables are defined outside functions, are also named
outside variables.
• They are effective from the place where the variables are defined to
the end of the file.
• Global variables may increase channel / media of data
communication among functions. So, the caller can obtain more
than one return values from a called function.

CSE4201 33
Example
#include <stdio.h>
int x;
void f1 (void) {
x++;
}
void f2 (void) {
x++;
}
int main(void) {
x=7;
f1();
f2();
printf(“x=%i \n”,x);
}

CSE4201 34
Automatic Local Variables
• 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.

CSE4201 35
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

CSE4201 36
Example
void auto_static (void){
int autoVar = 1;
static int staticVar = 1;
printf ("automatic = %i, static = %i\n", autoVar, staticVar);
++autoVar;
++staticVar;
} /* Program to
int main (void){ illustrate static
int i; and automatic
for ( i = 0; i < 5; ++i ) variables */
auto_static ();
return 0;
}

CSE4201 37
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)

CSE4201 38
Example
/* Recursive function to calculate the factorial of n */
long int factorial (unsigned int n)
{
long int result;
if ( n == 0 )
result = 1;
else
result = n * factorial (n - 1);
return result;
}

CSE4201 39
Recursive Function Calls
• Each time any function is called in
C—be it recursive or not—the n: 0

function gets its own set of local result: 1

variables and formal parameters


with which to work n: 1
result: 1
The local variable result and the
formal parameter n that exist when
the factorial function is called to n: 2
calculate the factorial of 3 are result: 2
distinct from the variable result
and the parameter n when the
n: 3
function is called to calculate the
factorial of 2. result: 6
CSE4201 40
Recursion Homework
• Write a program to find Fibonacci series:
1 1 2 3 5 8 13
• The sequence F(n) = F(n-1) + F(n-2)

CSE4201 41

You might also like