SlideShare ist ein Scribd-Unternehmen logo
1 von 88
US
E
R-DEFINE
D
FUNCTIONS
INTRODUCTION
• Cfunctions can be classified into twocategories
– Library functions
– User-defined functions
LIBRARYFUNCTIONS
– Library functions are not required to be written by
us
– printf and scanf belong to the category of library
function
– sqrt, cos, strcat, etc aresome of library functions
USER-DEFINEDFUNCTIONS
– User-defined functions hasto be developed bythe
user at the time of writingaprogram
– Auser-defined functions can later become apart
of the Cprogramlibrary
– main is an example of user-definedfunctions
NEEDFORUSER-DEFINEDFUNCTIONS
•
•
Everyprogram must have amain function
It is possible to code any program utilizing only main
function, it leads toanumber of problems
The program may become too large and complex
and asa 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 asingleunit
These subprograms called ‘functions’ are much
easier to understand, debug, andtest
•
•
•
NEEDFORUSER-DEFINEDFUNCTIONS
•
•
•
• There are times when some types of operation or
calculation is repeated at many points throughouta
program
In such situations, we may repeat theprogram
statements whenever they areneeded
Another approach is to design afunction thatcan be
called and used whenever required
Thissavesboth time andspace
NEEDFORUSER-DEFINEDFUNCTIONS
• Thissub-sectioning approach clearly results in a
number of advantages
– It facilitates top-down modularprogramming.
– Thelength of asource program can be reduced by using
functions at appropriate places. Thisfactor isparticularly
critical with microcomputers where memory spaceis
limited
– It is easy to locate and isolate afaulty function for further
investigations
– Afunction may be used by many other programs, this
means that aCprogram can build on what othershave
already done, instead ofstarting over, from scratch.
AMULTI-FUNCTION PROGRAM
•
•
Afunction is aself-contained block of codethat
performs aparticular task
Onceafunction hasbeen designed and packed, it can
be treated asa‘black box’ that takes some datafrom
the main program and returns avalue
The inner details are invisible to the rest of the program
Example:
main()
{
printline();
printf("This illustrated the useof Cfunctionsn");
printline();
}
printline()
{
int i;
for(i=1; i<40; i++)
pintf("-");
printf("n");
}
•
•
ELEMENTSOFUSER-DEFINED
FUNCTIONS
•
•
Functions are classified asone of the derived data types inC
Candefine functions and usethem like any other variablesin
Cprograms.
Similarities between functions and variables inC
– Both function name and variable namesare considered
identifiers and therefore they must adhere to the rules for
identifiers.
– Likevariables, functions have types (such asint) associated with
them
– Likevariables, function names and their types must bedeclared
and defined before they are used inaprogram
•
ELEMENTSOFUSER-DEFINED
FUNCTIONS
• There are three elements related to functions
– Function definition
– Function call
– Function declaration
Thefunctiondefinition is an independent program module
that is specially written to implement the requirements of the
function
Touse this function we need to invoke it at arequired place
in the program. Thisis known asthe functioncall.
Theprogram that calls the function is referred toasthe
callingprogram or calling function.
Thecalling program should declare any function that is tobe
used later in the program. Thisis known asthe function
declaration or functionprototype.
•
•
•
•
FUNCTION
DEFINITIONOFFUNCTIONS
• Afunction definition, also known asfunction
implementation shall include the followingelements;
– Function name;
– Function type;
– List of parameters;
– Local variable declaration;
– Function statements; and
– Areturn statement.
All six elements are grouped into twoparts, namely,
– Function header (First three elements);and
– Function body (Second three elements)
•
THEFORMOFCFUNCTION
function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;
return(expression);
}
Thefirst line function_type function_name(parameterlist) is
known asthe function header.
Thestatements within the opening and the closingbrace
constitute the functionbody.
•
•
FUNCTIONDEFINITION
• Function Header
– Thefunction header consists of three parts: the function type (also
known asreturn type), the function name and formal parameterlist.
– 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, Cassumeit asan integer
type.
– If the function is not returning anything then we need to specify the
return type asvoid
– Thefunction name is any valid Cidentifier and therefore ,just follow
the samerules of formation asother variable namesinC
•
FORMALPARAMETERLIST
• The parameter list declares the variables that will receive the
data sent by the callingprogram.
They serve asinput data to the function to carry out the
specified task.
Theyrepresent actual input values, they are often referredto
asformal parameters.
Theseparameters can also be used to send values to the
calling programs
Theparameter is known asarguments.
– float quadratic (int a, int b, intc) { …..}
– double power (double x, int n) {…..}
– int sum(int a, int b) { …..}
There is no semicolon after the closingparenthesis
Thedeclaration parameter variables cannot becombined
•
•
•
•
•
•
FORMALPARAMETERLIST
• Toindicate that the parameter list is empty,we usethe
keyword void between the parentheses asin
void printline (void)
{
…
}
Many compiler accept an empty set ofparentheses
void printline()
It is good to use void to indicate a nill parameter list
•
•
FUNCTIONBODY
• Thefunction body contains the declarations andstatements
necessary for performing the required task. Thebody
enclosed in braces, contains threeparts,
– Localdeclarations that specify the variables needed by thefunction
– Function statements that perform the task of the function
– Areturn statement that returns the value evaluated by thefunction
If afunction does not return any value, we can omit the
return statement.
Its return type should be specified asvoid
•
•
RETURNVALUESANDTHEIRTYPES
•
•
•
•
• Afunction may or may not send back any valueto
the callingfunction
Done through return statement
It is possible to send any number of values to the
called function
Thecalled function can only return one value percall
SYNTAX:
return;
or
return (expression);
RETURNVALUESANDTHEIRTYPES
•
•
• return;
– Plain return does not return anyvalue
– Acts asthe closing brace of thefunction
– Thecontrol is immediately passedback to the callingfunction
– EXAMPLE:
if(error)
return;
return (expression);
– Return the value of theexpression
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
– Thelast statement can be combined into one statement
as return(x*y);
RETURNVALUESANDTHEIRTYPES
•
•
•
Afunction may have more than one returnstatements
Thissituation arises when the value returned isbased
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 afunction to return aparticular type ofdata
by using type specifier in the functionheader
– EXAMPLE:
double product(x,y)
float sqr_root(p)
– When avalue is returned, it is automatically cast tothe
function’s type
•
CALLINGAFUNCTION
• Afunction canbe called by simply using the function
name in astatement
• When the function encounters afunction call,the
control is transferred tothe function mul(x,y)
main()
{
int p;
p =mul(10,5);
printf("%dn", p);
}
int mul(int x,inty)
{
int p; /*local variables*/
p =x* y;/* x=10, y =5*/
return(p);
}
CALLINGAFUNCTION
• Thefunction is executed and the value isreturned
and assigned to p
Afunction which returns avalue 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");
Afunction cannot be used on the right side ofan
assignment statement
mul(a,b) =15;
Afunction that does not return any value may notbe
used in expression; but can be called to perform
certain tasks specified in thefunction
main() { printline();}
•
•
•
FUNCTIONDECLARATION
• Afunction declaration consists of fourparts
– Function type (return type)
– Function name
– Parameter list
– Terminating semicolon
Format
– Function-type function-name (parameterlist);
Very similar tothe function header line expect the
terminating semicolon.
– int mul(int m, int n); /* Function prototype */
Equally acceptable forms of declarationsare
– int mul (int,int);
– mul (int a, intb);
– mul (int, int);
•
•
•
FUNCTIONDECLARATION
• When afunction does not take any parameters and doesnot
return any value, its prototype is writtenas:
void display (void);
Aprototype declaration may be placed in two places ina
program.
– Above all the functions (including main) (globalprototype)
– Inside afunction definition (localprototype)
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 enhancesdocumentation
•
•
•
CATEGORYOFFUNCTIONS
• Category 1: Functions with no arguments andno
return values
Category 2: Functions with arguments and noreturn
values
Category 3: Functions with arguments andone
return values
Category 4: Functions with no arguments butreturn
avalue
Category 5: Functions that return multiplevalues
•
•
•
•
NOARGUMENTSANDNORETURN
VALUES
•
•
•
• When afunction hasno arguments, it doesnot
receive any data from the callingfunction
When itdoes not return avalue, the calling function
does not receive any data from thecalled function
There is no data transfer between thecalling
function and the calledfunction
There is only a transfer of control but not data
EXAMPLE
#include <stdio.h>
#include<conio.h>
void add(void);
//calling function
void main()
{
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
Sumis:7
ARGUMENTSBUTNORETURN
VALUES
• Thecalling function read data fromthe terminal and
passit on to thecalled function.
It is aoneway data communication,i.e. the called
program receives data from calling program but it
does not return any value tothe calling program.
Thisapproach is wiser becausethe calling function
can check for the validity of data, if necessary, before
itis handed over to the called function.
Called function with arguments
value(p,r,n)
•
•
•
ARGUMENTSBUTNORETURN
VALUES
• Thefunction call
value(500,0.12,5)
Would send the value 500, 0.12, 5 to thefunction
value(float p, float r, intn)
and assign500 to p, 0.12 to r and 5 to n
Thevalues 500, 0.12, 5 are the actualarguments
Thearguments p, r, n are the formalarguments
Theactual and formal arguments should matchin
number, type, andorder
Thevalues of actual arguments are assigned to the
formal arguments on aone to onebasis
•
•
•
•
•
•
ARGUMENTSBUTNORETURN
VALUES
• if the actual arguments are more than the formal
arguments, the extra actual arguments arediscarded
If the actual arguments are lessthan the formal
arguments, the unmatched formal argumentsare
initialized to some garbagevalues
No error messagewill begenerated
Theformal arguments must be valid variablenames
Theactual arguments my be variable names,
expression, or constants
When afunction call is made, only acopy of the
values of actual arguments is passedinto thecalled
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
Sumis:6
ARGUMENTSWITHRETURNVALUES
•
•
• Here data transfer take place between the calling
function and the called function aswell asbetween
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 thecalling program.
Aself-contained and independent function should
behave like a‘black box’ that receives apredefined
form of input and outputsadesired 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
Sumis:13
RETURNINGFLOATVALUE
• Cfunction returns avalue of the type int asadefault
casewhen no other type is specifiedexplicitly.
return(z);
Return the integer value ofsum
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 prototypedeclaration
•
•
•
•
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, inty)
{
float z;
z=x+y/3;
return(z);
}
OUTPUT
:
Enter two number:6
7
Sumis:13
RETURNINGNON-INTEGERVALUE
• The type-specifier tells the
compiler, the type of data
the function is toreturn
Thecalled function mustbe
declared at the start of the
body in the callingfunction,
like any other variable. This
is to tell thecalling 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,floaty)
{
return(x*y);
}
double dic(float p, floatq)
{
return(p/q);
}
NOARGUMENTSBUTRETURNSA
VALUE
• There could be
occasionswhere we
may need adesign
functions that may not
take any argumentsbut
returns avalue 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);
}
FUNCTIONSRETURNINGNOTHING
• Functions that do not return
any values are not declaredin
the main
main()
{
printline();
value();
printline();
}
printline()
{
....
}
value()
{
....
}
• We can also declare them in
the main with the qualifier
void
• Thisstates explicitly that the
functions do not return
values
main()
{
void printline();
void value();
void printline();
}
void printline()
{
....
}
void value()
{
....
}
FUNCTIONSTHATRETURN
MULTIPLEVALUES
•
•
Areturn statement can return only onevalue.
Toget more information from afunction, wecan
achieve this in Cusing the arguments not only to
receive information but also to send back
information to the callingfunction.
Thearguments that are used to “sendout”
information are called outputparameters.
Themechanism of sending back information through
arguments is achieved using what are known asthe
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;
}
•
•
•
xand y – input arguments
sand d – output arguments
We pass
– Valueof
– Valueof
xto a
y to b
– Addressof
– Addressof
sto sum
d to diff
• Thebody of the function
when executed add the
value and find difference
and store the result in
memory location pointed
by sumand diff.
FUNCTIONSTHATRETURN
MULTIPLEVALUES
• The indirection operator * indicates the variables are to store
addresses, not actual values of variables
Theoperator * is known asindirection operator because it gives
an indirect reference to avariable through itsaddress
Thevariables *sum and *diff are known aspointers andsum
and diff aspointer variables
They are declared asint, they can point to locations of int type
data
Theuseof pointer variables asactual parameters for
communicating data between functions is called “passby
pointers” or “call by address orreference”.
•
•
•
•
NESTINGOFFUNCTIONS
•
•
Cpermits nesting of functionsfreely
main can call function1, which calls function2,which
calls function3, …..andsoon
RECURSION
•
•
•
When acalled function in turncalls another function a
process of ‘chaining’occurs
Recursion is aspecial case,where afunction 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
Thisis 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
Thefactorial of 5! is120
FUNCTIONSWITH1DARRAYS
•
•
Possible to passthe values of an array toafunction
To pass an array to a called function, it is sufficient to
list the name of the array without any subscripts, and
the sizeof the array asarguments
The call:
largest(a,n);
will passall the elements contained in thearray aof
size n.
Thecalled function expecting this call mustbe
appropriately defined
Thelargest function headeris
float largest(float array[], intsize)
•
•
•
•
FUNCTIONSWITH1DARRAYS
• Thefunction header(largest) is defined to take two
arguments, the array name and the sizeof thearray
to specify the number of elements in the array
Thedeclaration of formal argument arrayis
float array[];
Thepair of brackets informs the compiler thatthe
arguments array is an array of numbers
It is not necessary to specify the size of the array
here
•
•
•
FUNCTIONSWITH1DARRAYS
• Here an array is transferred asparameter to a
function.
void fun(int b[], intn)
{
int x,b[5];
…
…
…
…
.
.
…
…
…
…
.
.
void main()
{
void fun(int[],int);
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 theNumber:
");
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
Thesum is: 15
FUNCTIONSWITH2DARRAYS
• Canalso passmulti-dimensional arrays to functions.
Therules are:
– Thefunction must be called by passing only thearray
name
– In the function definition, we must indicate that the array
hastwo-dimensional by including two sets ofbrackets
– Thesizeof the second dimension must bespecified
– Theprototype declaration should be similar tothe
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], intM,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));
}
PASSINGSTRINGSTOFUNCTIONS
• Thestrings are treated ascharacter arrays in Cand
therefore the rules for passing strings to function are
very similar to those for passingarrays to functions
Basicrules are
– Thestring to be passedmust be declared asaformal
argument of the function when it is defined
Example:
voiddisplay(char item_name[])
{
...
}
•
PASSINGSTRINGSTOFUNCTIONS
– Thefunction prototype must show that the argument is a
string
voiddispay(char str[]);
– Acall to the fuction must have astring arrayname without
subscripts asits actual argument
Example:
display(names);
Nameis aproperly declared string array in the callingfunction
Like arrays, strings in Ccannot be passedby value to
function
•
THESCOPE,VISIBILITYAND
LIFETIMEOFVARIABLES
• It is very important to understand the concept of
storage classesand their utility in order to develop
efficient multifunction programs
In Cthere are four storageclasses
– Automatic variables
– External variables
– Static variables
– Register variables
Here we discussthe scope, visibility and longevityof
the above classof variables
•
•
THESCOPEANDLIFETIMEOF
VARIABLESINFUNCITONS
• SCOPEOFVARIABLE
– Determines over what parts of the program a variable is actually
available for use(active)
LONGEVITY
– Refers to the period during whichavariable retains agiven value
during execution of program(alive)
– It has adirect effect on the utility of agiven variables
VISIBILITY
•
•
• The visibility refers to the accessibility of avariable from the
memory
• Variables are categorized depending on the place oftheir
declaration
– Internal (local)
• Internal variables are those which are declared within aparticular
function
– External (global)
• External variables are declared outside of anyfunction
AUTOMATICVARIABLES
• Automatic variables are declared inside afunction in
which they are to beutilized
Theyare created when the function is called and
destroyed automatically when the function isexited,
hence the nameautomatic
Automatic variables are therefore private tothe
function in which they aredeclared
Automatic variables are also referred to aslocalor
internal variables
•
•
•
AUTOMATICVARIABLES
• Avariable declared inside afunction without storage
classspecification is, by default, an automatic variable
Thestorage classof the variable number isautomatic
main()
{
int number;
.......
}
We may also usethe keyword auto to declareautomatic
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
AUTOMATICVARIABLES
• There are two consequences of thescopeand
longevity of autovariables
Any variable local to main will normally live
throughout the whole program, although itis active
only in main.
During recursion, the nested variables areunique
auto variables
•
•
EXTERNALVARIABLES
• Variables that are both alive and activethroughout
the entire program are known asexternalvariables
Theyare also known asglobal variables
Global variables can be accessedby any function in
the program
External variables are declared outside afunction
•
•
•
EXTERNALVARIABLES
int number;
float length =7.5;
main)
{
.....
}
function1()
{
.....
}
function2()
{
.....
}
•
•
Thevariables number and length are available for usein allthe
three functions
In casealocal variables and aglobal variable have the same
name, the local variable will have precedence over theglobal one
in the function where itis declared
EXTERNALVARIABLES
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
EXTERNALVARIABLES
•
•
•
Onceavariable hasbeen declared asglobal, any function can
useit and change itsvalue
Then subsequent functions can reference only that newvalue
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;
}
Asfor asmain is concerned, y is not defined. So,thecompiler
will issue an error message
Global variables are initialized to zero bydefault
Thestatement y =y +1 will assign1 to y.
•
•
•
EXTERNALDECLARATION
•
•
Themain cannot accessthe variable y asit hasbeendeclared
after the mainfunction
Thisproblem can be solved by declaring the variable withthe
storage classextern
main()
{
extern int y; /* external declaration */
....
}
func1()
{
extern int y; /* external declaration */
.....
}
int y; /* definition */
Although the variable y hasbeen defined after boththe
functions, the external declaration of y inside the function
informs the compiler that y is an integer type defined
somewhere else in the program
Theextern declaration does not allocate storage spacefor
variables
•
•
EXTERNALDECLARATION
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 withinafunction provides the type information to
just that onefunction
We can provide type information to all functions within afile by
placing external declaration before any ofthem
EXTERNALDECLARATION
• Thedistinction between
definition anddeclaration
also applies to functions
Afunction is defined when
its parameters andfunction
body are specified
Thistells the compiler to
allocate spacefor the
function code andprovides
type information for the
parameters
Since functions are external
by default, we declare them
without the qualifierextern
voidprint_out(); is
equivalent to
extern voidprint_out();
•
•
•
•
•
extern float height[];
main()
{
int i;
void print_out(void);
....
print_out();
}
void print_out(void)
{
int i;
......
}
float height[SIZE];
STATICVARIABLES
• Thevalue of static variables persists until the end ofthe
program
Avariable can be declared static using the keyword
static
static int x;
static float y;
Astatic variable may be an internal or externaltype,
depending on the place ofdeclaration
•
•
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 xasan
auto variable. The output
would be
X=1
X=1
X=1
STATICVARIABLES
Internal static variables
•
•
•
•
Declared inside afunction
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 ofthe program
Static variable is initialized only once, when theprogram is
compiled. It is never initializedagain
External static variables
• Declared outside of all functions and is available to all the
functions in thatprogram
• Thedifference between astatic external variable and asimple
external variable isthat:
– the static external variable is available only within the file where it is
defined while the simple external variable canbe accessedby otherfiles
SCOPEOFFUNCTION
• 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 classstatic
REGISTERVARIABLES
•
•
Register accessis much faster than amemory access
We can make avariable to be placed in one ofthe
machine register instead of memoryusing
register int count;
Most compiler allow int or char variables to be
placed in the register
ANSIstandard does not restrict to any particulardata
type
Cwill automatically convert register variablesinto
non-register variables once the limit isreached
•
•
•
MULTIFILEPROGRAMS
• 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 avariable declaredas
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 withextern in other file
•
•
•
USEOFEXTERNIN AMULTIFILE
PROGRAM
file1.c file2.c
main()
{
extern int m;
int i;
....
}
function1()
{
int j;
....
}
int m /* global variable */
function2()
{
int i;
.....
}
function3()
{
int count;
.....
}
USEOFEXTERNIN AMULTIFILE
PROGRAM
file1.c file2.c
int m; /* global variable */
main()
{
int i;
....
}
function1()
{
int j;
....
}
extern int m;
function2()
{
int i;
....
}
function3()
{
int count;
.....
}
MULTIFILEPROGRAMS
• Theextern specifier tells the compiler that thefollowing
variables types and names have already been declared
elsewhere and no need to create storage spacefor
them
It is the responsibility of the linker to resolve the
reference problem
Afunction defined in one file and accessedinanother
must include afunction declaration
Thedeclaration identifies the function asanexternal
function whose definition appearselsewhere
We place suchdeclarations at the beginning of thefile,
before all functions
Although all functions are external, it would be good
practice to explicitly declare suchfunctions withstorage
classextern
•
•
•
•
•
TOFINDTHEMAXIMUM
main()
{
float largest(float a[],intn);
float value[4] ={2.5, -4.75, 1,2.3.6}
printf("%fn", largest(value,4));
}
float largest(float a[], intn)
{
int i; float max;
max =a[0];
for(i=1;i<n;i++)
if(max<a[i])
max =a[i];
return(max);
}
TOSORTANARRAYOFINTEGERS
main()
{
int i;
int marks[5] ={40, 90, 73, 81,35};
printf("Marks beforesortingn");
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, intx[])
{
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;
}
}
SWAPPINGNUMBERSUSINGCALL
BYREFERENCE
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x,y;
printf("Enter the value of xandyn");
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;
}
FIBONACCISERIESUSING
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(intn)
{
if ( n ==0)
return 0;
else if ( n ==1)
return 1;
else
return ( Fibonacci(n-1)+
Fibonacci(n-2) );
}
THEEND

