SlideShare uma empresa Scribd logo
1 de 88
USER-DEFINED
FUNCTIONS
INTRODUCTION
• C functions can be classified into two categories
– Library functions
– User-defined functions
LIBRARY FUNCTIONS
– Library functions are not required to be written by
us
– printf and scanf belong to the category of library
function
– sqrt, cos, strcat, etc are some of library functions
USER-DEFINED FUNCTIONS
– User-defined functions has to be developed by the
user at the time of writing a program
– A user-defined functions can later become a part
of the C program library
– main is an example of user-defined functions
NEED FOR USER-DEFINED FUNCTIONS
• Every program must have a main function
• It is possible to code any program utilizing only main
function, it leads to a number of problems
• The program may become too large and complex
and as a result the task of debugging, testing, and
maintaining becomes difficult
• If a program is divided into functional parts, then
each part may be independently coded and later
combined into a single unit
• These subprograms called ‘functions’ are much
easier to understand, debug, and test
NEED FOR USER-DEFINED FUNCTIONS
• There are times when some types of operation or
calculation is repeated at many points throughout a
program
• In such situations, we may repeat the program
statements whenever they are needed
• Another approach is to design a function that can be
called and used whenever required
• This saves both time and space
NEED FOR USER-DEFINED FUNCTIONS
• This sub-sectioning approach clearly results in a
number of advantages
– It facilitates top-down modular programming.
– The length of a source program can be reduced by using
functions at appropriate places. This factor is particularly
critical with microcomputers where memory space is
limited
– It is easy to locate and isolate a faulty function for further
investigations
– A function may be used by many other programs, this
means that a C program can build on what others have
already done, instead of starting over, from scratch.
A MULTI-FUNCTION PROGRAM
• A function is a self-contained block of code that
performs a particular task
• Once a function has been designed and packed, it can
be treated as a ‘black box’ that takes some data from
the main program and returns a value
• The inner details are invisible to the rest of the program
• Example:
main()
{
printline();
printf("This illustrated the use of C functions n");
printline();
}
printline()
{
int i;
for(i=1; i<40; i++)
pintf("-");
printf("n");
}
ELEMENTS OF USER-DEFINED
FUNCTIONS
• Functions are classified as one of the derived data types in C
• Can define functions and use them like any other variables in
C programs.
• Similarities between functions and variables in C
– Both function name and variable names are considered
identifiers and therefore they must adhere to the rules for
identifiers.
– Like variables, functions have types (such as int) associated with
them
– Like variables, function names and their types must be declared
and defined before they are used in a program
ELEMENTS OF USER-DEFINED
FUNCTIONS
• There are three elements related to functions
– Function definition
– Function call
– Function declaration
• The function definition is an independent program module
that is specially written to implement the requirements of the
function
• To use this function we need to invoke it at a required place
in the program. This is known as the function call.
• The program that calls the function is referred to as the
calling program or calling function.
• The calling program should declare any function that is to be
used later in the program. This is known as the function
declaration or function prototype.
FUNCTION
DEFINITION OF FUNCTIONS
• A function definition, also known as function
implementation shall include the following elements;
– Function name;
– Function type;
– List of parameters;
– Local variable declaration;
– Function statements; and
– A return statement.
• All six elements are grouped into two parts, namely,
– Function header (First three elements); and
– Function body (Second three elements)
THE FORM OF C FUNCTION
function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;
----------------
----------------
return(expression);
}
• The first line function_type function_name(parameter list) is
known as the function header.
• The statements within the opening and the closing brace
constitute the function body.
FUNCTION DEFINITION
• Function Header
– The function header consists of three parts: the function type (also
known as return type), the function name and formal parameter list.
– Semicolon is not used at the end of the function header
• Name and Type
– The function type specifies the type of value (like float or double) that
the function id expected to return to the program calling the function
– If the return type is not explicitly specified, C assume it as an integer
type.
– If the function is not returning anything then we need to specify the
return type as void
– The function name is any valid C identifier and therefore ,just follow
the same rules of formation as other variable names in C
FORMAL PARAMETER LIST
• The parameter list declares the variables that will receive the
data sent by the calling program.
• They serve as input data to the function to carry out the
specified task.
• They represent actual input values, they are often referred to
as formal parameters.
• These parameters can also be used to send values to the
calling programs
• The parameter is known as arguments.
– float quadratic (int a, int b, int c) { ….. }
– double power (double x, int n) { ….. }
– int sum (int a, int b) { ….. }
• There is no semicolon after the closing parenthesis
• The declaration parameter variables cannot be combined
FORMAL PARAMETER LIST
• To indicate that the parameter list is empty, we use the
keyword void between the parentheses as in
void printline (void)
{
…
}
• Many compiler accept an empty set of parentheses
void printline()
• It is good to use void to indicate a nill parameter list
FUNCTION BODY
• The function body contains the declarations and statements
necessary for performing the required task. The body
enclosed in braces, contains three parts,
– Local declarations that specify the variables needed by the function
– Function statements that perform the task of the function
– A return statement that returns the value evaluated by the function
• If a function does not return any value, we can omit the
return statement.
• Its return type should be specified as void
RETURN VALUES AND THEIR TYPES
• A function may or may not send back any value to
the calling function
• Done through return statement
• It is possible to send any number of values to the
called function
• The called function can only return one value per call
• SYNTAX:
return;
or
return (expression);
RETURN VALUES AND THEIR TYPES
• return;
– Plain return does not return any value
– Acts as the closing brace of the function
– The control is immediately passed back to the calling function
– EXAMPLE:
if(error)
return;
• return (expression);
– Return the value of the expression
• EXAMPLE:
mul(x,y)
int x,y;
{
int p;
p = x*y;
return(p);
}
– Returns the value of p which is the product of the values of x and y
– The last statement can be combined into one statement as
return(x*y);
RETURN VALUES AND THEIR TYPES
• A function may have more than one return statements
• This situation arises when the value returned is based
on certain conditions
• EXAMPLE:
if(x <= 0)
return(0);
else
return(1);
• Return type of data:
– All function by default return int type data
– We can force a function to return a particular type of data
by using type specifier in the function header
– EXAMPLE:
double product(x,y)
float sqr_root(p)
– When a value is returned, it is automatically cast to the
function’s type
CALLING A FUNCTION
• A function can be called by simply using the function
name in a statement
• When the function encounters a function call, the
control is transferred to the function mul(x,y)
main()
{
int p;
p = mul(10,5);
printf("%dn", p);
}
int mul(int x,int y)
{
int p; /*local variables*/
p = x * y;/* x = 10, y = 5*/
return(p);
}
CALLING A FUNCTION
• The function is executed and the value is returned
and assigned to p
• A function which returns a value can be used in
expressions like any other variables
printf("%dn", mul(p,q));
y = mul(p,q) / (p+q);
if (mul(m,n)>total)
printf("large");
• A function cannot be used on the right side of an
assignment statement
mul(a,b) = 15;
• A function that does not return any value may not be
used in expression; but can be called to perform
certain tasks specified in the function
main() { printline(); }
FUNCTION DECLARATION
• A function declaration consists of four parts
– Function type (return type)
– Function name
– Parameter list
– Terminating semicolon
• Format
– Function-type function-name (parameter list);
• Very similar to the function header line expect the
terminating semicolon.
– int mul(int m, int n); /* Function prototype */
• Equally acceptable forms of declarations are
– int mul (int, int);
– mul (int a, int b);
– mul (int, int);
FUNCTION DECLARATION
• When a function does not take any parameters and does not
return any value, its prototype is written as:
void display (void);
• A prototype declaration may be placed in two places in a
program.
– Above all the functions (including main) (global prototype)
– Inside a function definition (local prototype)
• It is good to declare prototypes in the global declaration
section before main.
• It adds flexibility, provides an excellent quick reference to the
functions used in the program, and enhances documentation
CATEGORY OF FUNCTIONS
• Category 1: Functions with no arguments and no
return values
• Category 2: Functions with arguments and no return
values
• Category 3: Functions with arguments and one
return values
• Category 4: Functions with no arguments but return
a value
• Category 5: Functions that return multiple values
NO ARGUMENTS AND NO RETURN
VALUES
• When a function has no arguments, it does not
receive any data from the calling function
• When it does not return a value, the calling function
does not receive any data from the called function
• There is no data transfer between the calling
function and the called function
• There is only a transfer of control but not data
EXAMPLE
#include <stdio.h>
#include<conio.h>
void add(void);
void main() //calling function
{
add();
}
add() //called function
{
int a,b,c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
printf("nSum is:%d",c);
}
OUTPUT:
Enter two number:3
4
Sum is:7
ARGUMENTS BUT NO RETURN
VALUES
• The calling function read data from the terminal and
pass it on to the called function.
• It is a one way data communication, i.e. the called
program receives data from calling program but it
does not return any value to the calling program.
• This approach is wiser because the calling function
can check for the validity of data, if necessary, before
it is handed over to the called function.
• Called function with arguments
value(p,r,n)
ARGUMENTS BUT NO RETURN
VALUES
• The function call
value(500,0.12,5)
• Would send the value 500, 0.12, 5 to the function
value(float p, float r, int n)
• and assign 500 to p, 0.12 to r and 5 to n
• The values 500, 0.12, 5 are the actual arguments
• The arguments p, r, n are the formal arguments
• The actual and formal arguments should match in
number, type, and order
• The values of actual arguments are assigned to the
formal arguments on a one to one basis
ARGUMENTS BUT NO RETURN
VALUES
• if the actual arguments are more than the formal
arguments, the extra actual arguments are discarded
• If the actual arguments are less than the formal
arguments, the unmatched formal arguments are
initialized to some garbage values
• No error message will be generated
• The formal arguments must be valid variable names
• The actual arguments my be variable names,
expression, or constants
• When a function call is made, only a copy of the
values of actual arguments is passed into the called
function
EXAMPLE
#include <stdio.h>
#include<conio.h>
add(int, int);
void main()
{
int a,b;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
add(a,b);
}
add(int x, int y)
//function with arguments
{
int z;
z=x+y;
printf("nSum is:%d",z);
}
OUTPUT:
Enter two number:2
4
Sum is:6
ARGUMENTS WITH RETURN VALUES
• Here data transfer take place between the calling
function and the called function as well as between
called function and calling function .
• It is a two way data communication, i.e. the called
program receives data from calling program and it
return some value to the calling program.
• A self-contained and independent function should
behave like a ‘black box’ that receives a predefined
form of input and outputs a desired value
EXAMPLE
#include <stdio.h>
#include<conio.h>
add(int, int);
void main()
{
int a,b;
float c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("nSum is:%f",c);
}
add(int x, int y)
{
float z;
z=x+y/3;
return(z);
}
OUTPUT:
Enter two number:6
7
Sum is:13
RETURNING FLOAT VALUE
• C function returns a value of the type int as a default
case when no other type is specified explicitly.
return(z);
• Return the integer value of sum
• This is due to the absence of the type-specifier in the
function header
• There will be times when we may find it necessary to
receive the float or double type of data
• We must explicitly specify the return type on both
the function definition and the prototype declaration
EXAMPLE
#include <stdio.h>
#include<conio.h>
float add(int, int);
void main()
{
int a,b;
float c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("nSum is:%f",c);
}
float add(int x, int y)
{
float z;
z=x+y/3;
return(z);
}
OUTPUT:
Enter two number:6
7
Sum is:13
RETURNING NON-INTEGER VALUE
• The type-specifier tells the
compiler, the type of data
the function is to return
• The called function must be
declared at the start of the
body in the calling function,
like any other variable. This
is to tell the calling function
the type of data that the
function is actually
returning
float mul(float, float);
double div(float, float);
main() {
float a,b;
a = 12.345;
b = 9.82;
printf("%fn", mul(a,b));
printf("%fn", div(a,b));
}
float mul(float x,float y)
{
return(x*y);
}
double dic(float p, float q)
{
return(p/q);
}
NO ARGUMENTS BUT RETURNS A
VALUE
• There could be
occasions where we
may need a design
functions that may not
take any arguments but
returns a value to the
calling function.
int get_number(void);
main()
{
int m = get_number();
printf(“%d”,m);
}
int get_number(void)
{
int number;
scanf(“%d”, &number);
return(number);
}
FUNCTIONS RETURNING NOTHING
• Functions that do not return
any values are not declared in
the main
main()
{
printline();
value();
printline();
}
printline()
{
....
}
value()
{
....
}
• We can also declare them in
the main with the qualifier
void
• This states explicitly that the
functions do not return
values
main()
{
void printline();
void value();
void printline();
}
void printline()
{
....
}
void value()
{
....
}
FUNCTIONS THAT RETURN
MULTIPLE VALUES
• A return statement can return only one value.
• To get more information from a function, we can
achieve this in C using the arguments not only to
receive information but also to send back
information to the calling function.
• The arguments that are used to “send out”
information are called output parameters.
• The mechanism of sending back information through
arguments is achieved using what are known as the
address operator (&) and indirection operator (*).
PROGRAM
void mathoperation(int x, int y, int *s, int *d);
main()
{
int x = 20, y = 10, s, d;
mathoperation(x,y,&s,&d);
printf("s=%dn d=%dm", s,d);
}
void mathoperation(int x, int y, int *sum, int
*diff)
{
*sum = a+b;
*diff = a-b;
}
• x and y – input arguments
• s and d – output arguments
• We pass
– Value of x to a
– Value of y to b
– Address of s to sum
– Address of d to diff
• The body of the function
when executed add the
value and find difference
and store the result in
memory location pointed
by sum and diff.
FUNCTIONS THAT RETURN
MULTIPLE VALUES
• The indirection operator * indicates the variables are to store
addresses, not actual values of variables
• The operator * is known as indirection operator because it gives
an indirect reference to a variable through its address
• The variables *sum and *diff are known as pointers and sum
and diff as pointer variables
• They are declared as int, they can point to locations of int type
data
• The use of pointer variables as actual parameters for
communicating data between functions is called “pass by
pointers” or “call by address or reference”.
NESTING OF FUNCTIONS
• C permits nesting of functions freely
• main can call function1, which calls function2, which
calls function3, …..and so on
RECURSION
• When a called function in turn calls another function a
process of ‘chaining’ occurs
• Recursion is a special case, where a function calls itself
• EXAMPLE:
main()
{
printf("This is an example of recursionn");
main();
}
• OUTPUT:
This is an example of recursion
This is an example of recursion
This is an example of recursion
This is an exa
• Execution is terminated abruptly
EXAMPLE
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
int factorial (int);
printf("nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d! is
%d",a,factorial(a));
}
int factorial(int x)
{
int f;
if(x==1)
return(1);
else
f=x*factorial (x-1);
return(f);
}
OUTPUT:
Enter the number:5
The factorial of 5! is 120
FUNCTIONS WITH 1D ARRAYS
• Possible to pass the values of an array to a function
• To pass an array to a called function, it is sufficient to
list the name of the array without any subscripts, and
the size of the array as arguments
• The call:
largest(a,n);
• will pass all the elements contained in the array a of
size n.
• The called function expecting this call must be
appropriately defined
• The largest function header is
float largest(float array[], int size)
FUNCTIONS WITH 1D ARRAYS
• The function header(largest) is defined to take two
arguments, the array name and the size of the array
to specify the number of elements in the array
• The declaration of formal argument array is
float array[];
• The pair of brackets informs the compiler that the
arguments array is an array of numbers
• It is not necessary to specify the size of the array
here
FUNCTIONS WITH 1D ARRAYS
• Here an array is transferred as parameter to a
function.
void main() void fun(int b[], int n)
{ {
void fun(int[],int); int x,b[5];
int a[5],n; …………..
…………… …………..
fun(a,n);
…………… }
}
EXAMPLE
#include<stdio.h>
#include<conio.h>
void add(int[],int b);
void main()
{
int a[5],i,n;
clrscr();
printf("n Enter the Number:
");
scanf("%d",&n);
printf("n Enter the Values: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
add(a,n);
}
void add(int b[],int x)
{
int sum=0,i;
for(i=0;i<x;i++)
sum=sum+b[i];
printf("nThe sum is: %d",sum);
}
OUTPUT:
Enter the Number: 5
Enter the Values: 1
2
3
4
5
The sum is: 15
FUNCTIONS WITH 2D ARRAYS
• Can also pass multi-dimensional arrays to functions.
The rules are:
– The function must be called by passing only the array
name
– In the function definition, we must indicate that the array
has two-dimensional by including two sets of brackets
– The size of the second dimension must be specified
– The prototype declaration should be similar to the
function header
PROGRAM
main()
{
int M=3, N=2;
float average(int [][N], int,
int);
float mean;
int matrix[M][N] = { {1,2},
{3,4}, {5,6} };
mean = average(matrix, M,
N);
}
float average(int x[][N], int M,int
N)
{
int i, j;
float sum = 0.0;
for(i=0; i<M; i++)
for(j=0; j<N; j++)
sum+=x[i][j];
return(sum/(M*N));
}
PASSING STRINGS TO FUNCTIONS
• The strings are treated as character arrays in C and
therefore the rules for passing strings to function are
very similar to those for passing arrays to functions
• Basic rules are
– The string to be passed must be declared as a formal
argument of the function when it is defined
Example:
void display(char item_name[])
{
...
}
PASSING STRINGS TO FUNCTIONS
– The function prototype must show that the argument is a
string
void dispay(char str[]);
– A call to the fuction must have a string array name without
subscripts as its actual argument
Example:
display(names);
Name is a properly declared string array in the calling function
• Like arrays, strings in C cannot be passed by value to
function
THE SCOPE, VISIBILITY AND
LIFETIME OF VARIABLES
• It is very important to understand the concept of
storage classes and their utility in order to develop
efficient multifunction programs
• In C there are four storage classes
– Automatic variables
– External variables
– Static variables
– Register variables
• Here we discuss the scope, visibility and longevity of
the above class of variables
THE SCOPE AND LIFETIME OF
VARIABLES IN FUNCITONS
• SCOPE OF VARIABLE
– Determines over what parts of the program a variable is actually
available for use (active)
• LONGEVITY
– Refers to the period during which a variable retains a given value
during execution of program (alive)
– It has a direct effect on the utility of a given variables
• VISIBILITY
• The visibility refers to the accessibility of a variable from the
memory
• Variables are categorized depending on the place of their
declaration
– Internal (local)
• Internal variables are those which are declared within a particular
function
– External (global)
• External variables are declared outside of any function
AUTOMATIC VARIABLES
• Automatic variables are declared inside a function in
which they are to be utilized
• They are created when the function is called and
destroyed automatically when the function is exited,
hence the name automatic
• Automatic variables are therefore private to the
function in which they are declared
• Automatic variables are also referred to as local or
internal variables
AUTOMATIC VARIABLES
• A variable declared inside a function without storage
class specification is, by default, an automatic variable
• The storage class of the variable number is automatic
main()
{
int number;
.......
}
• We may also use the keyword auto to declare automatic
variables explicitly
main()
{
auto int number;
.......
}
EXAMPLE
void function1(void);
void function2(void);
main()
{
int m = 1000;
function2();
printf("%dn",m);
}
void function1(void)
{
int m = 10;
printf("%dn",m);
}
void function2(void)
{
int m = 100;
function1();
printf("%dn",m);
}
EXAMPLE
void function1(void);
void function2(void);
main()
{
int m = 1000;
function2();
printf("%dn",m);
}
void function1(void)
{
int m = 10;
printf("%dn",m);
}
void function2(void)
{
int m = 100;
function1();
printf("%dn",m);
}
OUTPUT:
10
100
1000
AUTOMATIC VARIABLES
• There are two consequences of the scope and
longevity of auto variables
• Any variable local to main will normally live
throughout the whole program, although it is active
only in main.
• During recursion, the nested variables are unique
auto variables
EXTERNAL VARIABLES
• Variables that are both alive and active throughout
the entire program are known as external variables
• They are also known as global variables
• Global variables can be accessed by any function in
the program
• External variables are declared outside a function
EXTERNAL VARIABLES
int number;
float length = 7.5;
main)
{
.....
}
function1()
{
.....
}
function2()
{
.....
}
• The variables number and length are available for use in all the
three functions
• In case a local variables and a global variable have the same
name, the local variable will have precedence over the global one
in the function where it is declared
EXTERNAL VARIABLES
int count;
main()
{
count = 10;
.....
}
function()
{
int count = 0;
....
count = count+1;
}
• When the function references the variable count, it
will be referencing only its local variable, not the
global one
• The value of count in main will not be affected
EXAMPLE
int fun1(void);
int fun2(void);
int fun3(void);
int x;
main()
{
x = 10;
printf("x = %dn",x);
printf("x = %dn",fun1());
printf("x = %dn",fun2());
printf("x = %dn",fun3());
}
fun1(void)
{
x = x + 10;
}
fun2(void)
{
int x
x = 1;
return(x);
}
fun3(void)
{
x = x + 10;
}
EXAMPLE
int fun1(void);
int fun2(void);
int fun3(void);
int x;
main()
{
x = 10;
printf("x = %dn",x);
printf("x = %dn",fun1());
printf("x = %dn",fun2());
printf("x = %dn",fun3());
}
fun1(void)
{
x = x + 10;
}
fun2(void)
{
int x
x = 1;
return(x);
}
fun3(void)
{
x = x + 10;
}
OUTPUT:
x = 10
x = 20
x = 1
x = 30
EXTERNAL VARIABLES
• Once a variable has been declared as global, any function can
use it and change its value
• Then subsequent functions can reference only that new value
• Global variable is that it is visible only from the point of
declaration to the end of the program
main()
{
y = 5;
....
}
int y;
func1()
{
y = y + 1;
}
• As for as main is concerned, y is not defined. So, the compiler
will issue an error message
• Global variables are initialized to zero by default
• The statement y = y + 1 will assign 1 to y.
EXTERNAL DECLARATION
• The main cannot access the variable y as it has been declared
after the main function
• This problem can be solved by declaring the variable with the
storage class extern
main()
{
extern int y; /* external declaration */
....
}
func1()
{
extern int y; /* external declaration */
.....
}
int y; /* definition */
• Although the variable y has been defined after both the
functions, the external declaration of y inside the function
informs the compiler that y is an integer type defined
somewhere else in the program
• The extern declaration does not allocate storage space for
variables
EXTERNAL DECLARATION
main()
{
int i;
void print_out(void);
extern float height[];
....
print_out();
}
void print_out(void)
{
extern float height[];
int i;
......
.....
}
float height[SIZE];
• An extern within a function provides the type information to
just that one function
• We can provide type information to all functions within a file by
placing external declaration before any of them
EXTERNAL DECLARATION
• The distinction between
definition and declaration
also applies to functions
• A function is defined when
its parameters and function
body are specified
• This tells the compiler to
allocate space for the
function code and provides
type information for the
parameters
• Since functions are external
by default, we declare them
without the qualifier extern
• void print_out(); is
equivalent to
• extern void print_out();
extern float height[];
main()
{
int i;
void print_out(void);
....
print_out();
}
void print_out(void)
{
int i;
......
}
float height[SIZE];
STATIC VARIABLES
• The value of static variables persists until the end of the
program
• A variable can be declared static using the keyword
static
static int x;
static float y;
• A static variable may be an internal or external type,
depending on the place of declaration
EXAMPLE
void stat(void)
main()
{
int i;
for(i=1; i<=3; i++)
stat();
}
void stat(void)
{
static int x = 0;
x = x + 1;
printf("x = %dn",x);
}
OUTPUT:
x = 1
x = 2
x = 3
• If we had declared x as an
auto variable. The output
would be
X = 1
X = 1
X = 1
STATIC VARIABLES
Internal static variables
• Declared inside a function
• The scope extend up to end of the function in which they are
defined
• Similar to auto variables, except that they remain inexistence
(alive) throughout the remainder of the program
• Static variable is initialized only once, when the program is
compiled. It is never initialized again
External static variables
• Declared outside of all functions and is available to all the
functions in that program
• The difference between a static external variable and a simple
external variable is that:
– the static external variable is available only within the file where it is
defined while the simple external variable can be accessed by other files
SCOPE OF FUNCTION
• To make a particular function accessible only to the
functions in the file in which it is defined and not to
any function in other files by defining that function
with the storage class static
REGISTER VARIABLES
• Register access is much faster than a memory access
• We can make a variable to be placed in one of the
machine register instead of memory using
register int count;
• Most compiler allow int or char variables to be
placed in the register
• ANSI standard does not restrict to any particular data
type
• C will automatically convert register variables into
non-register variables once the limit is reached
MULTIFILE PROGRAMS
• More than one source file is compiled separately and
linked later to form an executable object code
• This approach is very useful because any change in
one file does not affect other files thus eliminating
the need for recompilation of the entire program
• Multiple source files can share a variable declared as
an external variable
• Variables that are shared by two or more files are
global variables and we must declare them
accordingly in one file and then explicitly define
them with extern in other file
USE OF EXTERN IN A MULTIFILE
PROGRAM
file1.c
main()
{
extern int m;
int i;
....
}
function1()
{
int j;
....
}
file2.c
int m /* global variable */
function2()
{
int i;
.....
}
function3()
{
int count;
.....
}
USE OF EXTERN IN A MULTIFILE
PROGRAM
file1.c
int m; /* global variable */
main()
{
int i;
....
}
function1()
{
int j;
....
}
file2.c
extern int m;
function2()
{
int i;
....
}
function3()
{
int count;
.....
}
MULTIFILE PROGRAMS
• The extern specifier tells the compiler that the following
variables types and names have already been declared
elsewhere and no need to create storage space for
them
• It is the responsibility of the linker to resolve the
reference problem
• A function defined in one file and accessed in another
must include a function declaration
• The declaration identifies the function as an external
function whose definition appears elsewhere
• We place such declarations at the beginning of the file,
before all functions
• Although all functions are external, it would be good
practice to explicitly declare such functions with storage
class extern
TO FIND THE MAXIMUM
main()
{
float largest(float a[],int n);
float value[4] = {2.5, -4.75, 1,2. 3.6}
printf("%fn", largest(value,4));
}
float largest(float a[], int n)
{
int i; float max;
max = a[0];
for(i=1;i<n;i++)
if(max<a[i])
max = a[i];
return(max);
}
TO SORT AN ARRAY OF INTEGERS
main()
{
int i;
int marks[5] = {40, 90, 73, 81, 35};
printf("Marks before sortingn");
for(i=0;i<5;i++)
printf("%d ",marks[i]);
printf("nn");
sort(5, marks);
printf("Marks after sortingn");
for(i=0;i<5;i++)
printf("%4d ",marks[i]);
}
void sort(int m, int x[])
{
int i,j,t;
for(i=1;i<=m-1;i++)
for(j=1;j<=m-i;j++)
if(x[j-1]>=x[j])
{
t = a[j-1];
x[j-1] = x[j];
x[j] = t;
}
}
SWAPPING NUMBERS USING CALL
BY REFERENCE
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and yn");
scanf("%d%d",&x,&y);
printf("Before Swappingnx = %dny = %dn", x, y);
swap(&x, &y);
printf("After Swappingnx = %dny = %dn", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
FIBONACCI SERIES USING
RECURSION
#include<stdio.h>
int Fibonacci(int);
main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci seriesn");
for ( c = 1 ; c <= n ; c++ )
{
printf("%dn", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) +
Fibonacci(n-2) );
}
THE END

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
C functions
C functionsC functions
C functions
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
user defined function
user defined functionuser defined function
user defined function
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
Function
FunctionFunction
Function
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Function in c
Function in cFunction in c
Function in c
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Call by value
Call by valueCall by value
Call by value
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Data types
Data typesData types
Data types
 
Structure in C
Structure in CStructure in C
Structure in C
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 

Destaque

Functions of visual_language
Functions of visual_languageFunctions of visual_language
Functions of visual_languageakeka
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Appili Vamsi Krishna
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programmingAppili Vamsi Krishna
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers Appili Vamsi Krishna
 
BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015Appili Vamsi Krishna
 
Difference between structure and union
Difference between structure and unionDifference between structure and union
Difference between structure and unionAppili Vamsi Krishna
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Kamal Acharya
 
Lesson9 Working With Basic Functions
Lesson9 Working With Basic FunctionsLesson9 Working With Basic Functions
Lesson9 Working With Basic Functionsguevarra_2000
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing TechniquesAppili Vamsi Krishna
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
8.3 program structure (1 hour)
8.3 program structure (1 hour)8.3 program structure (1 hour)
8.3 program structure (1 hour)akmalfahmi
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programmingAppili Vamsi Krishna
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)Jyoti Bhardwaj
 