Weitere ähnliche Inhalte

Ähnlich wie user-definedfunctions-converted.pptx

Ähnlich wie user-definedfunctions-converted.pptx (20)

Lecture6
Lecture6Lecture6
Lecture6
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Functions
FunctionsFunctions
Functions
 
Functions
Functions Functions
Functions
 
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
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
Function
Function Function
Function
 
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
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Functions
FunctionsFunctions
Functions
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Functions.pptx
Functions.pptxFunctions.pptx
Functions.pptx
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 

Mehr von ZaibunnisaMalik1

Mehr von ZaibunnisaMalik1 (9)

Chp1.3.pptx
Chp1.3.pptxChp1.3.pptx
Chp1.3.pptx
 
Inner Pages 2022_merged (1).pdf
Inner Pages 2022_merged (1).pdfInner Pages 2022_merged (1).pdf
Inner Pages 2022_merged (1).pdf
 
pointer-to-object-.pptx
pointer-to-object-.pptxpointer-to-object-.pptx
pointer-to-object-.pptx
 
Faculty of Science.pdf
Faculty of Science.pdfFaculty of Science.pdf
Faculty of Science.pdf
 
Hadiths of Prophet Mohammed SAW for Campaign.docx
Hadiths of Prophet Mohammed SAW for Campaign.docxHadiths of Prophet Mohammed SAW for Campaign.docx
Hadiths of Prophet Mohammed SAW for Campaign.docx
 