New Threats, New Approaches in Modern Data Centers
New Threats, New Approaches in Modern Data CentersNew Threats, New Approaches in Modern Data Centers
New Threats, New Approaches in Modern Data CentersIben Rodriguez
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 

Destaque (20)

Functions of visual_language
Functions of visual_languageFunctions of visual_language
Functions of visual_language
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers
 
BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015
 
Difference between structure and union
Difference between structure and unionDifference between structure and union
Difference between structure and union
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
Lesson9 Working With Basic Functions
Lesson9 Working With Basic FunctionsLesson9 Working With Basic Functions
Lesson9 Working With Basic Functions
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
CP Handout#2
CP Handout#2CP Handout#2
CP Handout#2
 
8.3 program structure (1 hour)
8.3 program structure (1 hour)8.3 program structure (1 hour)
8.3 program structure (1 hour)
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programming
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
CP Handout#5
CP Handout#5CP Handout#5
CP Handout#5
 
New Threats, New Approaches in Modern Data Centers
New Threats, New Approaches in Modern Data CentersNew Threats, New Approaches in Modern Data Centers
New Threats, New Approaches in Modern Data Centers
 
Troubleshooting Java HotSpot VM
Troubleshooting Java HotSpot VMTroubleshooting Java HotSpot VM
Troubleshooting Java HotSpot VM
 
Verilog Tasks and functions
Verilog Tasks and functionsVerilog Tasks and functions
Verilog Tasks and functions
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 

Semelhante a User defined functions in C programmig

Semelhante a User defined functions in C programmig (20)

user-definedfunctions-converted.pptx
user-definedfunctions-converted.pptxuser-definedfunctions-converted.pptx
user-definedfunctions-converted.pptx
 
User defined function in c
User defined function in cUser defined function in c
User defined function in c
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
Chapter 1_C Fundamentals_HS_Tech Yourself C.pptx
Chapter 1_C Fundamentals_HS_Tech Yourself C.pptxChapter 1_C Fundamentals_HS_Tech Yourself C.pptx
Chapter 1_C Fundamentals_HS_Tech Yourself C.pptx
 
Functions
FunctionsFunctions
Functions
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
Function
Function Function
Function
 
Functions
FunctionsFunctions
Functions
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothi
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Functions
Functions Functions
Functions
 
Functions
FunctionsFunctions
Functions
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

User defined functions in C programmig

  • 2. INTRODUCTION • C functions can be classified into two categories – Library functions – User-defined functions
  • 3. LIBRARY FUNCTIONS – Library functions are not required to be written by us – printf and scanf belong to the category of library function – sqrt, cos, strcat, etc are some of library functions
  • 4. USER-DEFINED FUNCTIONS – User-defined functions has to be developed by the user at the time of writing a program – A user-defined functions can later become a part of the C program library – main is an example of user-defined functions
  • 5. NEED FOR USER-DEFINED FUNCTIONS • Every program must have a main function • It is possible to code any program utilizing only main function, it leads to a number of problems • The program may become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult • If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit • These subprograms called ‘functions’ are much easier to understand, debug, and test
  • 6. NEED FOR USER-DEFINED FUNCTIONS • There are times when some types of operation or calculation is repeated at many points throughout a program • In such situations, we may repeat the program statements whenever they are needed • Another approach is to design a function that can be called and used whenever required • This saves both time and space
  • 7. NEED FOR USER-DEFINED FUNCTIONS • This sub-sectioning approach clearly results in a number of advantages – It facilitates top-down modular programming. – The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited – It is easy to locate and isolate a faulty function for further investigations – A function may be used by many other programs, this means that a C program can build on what others have already done, instead of starting over, from scratch.
  • 8. A MULTI-FUNCTION PROGRAM • A function is a self-contained block of code that performs a particular task • Once a function has been designed and packed, it can be treated as a ‘black box’ that takes some data from the main program and returns a value • The inner details are invisible to the rest of the program • Example: main() { printline(); printf("This illustrated the use of C functions n"); printline(); } printline() { int i; for(i=1; i<40; i++) pintf("-"); printf("n"); }
  • 9. ELEMENTS OF USER-DEFINED FUNCTIONS • Functions are classified as one of the derived data types in C • Can define functions and use them like any other variables in C programs. • Similarities between functions and variables in C – Both function name and variable names are considered identifiers and therefore they must adhere to the rules for identifiers. – Like variables, functions have types (such as int) associated with them – Like variables, function names and their types must be declared and defined before they are used in a program
  • 10. ELEMENTS OF USER-DEFINED FUNCTIONS • There are three elements related to functions – Function definition – Function call – Function declaration • The function definition is an independent program module that is specially written to implement the requirements of the function • To use this function we need to invoke it at a required place in the program. This is known as the function call. • The program that calls the function is referred to as the calling program or calling function. • The calling program should declare any function that is to be used later in the program. This is known as the function declaration or function prototype.
  • 12. DEFINITION OF FUNCTIONS • A function definition, also known as function implementation shall include the following elements; – Function name; – Function type; – List of parameters; – Local variable declaration; – Function statements; and – A return statement. • All six elements are grouped into two parts, namely, – Function header (First three elements); and – Function body (Second three elements)
  • 13. THE FORM OF C FUNCTION function_type function_name(parameter list) { local variable declaration; executable statement1; executable statement2; ---------------- ---------------- return(expression); } • The first line function_type function_name(parameter list) is known as the function header. • The statements within the opening and the closing brace constitute the function body.
  • 14. FUNCTION DEFINITION • Function Header – The function header consists of three parts: the function type (also known as return type), the function name and formal parameter list. – Semicolon is not used at the end of the function header • Name and Type – The function type specifies the type of value (like float or double) that the function id expected to return to the program calling the function – If the return type is not explicitly specified, C assume it as an integer type. – If the function is not returning anything then we need to specify the return type as void – The function name is any valid C identifier and therefore ,just follow the same rules of formation as other variable names in C
  • 15. FORMAL PARAMETER LIST • The parameter list declares the variables that will receive the data sent by the calling program. • They serve as input data to the function to carry out the specified task. • They represent actual input values, they are often referred to as formal parameters. • These parameters can also be used to send values to the calling programs • The parameter is known as arguments. – float quadratic (int a, int b, int c) { ….. } – double power (double x, int n) { ….. } – int sum (int a, int b) { ….. } • There is no semicolon after the closing parenthesis • The declaration parameter variables cannot be combined
  • 16. FORMAL PARAMETER LIST • To indicate that the parameter list is empty, we use the keyword void between the parentheses as in void printline (void) { … } • Many compiler accept an empty set of parentheses void printline() • It is good to use void to indicate a nill parameter list
  • 17. FUNCTION BODY • The function body contains the declarations and statements necessary for performing the required task. The body enclosed in braces, contains three parts, – Local declarations that specify the variables needed by the function – Function statements that perform the task of the function – A return statement that returns the value evaluated by the function • If a function does not return any value, we can omit the return statement. • Its return type should be specified as void
  • 18. RETURN VALUES AND THEIR TYPES • A function may or may not send back any value to the calling function • Done through return statement • It is possible to send any number of values to the called function • The called function can only return one value per call • SYNTAX: return; or return (expression);
  • 19. RETURN VALUES AND THEIR TYPES • return; – Plain return does not return any value – Acts as the closing brace of the function – The control is immediately passed back to the calling function – EXAMPLE: if(error) return; • return (expression); – Return the value of the expression • EXAMPLE: mul(x,y) int x,y; { int p; p = x*y; return(p); } – Returns the value of p which is the product of the values of x and y – The last statement can be combined into one statement as return(x*y);
  • 20. RETURN VALUES AND THEIR TYPES • A function may have more than one return statements • This situation arises when the value returned is based on certain conditions • EXAMPLE: if(x <= 0) return(0); else return(1); • Return type of data: – All function by default return int type data – We can force a function to return a particular type of data by using type specifier in the function header – EXAMPLE: double product(x,y) float sqr_root(p) – When a value is returned, it is automatically cast to the function’s type
  • 21. CALLING A FUNCTION • A function can be called by simply using the function name in a statement • When the function encounters a function call, the control is transferred to the function mul(x,y) main() { int p; p = mul(10,5); printf("%dn", p); } int mul(int x,int y) { int p; /*local variables*/ p = x * y;/* x = 10, y = 5*/ return(p); }
  • 22. CALLING A FUNCTION • The function is executed and the value is returned and assigned to p • A function which returns a value can be used in expressions like any other variables printf("%dn", mul(p,q)); y = mul(p,q) / (p+q); if (mul(m,n)>total) printf("large"); • A function cannot be used on the right side of an assignment statement mul(a,b) = 15; • A function that does not return any value may not be used in expression; but can be called to perform certain tasks specified in the function main() { printline(); }
  • 23. FUNCTION DECLARATION • A function declaration consists of four parts – Function type (return type) – Function name – Parameter list – Terminating semicolon • Format – Function-type function-name (parameter list); • Very similar to the function header line expect the terminating semicolon. – int mul(int m, int n); /* Function prototype */ • Equally acceptable forms of declarations are – int mul (int, int); – mul (int a, int b); – mul (int, int);
  • 24. FUNCTION DECLARATION • When a function does not take any parameters and does not return any value, its prototype is written as: void display (void); • A prototype declaration may be placed in two places in a program. – Above all the functions (including main) (global prototype) – Inside a function definition (local prototype) • It is good to declare prototypes in the global declaration section before main. • It adds flexibility, provides an excellent quick reference to the functions used in the program, and enhances documentation
  • 25. CATEGORY OF FUNCTIONS • Category 1: Functions with no arguments and no return values • Category 2: Functions with arguments and no return values • Category 3: Functions with arguments and one return values • Category 4: Functions with no arguments but return a value • Category 5: Functions that return multiple values
  • 26. NO ARGUMENTS AND NO RETURN VALUES • When a function has no arguments, it does not receive any data from the calling function • When it does not return a value, the calling function does not receive any data from the called function • There is no data transfer between the calling function and the called function • There is only a transfer of control but not data
  • 27.
  • 28. EXAMPLE #include <stdio.h> #include<conio.h> void add(void); void main() //calling function { add(); } add() //called function { int a,b,c; printf("nEnter two number:"); scanf("%d%d",&a,&b); c=a+b; printf("nSum is:%d",c); } OUTPUT: Enter two number:3 4 Sum is:7
  • 29. ARGUMENTS BUT NO RETURN VALUES • The calling function read data from the terminal and pass it on to the called function. • It is a one way data communication, i.e. the called program receives data from calling program but it does not return any value to the calling program. • This approach is wiser because the calling function can check for the validity of data, if necessary, before it is handed over to the called function. • Called function with arguments value(p,r,n)
  • 30. ARGUMENTS BUT NO RETURN VALUES • The function call value(500,0.12,5) • Would send the value 500, 0.12, 5 to the function value(float p, float r, int n) • and assign 500 to p, 0.12 to r and 5 to n • The values 500, 0.12, 5 are the actual arguments • The arguments p, r, n are the formal arguments • The actual and formal arguments should match in number, type, and order • The values of actual arguments are assigned to the formal arguments on a one to one basis
  • 31.
  • 32.
  • 33. ARGUMENTS BUT NO RETURN VALUES • if the actual arguments are more than the formal arguments, the extra actual arguments are discarded • If the actual arguments are less than the formal arguments, the unmatched formal arguments are initialized to some garbage values • No error message will be generated • The formal arguments must be valid variable names • The actual arguments my be variable names, expression, or constants • When a function call is made, only a copy of the values of actual arguments is passed into the called function
  • 34. EXAMPLE #include <stdio.h> #include<conio.h> add(int, int); void main() { int a,b; printf("nEnter two number:"); scanf("%d%d",&a,&b); add(a,b); } add(int x, int y) //function with arguments { int z; z=x+y; printf("nSum is:%d",z); } OUTPUT: Enter two number:2 4 Sum is:6
  • 35. ARGUMENTS WITH RETURN VALUES • Here data transfer take place between the calling function and the called function as well as between called function and calling function . • It is a two way data communication, i.e. the called program receives data from calling program and it return some value to the calling program. • A self-contained and independent function should behave like a ‘black box’ that receives a predefined form of input and outputs a desired value
  • 36.
  • 37. EXAMPLE #include <stdio.h> #include<conio.h> add(int, int); void main() { int a,b; float c; printf("nEnter two number:"); scanf("%d%d",&a,&b); c=add(a,b); printf("nSum is:%f",c); } add(int x, int y) { float z; z=x+y/3; return(z); } OUTPUT: Enter two number:6 7 Sum is:13
  • 38. RETURNING FLOAT VALUE • C function returns a value of the type int as a default case when no other type is specified explicitly. return(z); • Return the integer value of sum • This is due to the absence of the type-specifier in the function header • There will be times when we may find it necessary to receive the float or double type of data • We must explicitly specify the return type on both the function definition and the prototype declaration
  • 39. EXAMPLE #include <stdio.h> #include<conio.h> float add(int, int); void main() { int a,b; float c; printf("nEnter two number:"); scanf("%d%d",&a,&b); c=add(a,b); printf("nSum is:%f",c); } float add(int x, int y) { float z; z=x+y/3; return(z); } OUTPUT: Enter two number:6 7 Sum is:13
  • 40. RETURNING NON-INTEGER VALUE • The type-specifier tells the compiler, the type of data the function is to return • The called function must be declared at the start of the body in the calling function, like any other variable. This is to tell the calling function the type of data that the function is actually returning float mul(float, float); double div(float, float); main() { float a,b; a = 12.345; b = 9.82; printf("%fn", mul(a,b)); printf("%fn", div(a,b)); } float mul(float x,float y) { return(x*y); } double dic(float p, float q) { return(p/q); }
  • 41. NO ARGUMENTS BUT RETURNS A VALUE • There could be occasions where we may need a design functions that may not take any arguments but returns a value to the calling function. int get_number(void); main() { int m = get_number(); printf(“%d”,m); } int get_number(void) { int number; scanf(“%d”, &number); return(number); }
  • 42. FUNCTIONS RETURNING NOTHING • Functions that do not return any values are not declared in the main main() { printline(); value(); printline(); } printline() { .... } value() { .... } • We can also declare them in the main with the qualifier void • This states explicitly that the functions do not return values main() { void printline(); void value(); void printline(); } void printline() { .... } void value() { .... }
  • 43. FUNCTIONS THAT RETURN MULTIPLE VALUES • A return statement can return only one value. • To get more information from a function, we can achieve this in C using the arguments not only to receive information but also to send back information to the calling function. • The arguments that are used to “send out” information are called output parameters. • The mechanism of sending back information through arguments is achieved using what are known as the address operator (&) and indirection operator (*).
  • 44. PROGRAM void mathoperation(int x, int y, int *s, int *d); main() { int x = 20, y = 10, s, d; mathoperation(x,y,&s,&d); printf("s=%dn d=%dm", s,d); } void mathoperation(int x, int y, int *sum, int *diff) { *sum = a+b; *diff = a-b; } • x and y – input arguments • s and d – output arguments • We pass – Value of x to a – Value of y to b – Address of s to sum – Address of d to diff • The body of the function when executed add the value and find difference and store the result in memory location pointed by sum and diff.
  • 45. FUNCTIONS THAT RETURN MULTIPLE VALUES • The indirection operator * indicates the variables are to store addresses, not actual values of variables • The operator * is known as indirection operator because it gives an indirect reference to a variable through its address • The variables *sum and *diff are known as pointers and sum and diff as pointer variables • They are declared as int, they can point to locations of int type data • The use of pointer variables as actual parameters for communicating data between functions is called “pass by pointers” or “call by address or reference”.
  • 46. NESTING OF FUNCTIONS • C permits nesting of functions freely • main can call function1, which calls function2, which calls function3, …..and so on
  • 47.
  • 48. RECURSION • When a called function in turn calls another function a process of ‘chaining’ occurs • Recursion is a special case, where a function calls itself • EXAMPLE: main() { printf("This is an example of recursionn"); main(); } • OUTPUT: This is an example of recursion This is an example of recursion This is an example of recursion This is an exa • Execution is terminated abruptly
  • 49. EXAMPLE #include<stdio.h> #include<conio.h> void main() { int a; int factorial (int); printf("nEnter the number:"); scanf("%d",&a); printf("The factorial of %d! is %d",a,factorial(a)); } int factorial(int x) { int f; if(x==1) return(1); else f=x*factorial (x-1); return(f); } OUTPUT: Enter the number:5 The factorial of 5! is 120
  • 50. FUNCTIONS WITH 1D ARRAYS • Possible to pass the values of an array to a function • To pass an array to a called function, it is sufficient to list the name of the array without any subscripts, and the size of the array as arguments • The call: largest(a,n); • will pass all the elements contained in the array a of size n. • The called function expecting this call must be appropriately defined • The largest function header is float largest(float array[], int size)
  • 51. FUNCTIONS WITH 1D ARRAYS • The function header(largest) is defined to take two arguments, the array name and the size of the array to specify the number of elements in the array • The declaration of formal argument array is float array[]; • The pair of brackets informs the compiler that the arguments array is an array of numbers • It is not necessary to specify the size of the array here
  • 52. FUNCTIONS WITH 1D ARRAYS • Here an array is transferred as parameter to a function. void main() void fun(int b[], int n) { { void fun(int[],int); int x,b[5]; int a[5],n; ………….. …………… ………….. fun(a,n); …………… } }
  • 53. EXAMPLE #include<stdio.h> #include<conio.h> void add(int[],int b); void main() { int a[5],i,n; clrscr(); printf("n Enter the Number: "); scanf("%d",&n); printf("n Enter the Values: "); for(i=0;i<n;i++) scanf("%d",&a[i]); add(a,n); } void add(int b[],int x) { int sum=0,i; for(i=0;i<x;i++) sum=sum+b[i]; printf("nThe sum is: %d",sum); } OUTPUT: Enter the Number: 5 Enter the Values: 1 2 3 4 5 The sum is: 15
  • 54. FUNCTIONS WITH 2D ARRAYS • Can also pass multi-dimensional arrays to functions. The rules are: – The function must be called by passing only the array name – In the function definition, we must indicate that the array has two-dimensional by including two sets of brackets – The size of the second dimension must be specified – The prototype declaration should be similar to the function header
  • 55. PROGRAM main() { int M=3, N=2; float average(int [][N], int, int); float mean; int matrix[M][N] = { {1,2}, {3,4}, {5,6} }; mean = average(matrix, M, N); } float average(int x[][N], int M,int N) { int i, j; float sum = 0.0; for(i=0; i<M; i++) for(j=0; j<N; j++) sum+=x[i][j]; return(sum/(M*N)); }
  • 56. PASSING STRINGS TO FUNCTIONS • The strings are treated as character arrays in C and therefore the rules for passing strings to function are very similar to those for passing arrays to functions • Basic rules are – The string to be passed must be declared as a formal argument of the function when it is defined Example: void display(char item_name[]) { ... }
  • 57. PASSING STRINGS TO FUNCTIONS – The function prototype must show that the argument is a string void dispay(char str[]); – A call to the fuction must have a string array name without subscripts as its actual argument Example: display(names); Name is a properly declared string array in the calling function • Like arrays, strings in C cannot be passed by value to function
  • 58. THE SCOPE, VISIBILITY AND LIFETIME OF VARIABLES • It is very important to understand the concept of storage classes and their utility in order to develop efficient multifunction programs • In C there are four storage classes – Automatic variables – External variables – Static variables – Register variables • Here we discuss the scope, visibility and longevity of the above class of variables
  • 59. THE SCOPE AND LIFETIME OF VARIABLES IN FUNCITONS • SCOPE OF VARIABLE – Determines over what parts of the program a variable is actually available for use (active) • LONGEVITY – Refers to the period during which a variable retains a given value during execution of program (alive) – It has a direct effect on the utility of a given variables • VISIBILITY • The visibility refers to the accessibility of a variable from the memory • Variables are categorized depending on the place of their declaration – Internal (local) • Internal variables are those which are declared within a particular function – External (global) • External variables are declared outside of any function
  • 60. AUTOMATIC VARIABLES • Automatic variables are declared inside a function in which they are to be utilized • They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic • Automatic variables are therefore private to the function in which they are declared • Automatic variables are also referred to as local or internal variables
  • 61. AUTOMATIC VARIABLES • A variable declared inside a function without storage class specification is, by default, an automatic variable • The storage class of the variable number is automatic main() { int number; ....... } • We may also use the keyword auto to declare automatic variables explicitly main() { auto int number; ....... }
  • 62. EXAMPLE void function1(void); void function2(void); main() { int m = 1000; function2(); printf("%dn",m); } void function1(void) { int m = 10; printf("%dn",m); } void function2(void) { int m = 100; function1(); printf("%dn",m); }
  • 63. EXAMPLE void function1(void); void function2(void); main() { int m = 1000; function2(); printf("%dn",m); } void function1(void) { int m = 10; printf("%dn",m); } void function2(void) { int m = 100; function1(); printf("%dn",m); } OUTPUT: 10 100 1000
  • 64. AUTOMATIC VARIABLES • There are two consequences of the scope and longevity of auto variables • Any variable local to main will normally live throughout the whole program, although it is active only in main. • During recursion, the nested variables are unique auto variables
  • 65. EXTERNAL VARIABLES • Variables that are both alive and active throughout the entire program are known as external variables • They are also known as global variables • Global variables can be accessed by any function in the program • External variables are declared outside a function
  • 66. EXTERNAL VARIABLES int number; float length = 7.5; main) { ..... } function1() { ..... } function2() { ..... } • The variables number and length are available for use in all the three functions • In case a local variables and a global variable have the same name, the local variable will have precedence over the global one in the function where it is declared
  • 67. EXTERNAL VARIABLES int count; main() { count = 10; ..... } function() { int count = 0; .... count = count+1; } • When the function references the variable count, it will be referencing only its local variable, not the global one • The value of count in main will not be affected
  • 68. EXAMPLE int fun1(void); int fun2(void); int fun3(void); int x; main() { x = 10; printf("x = %dn",x); printf("x = %dn",fun1()); printf("x = %dn",fun2()); printf("x = %dn",fun3()); } fun1(void) { x = x + 10; } fun2(void) { int x x = 1; return(x); } fun3(void) { x = x + 10; }
  • 69. EXAMPLE int fun1(void); int fun2(void); int fun3(void); int x; main() { x = 10; printf("x = %dn",x); printf("x = %dn",fun1()); printf("x = %dn",fun2()); printf("x = %dn",fun3()); } fun1(void) { x = x + 10; } fun2(void) { int x x = 1; return(x); } fun3(void) { x = x + 10; } OUTPUT: x = 10 x = 20 x = 1 x = 30
  • 70. EXTERNAL VARIABLES • Once a variable has been declared as global, any function can use it and change its value • Then subsequent functions can reference only that new value • Global variable is that it is visible only from the point of declaration to the end of the program main() { y = 5; .... } int y; func1() { y = y + 1; } • As for as main is concerned, y is not defined. So, the compiler will issue an error message • Global variables are initialized to zero by default • The statement y = y + 1 will assign 1 to y.
  • 71. EXTERNAL DECLARATION • The main cannot access the variable y as it has been declared after the main function • This problem can be solved by declaring the variable with the storage class extern main() { extern int y; /* external declaration */ .... } func1() { extern int y; /* external declaration */ ..... } int y; /* definition */ • Although the variable y has been defined after both the functions, the external declaration of y inside the function informs the compiler that y is an integer type defined somewhere else in the program • The extern declaration does not allocate storage space for variables
  • 72. EXTERNAL DECLARATION main() { int i; void print_out(void); extern float height[]; .... print_out(); } void print_out(void) { extern float height[]; int i; ...... ..... } float height[SIZE]; • An extern within a function provides the type information to just that one function • We can provide type information to all functions within a file by placing external declaration before any of them
  • 73. EXTERNAL DECLARATION • The distinction between definition and declaration also applies to functions • A function is defined when its parameters and function body are specified • This tells the compiler to allocate space for the function code and provides type information for the parameters • Since functions are external by default, we declare them without the qualifier extern • void print_out(); is equivalent to • extern void print_out(); extern float height[]; main() { int i; void print_out(void); .... print_out(); } void print_out(void) { int i; ...... } float height[SIZE];
  • 74. STATIC VARIABLES • The value of static variables persists until the end of the program • A variable can be declared static using the keyword static static int x; static float y; • A static variable may be an internal or external type, depending on the place of declaration
  • 75. EXAMPLE void stat(void) main() { int i; for(i=1; i<=3; i++) stat(); } void stat(void) { static int x = 0; x = x + 1; printf("x = %dn",x); } OUTPUT: x = 1 x = 2 x = 3 • If we had declared x as an auto variable. The output would be X = 1 X = 1 X = 1
  • 76. STATIC VARIABLES Internal static variables • Declared inside a function • The scope extend up to end of the function in which they are defined • Similar to auto variables, except that they remain inexistence (alive) throughout the remainder of the program • Static variable is initialized only once, when the program is compiled. It is never initialized again External static variables • Declared outside of all functions and is available to all the functions in that program • The difference between a static external variable and a simple external variable is that: – the static external variable is available only within the file where it is defined while the simple external variable can be accessed by other files
  • 77. SCOPE OF FUNCTION • To make a particular function accessible only to the functions in the file in which it is defined and not to any function in other files by defining that function with the storage class static
  • 78. REGISTER VARIABLES • Register access is much faster than a memory access • We can make a variable to be placed in one of the machine register instead of memory using register int count; • Most compiler allow int or char variables to be placed in the register • ANSI standard does not restrict to any particular data type • C will automatically convert register variables into non-register variables once the limit is reached
  • 79.
  • 80. MULTIFILE PROGRAMS • More than one source file is compiled separately and linked later to form an executable object code • This approach is very useful because any change in one file does not affect other files thus eliminating the need for recompilation of the entire program • Multiple source files can share a variable declared as an external variable • Variables that are shared by two or more files are global variables and we must declare them accordingly in one file and then explicitly define them with extern in other file
  • 81. USE OF EXTERN IN A MULTIFILE PROGRAM file1.c main() { extern int m; int i; .... } function1() { int j; .... } file2.c int m /* global variable */ function2() { int i; ..... } function3() { int count; ..... }
  • 82. USE OF EXTERN IN A MULTIFILE PROGRAM file1.c int m; /* global variable */ main() { int i; .... } function1() { int j; .... } file2.c extern int m; function2() { int i; .... } function3() { int count; ..... }
  • 83. MULTIFILE PROGRAMS • The extern specifier tells the compiler that the following variables types and names have already been declared elsewhere and no need to create storage space for them • It is the responsibility of the linker to resolve the reference problem • A function defined in one file and accessed in another must include a function declaration • The declaration identifies the function as an external function whose definition appears elsewhere • We place such declarations at the beginning of the file, before all functions • Although all functions are external, it would be good practice to explicitly declare such functions with storage class extern
  • 84. TO FIND THE MAXIMUM main() { float largest(float a[],int n); float value[4] = {2.5, -4.75, 1,2. 3.6} printf("%fn", largest(value,4)); } float largest(float a[], int n) { int i; float max; max = a[0]; for(i=1;i<n;i++) if(max<a[i]) max = a[i]; return(max); }
  • 85. TO SORT AN ARRAY OF INTEGERS main() { int i; int marks[5] = {40, 90, 73, 81, 35}; printf("Marks before sortingn"); for(i=0;i<5;i++) printf("%d ",marks[i]); printf("nn"); sort(5, marks); printf("Marks after sortingn"); for(i=0;i<5;i++) printf("%4d ",marks[i]); } void sort(int m, int x[]) { int i,j,t; for(i=1;i<=m-1;i++) for(j=1;j<=m-i;j++) if(x[j-1]>=x[j]) { t = a[j-1]; x[j-1] = x[j]; x[j] = t; } }
  • 86. SWAPPING NUMBERS USING CALL BY REFERENCE #include <stdio.h> void swap(int*, int*); int main() { int x, y; printf("Enter the value of x and yn"); scanf("%d%d",&x,&y); printf("Before Swappingnx = %dny = %dn", x, y); swap(&x, &y); printf("After Swappingnx = %dny = %dn", x, y); return 0; } void swap(int *a, int *b) { int temp; temp = *b; *b = *a; *a = temp; }
  • 87. FIBONACCI SERIES USING RECURSION #include<stdio.h> int Fibonacci(int); main() { int n, i = 0, c; scanf("%d",&n); printf("Fibonacci seriesn"); for ( c = 1 ; c <= n ; c++ ) { printf("%dn", Fibonacci(i)); i++; } return 0; } int Fibonacci(int n) { if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) ); }