bab3c.ppt
bab3c.pptbab3c.ppt
bab3c.ppt
 
sav_ch09.ppt
sav_ch09.pptsav_ch09.ppt
sav_ch09.ppt
 
struct.pptx
struct.pptxstruct.pptx
struct.pptx
 
CPointer-hk.ppt
CPointer-hk.pptCPointer-hk.ppt
CPointer-hk.ppt
 

Kürzlich hochgeladen

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

user-definedfunctions-converted.pptx

  • 2. INTRODUCTION • Cfunctions can be classified into twocategories – Library functions – User-defined functions
  • 3. LIBRARYFUNCTIONS – Library functions are not required to be written by us – printf and scanf belong to the category of library function – sqrt, cos, strcat, etc aresome of library functions
  • 4. USER-DEFINEDFUNCTIONS – User-defined functions hasto be developed bythe user at the time of writingaprogram – Auser-defined functions can later become apart of the Cprogramlibrary – main is an example of user-definedfunctions
  • 5. NEEDFORUSER-DEFINEDFUNCTIONS • • Everyprogram must have amain function It is possible to code any program utilizing only main function, it leads toanumber of problems The program may become too large and complex and asa 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 asingleunit These subprograms called ‘functions’ are much easier to understand, debug, andtest • • •
  • 6. NEEDFORUSER-DEFINEDFUNCTIONS • • • • There are times when some types of operation or calculation is repeated at many points throughouta program In such situations, we may repeat theprogram statements whenever they areneeded Another approach is to design afunction thatcan be called and used whenever required Thissavesboth time andspace
  • 7. NEEDFORUSER-DEFINEDFUNCTIONS • Thissub-sectioning approach clearly results in a number of advantages – It facilitates top-down modularprogramming. – Thelength of asource program can be reduced by using functions at appropriate places. Thisfactor isparticularly critical with microcomputers where memory spaceis limited – It is easy to locate and isolate afaulty function for further investigations – Afunction may be used by many other programs, this means that aCprogram can build on what othershave already done, instead ofstarting over, from scratch.
  • 8. AMULTI-FUNCTION PROGRAM • • Afunction is aself-contained block of codethat performs aparticular task Onceafunction hasbeen designed and packed, it can be treated asa‘black box’ that takes some datafrom the main program and returns avalue The inner details are invisible to the rest of the program Example: main() { printline(); printf("This illustrated the useof Cfunctionsn"); printline(); } printline() { int i; for(i=1; i<40; i++) pintf("-"); printf("n"); } • •
  • 9. ELEMENTSOFUSER-DEFINED FUNCTIONS • • Functions are classified asone of the derived data types inC Candefine functions and usethem like any other variablesin Cprograms. Similarities between functions and variables inC – Both function name and variable namesare considered identifiers and therefore they must adhere to the rules for identifiers. – Likevariables, functions have types (such asint) associated with them – Likevariables, function names and their types must bedeclared and defined before they are used inaprogram •
  • 10. ELEMENTSOFUSER-DEFINED FUNCTIONS • There are three elements related to functions – Function definition – Function call – Function declaration Thefunctiondefinition is an independent program module that is specially written to implement the requirements of the function Touse this function we need to invoke it at arequired place in the program. Thisis known asthe functioncall. Theprogram that calls the function is referred toasthe callingprogram or calling function. Thecalling program should declare any function that is tobe used later in the program. Thisis known asthe function declaration or functionprototype. • • • •
  • 12. DEFINITIONOFFUNCTIONS • Afunction definition, also known asfunction implementation shall include the followingelements; – Function name; – Function type; – List of parameters; – Local variable declaration; – Function statements; and – Areturn statement. All six elements are grouped into twoparts, namely, – Function header (First three elements);and – Function body (Second three elements) •
  • 13. THEFORMOFCFUNCTION function_type function_name(parameter list) { local variable declaration; executable statement1; executable statement2; return(expression); } Thefirst line function_type function_name(parameterlist) is known asthe function header. Thestatements within the opening and the closingbrace constitute the functionbody. • •
  • 14. FUNCTIONDEFINITION • Function Header – Thefunction header consists of three parts: the function type (also known asreturn type), the function name and formal parameterlist. – 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, Cassumeit asan integer type. – If the function is not returning anything then we need to specify the return type asvoid – Thefunction name is any valid Cidentifier and therefore ,just follow the samerules of formation asother variable namesinC •
  • 15. FORMALPARAMETERLIST • The parameter list declares the variables that will receive the data sent by the callingprogram. They serve asinput data to the function to carry out the specified task. Theyrepresent actual input values, they are often referredto asformal parameters. Theseparameters can also be used to send values to the calling programs Theparameter is known asarguments. – float quadratic (int a, int b, intc) { …..} – double power (double x, int n) {…..} – int sum(int a, int b) { …..} There is no semicolon after the closingparenthesis Thedeclaration parameter variables cannot becombined • • • • • •
  • 16. FORMALPARAMETERLIST • Toindicate that the parameter list is empty,we usethe keyword void between the parentheses asin void printline (void) { … } Many compiler accept an empty set ofparentheses void printline() It is good to use void to indicate a nill parameter list • •
  • 17. FUNCTIONBODY • Thefunction body contains the declarations andstatements necessary for performing the required task. Thebody enclosed in braces, contains threeparts, – Localdeclarations that specify the variables needed by thefunction – Function statements that perform the task of the function – Areturn statement that returns the value evaluated by thefunction If afunction does not return any value, we can omit the return statement. Its return type should be specified asvoid • •
  • 18. RETURNVALUESANDTHEIRTYPES • • • • • Afunction may or may not send back any valueto the callingfunction Done through return statement It is possible to send any number of values to the called function Thecalled function can only return one value percall SYNTAX: return; or return (expression);
  • 19. RETURNVALUESANDTHEIRTYPES • • • return; – Plain return does not return anyvalue – Acts asthe closing brace of thefunction – Thecontrol is immediately passedback to the callingfunction – EXAMPLE: if(error) return; return (expression); – Return the value of theexpression 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 – Thelast statement can be combined into one statement as return(x*y);
  • 20. RETURNVALUESANDTHEIRTYPES • • • Afunction may have more than one returnstatements Thissituation arises when the value returned isbased 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 afunction to return aparticular type ofdata by using type specifier in the functionheader – EXAMPLE: double product(x,y) float sqr_root(p) – When avalue is returned, it is automatically cast tothe function’s type •
  • 21. CALLINGAFUNCTION • Afunction canbe called by simply using the function name in astatement • When the function encounters afunction call,the control is transferred tothe function mul(x,y) main() { int p; p =mul(10,5); printf("%dn", p); } int mul(int x,inty) { int p; /*local variables*/ p =x* y;/* x=10, y =5*/ return(p); }
  • 22. CALLINGAFUNCTION • Thefunction is executed and the value isreturned and assigned to p Afunction which returns avalue 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"); Afunction cannot be used on the right side ofan assignment statement mul(a,b) =15; Afunction that does not return any value may notbe used in expression; but can be called to perform certain tasks specified in thefunction main() { printline();} • • •
  • 23. FUNCTIONDECLARATION • Afunction declaration consists of fourparts – Function type (return type) – Function name – Parameter list – Terminating semicolon Format – Function-type function-name (parameterlist); Very similar tothe function header line expect the terminating semicolon. – int mul(int m, int n); /* Function prototype */ Equally acceptable forms of declarationsare – int mul (int,int); – mul (int a, intb); – mul (int, int); • • •
  • 24. FUNCTIONDECLARATION • When afunction does not take any parameters and doesnot return any value, its prototype is writtenas: void display (void); Aprototype declaration may be placed in two places ina program. – Above all the functions (including main) (globalprototype) – Inside afunction definition (localprototype) 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 enhancesdocumentation • • •
  • 25. CATEGORYOFFUNCTIONS • Category 1: Functions with no arguments andno return values Category 2: Functions with arguments and noreturn values Category 3: Functions with arguments andone return values Category 4: Functions with no arguments butreturn avalue Category 5: Functions that return multiplevalues • • • •
  • 26. NOARGUMENTSANDNORETURN VALUES • • • • When afunction hasno arguments, it doesnot receive any data from the callingfunction When itdoes not return avalue, the calling function does not receive any data from thecalled function There is no data transfer between thecalling function and the calledfunction There is only a transfer of control but not data
  • 27.
  • 28. EXAMPLE #include <stdio.h> #include<conio.h> void add(void); //calling function void main() { 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 Sumis:7
  • 29. ARGUMENTSBUTNORETURN VALUES • Thecalling function read data fromthe terminal and passit on to thecalled function. It is aoneway data communication,i.e. the called program receives data from calling program but it does not return any value tothe calling program. Thisapproach is wiser becausethe calling function can check for the validity of data, if necessary, before itis handed over to the called function. Called function with arguments value(p,r,n) • • •
  • 30. ARGUMENTSBUTNORETURN VALUES • Thefunction call value(500,0.12,5) Would send the value 500, 0.12, 5 to thefunction value(float p, float r, intn) and assign500 to p, 0.12 to r and 5 to n Thevalues 500, 0.12, 5 are the actualarguments Thearguments p, r, n are the formalarguments Theactual and formal arguments should matchin number, type, andorder Thevalues of actual arguments are assigned to the formal arguments on aone to onebasis • • • • • •
  • 31.
  • 32.
  • 33. ARGUMENTSBUTNORETURN VALUES • if the actual arguments are more than the formal arguments, the extra actual arguments arediscarded If the actual arguments are lessthan the formal arguments, the unmatched formal argumentsare initialized to some garbagevalues No error messagewill begenerated Theformal arguments must be valid variablenames Theactual arguments my be variable names, expression, or constants When afunction call is made, only acopy of the values of actual arguments is passedinto thecalled 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 Sumis:6
  • 35. ARGUMENTSWITHRETURNVALUES • • • Here data transfer take place between the calling function and the called function aswell asbetween 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 thecalling program. Aself-contained and independent function should behave like a‘black box’ that receives apredefined form of input and outputsadesired 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 Sumis:13
  • 38. RETURNINGFLOATVALUE • Cfunction returns avalue of the type int asadefault casewhen no other type is specifiedexplicitly. return(z); Return the integer value ofsum 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 prototypedeclaration • • • •
  • 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, inty) { float z; z=x+y/3; return(z); } OUTPUT : Enter two number:6 7 Sumis:13
  • 40. RETURNINGNON-INTEGERVALUE • The type-specifier tells the compiler, the type of data the function is toreturn Thecalled function mustbe declared at the start of the body in the callingfunction, like any other variable. This is to tell thecalling 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,floaty) { return(x*y); } double dic(float p, floatq) { return(p/q); }
  • 41. NOARGUMENTSBUTRETURNSA VALUE • There could be occasionswhere we may need adesign functions that may not take any argumentsbut returns avalue 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. FUNCTIONSRETURNINGNOTHING • Functions that do not return any values are not declaredin the main main() { printline(); value(); printline(); } printline() { .... } value() { .... } • We can also declare them in the main with the qualifier void • Thisstates explicitly that the functions do not return values main() { void printline(); void value(); void printline(); } void printline() { .... } void value() { .... }
  • 43. FUNCTIONSTHATRETURN MULTIPLEVALUES • • Areturn statement can return only onevalue. Toget more information from afunction, wecan achieve this in Cusing the arguments not only to receive information but also to send back information to the callingfunction. Thearguments that are used to “sendout” information are called outputparameters. Themechanism of sending back information through arguments is achieved using what are known asthe 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; } • • • xand y – input arguments sand d – output arguments We pass – Valueof – Valueof xto a y to b – Addressof – Addressof sto sum d to diff • Thebody of the function when executed add the value and find difference and store the result in memory location pointed by sumand diff.
  • 45. FUNCTIONSTHATRETURN MULTIPLEVALUES • The indirection operator * indicates the variables are to store addresses, not actual values of variables Theoperator * is known asindirection operator because it gives an indirect reference to avariable through itsaddress Thevariables *sum and *diff are known aspointers andsum and diff aspointer variables They are declared asint, they can point to locations of int type data Theuseof pointer variables asactual parameters for communicating data between functions is called “passby pointers” or “call by address orreference”. • • • •
  • 46. NESTINGOFFUNCTIONS • • Cpermits nesting of functionsfreely main can call function1, which calls function2,which calls function3, …..andsoon
  • 47.
  • 48. RECURSION • • • When acalled function in turncalls another function a process of ‘chaining’occurs Recursion is aspecial case,where afunction 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 Thisis 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 Thefactorial of 5! is120
  • 50. FUNCTIONSWITH1DARRAYS • • Possible to passthe values of an array toafunction To pass an array to a called function, it is sufficient to list the name of the array without any subscripts, and the sizeof the array asarguments The call: largest(a,n); will passall the elements contained in thearray aof size n. Thecalled function expecting this call mustbe appropriately defined Thelargest function headeris float largest(float array[], intsize) • • • •
  • 51. FUNCTIONSWITH1DARRAYS • Thefunction header(largest) is defined to take two arguments, the array name and the sizeof thearray to specify the number of elements in the array Thedeclaration of formal argument arrayis float array[]; Thepair of brackets informs the compiler thatthe arguments array is an array of numbers It is not necessary to specify the size of the array here • • •
  • 52. FUNCTIONSWITH1DARRAYS • Here an array is transferred asparameter to a function. void fun(int b[], intn) { int x,b[5]; … … … … . . … … … … . . void main() { void fun(int[],int); 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 theNumber: "); 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 Thesum is: 15
  • 54. FUNCTIONSWITH2DARRAYS • Canalso passmulti-dimensional arrays to functions. Therules are: – Thefunction must be called by passing only thearray name – In the function definition, we must indicate that the array hastwo-dimensional by including two sets ofbrackets – Thesizeof the second dimension must bespecified – Theprototype declaration should be similar tothe 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], intM,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. PASSINGSTRINGSTOFUNCTIONS • Thestrings are treated ascharacter arrays in Cand therefore the rules for passing strings to function are very similar to those for passingarrays to functions Basicrules are – Thestring to be passedmust be declared asaformal argument of the function when it is defined Example: voiddisplay(char item_name[]) { ... } •
  • 57. PASSINGSTRINGSTOFUNCTIONS – Thefunction prototype must show that the argument is a string voiddispay(char str[]); – Acall to the fuction must have astring arrayname without subscripts asits actual argument Example: display(names); Nameis aproperly declared string array in the callingfunction Like arrays, strings in Ccannot be passedby value to function •
  • 58. THESCOPE,VISIBILITYAND LIFETIMEOFVARIABLES • It is very important to understand the concept of storage classesand their utility in order to develop efficient multifunction programs In Cthere are four storageclasses – Automatic variables – External variables – Static variables – Register variables Here we discussthe scope, visibility and longevityof the above classof variables • •
  • 59. THESCOPEANDLIFETIMEOF VARIABLESINFUNCITONS • SCOPEOFVARIABLE – Determines over what parts of the program a variable is actually available for use(active) LONGEVITY – Refers to the period during whichavariable retains agiven value during execution of program(alive) – It has adirect effect on the utility of agiven variables VISIBILITY • • • The visibility refers to the accessibility of avariable from the memory • Variables are categorized depending on the place oftheir declaration – Internal (local) • Internal variables are those which are declared within aparticular function – External (global) • External variables are declared outside of anyfunction
  • 60. AUTOMATICVARIABLES • Automatic variables are declared inside afunction in which they are to beutilized Theyare created when the function is called and destroyed automatically when the function isexited, hence the nameautomatic Automatic variables are therefore private tothe function in which they aredeclared Automatic variables are also referred to aslocalor internal variables • • •
  • 61. AUTOMATICVARIABLES • Avariable declared inside afunction without storage classspecification is, by default, an automatic variable Thestorage classof the variable number isautomatic main() { int number; ....... } We may also usethe keyword auto to declareautomatic 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. AUTOMATICVARIABLES • There are two consequences of thescopeand longevity of autovariables Any variable local to main will normally live throughout the whole program, although itis active only in main. During recursion, the nested variables areunique auto variables • •
  • 65. EXTERNALVARIABLES • Variables that are both alive and activethroughout the entire program are known asexternalvariables Theyare also known asglobal variables Global variables can be accessedby any function in the program External variables are declared outside afunction • • •
  • 66. EXTERNALVARIABLES int number; float length =7.5; main) { ..... } function1() { ..... } function2() { ..... } • • Thevariables number and length are available for usein allthe three functions In casealocal variables and aglobal variable have the same name, the local variable will have precedence over theglobal one in the function where itis declared
  • 67. EXTERNALVARIABLES 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. EXTERNALVARIABLES • • • Onceavariable hasbeen declared asglobal, any function can useit and change itsvalue Then subsequent functions can reference only that newvalue 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; } Asfor asmain is concerned, y is not defined. So,thecompiler will issue an error message Global variables are initialized to zero bydefault Thestatement y =y +1 will assign1 to y. • • •
  • 71. EXTERNALDECLARATION • • Themain cannot accessthe variable y asit hasbeendeclared after the mainfunction Thisproblem can be solved by declaring the variable withthe storage classextern main() { extern int y; /* external declaration */ .... } func1() { extern int y; /* external declaration */ ..... } int y; /* definition */ Although the variable y hasbeen defined after boththe functions, the external declaration of y inside the function informs the compiler that y is an integer type defined somewhere else in the program Theextern declaration does not allocate storage spacefor variables • •
  • 72. EXTERNALDECLARATION 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 withinafunction provides the type information to just that onefunction We can provide type information to all functions within afile by placing external declaration before any ofthem
  • 73. EXTERNALDECLARATION • Thedistinction between definition anddeclaration also applies to functions Afunction is defined when its parameters andfunction body are specified Thistells the compiler to allocate spacefor the function code andprovides type information for the parameters Since functions are external by default, we declare them without the qualifierextern voidprint_out(); is equivalent to extern voidprint_out(); • • • • • extern float height[]; main() { int i; void print_out(void); .... print_out(); } void print_out(void) { int i; ...... } float height[SIZE];
  • 74. STATICVARIABLES • Thevalue of static variables persists until the end ofthe program Avariable can be declared static using the keyword static static int x; static float y; Astatic variable may be an internal or externaltype, depending on the place ofdeclaration • •
  • 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 xasan auto variable. The output would be X=1 X=1 X=1
  • 76. STATICVARIABLES Internal static variables • • • • Declared inside afunction 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 ofthe program Static variable is initialized only once, when theprogram is compiled. It is never initializedagain External static variables • Declared outside of all functions and is available to all the functions in thatprogram • Thedifference between astatic external variable and asimple external variable isthat: – the static external variable is available only within the file where it is defined while the simple external variable canbe accessedby otherfiles
  • 77. SCOPEOFFUNCTION • 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 classstatic
  • 78. REGISTERVARIABLES • • Register accessis much faster than amemory access We can make avariable to be placed in one ofthe machine register instead of memoryusing register int count; Most compiler allow int or char variables to be placed in the register ANSIstandard does not restrict to any particulardata type Cwill automatically convert register variablesinto non-register variables once the limit isreached • • •
  • 79.
  • 80. MULTIFILEPROGRAMS • 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 avariable declaredas 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 withextern in other file • • •
  • 81. USEOFEXTERNIN AMULTIFILE PROGRAM file1.c file2.c main() { extern int m; int i; .... } function1() { int j; .... } int m /* global variable */ function2() { int i; ..... } function3() { int count; ..... }
  • 82. USEOFEXTERNIN AMULTIFILE PROGRAM file1.c file2.c int m; /* global variable */ main() { int i; .... } function1() { int j; .... } extern int m; function2() { int i; .... } function3() { int count; ..... }
  • 83. MULTIFILEPROGRAMS • Theextern specifier tells the compiler that thefollowing variables types and names have already been declared elsewhere and no need to create storage spacefor them It is the responsibility of the linker to resolve the reference problem Afunction defined in one file and accessedinanother must include afunction declaration Thedeclaration identifies the function asanexternal function whose definition appearselsewhere We place suchdeclarations at the beginning of thefile, before all functions Although all functions are external, it would be good practice to explicitly declare suchfunctions withstorage classextern • • • • •
  • 84. TOFINDTHEMAXIMUM main() { float largest(float a[],intn); float value[4] ={2.5, -4.75, 1,2.3.6} printf("%fn", largest(value,4)); } float largest(float a[], intn) { int i; float max; max =a[0]; for(i=1;i<n;i++) if(max<a[i]) max =a[i]; return(max); }
  • 85. TOSORTANARRAYOFINTEGERS main() { int i; int marks[5] ={40, 90, 73, 81,35}; printf("Marks beforesortingn"); 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, intx[]) { 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. SWAPPINGNUMBERSUSINGCALL BYREFERENCE #include <stdio.h> void swap(int*, int*); int main() { int x,y; printf("Enter the value of xandyn"); 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. FIBONACCISERIESUSING 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(intn) { if ( n ==0) return 0; else if ( n ==1) return 1; else return ( Fibonacci(n-1)+ Fibonacci(n-2) ); }