MODULE 3 -
FUNCTIONS
INTRODUCTION
• Functions are program segments which perform a definite, well-
defined task.
• A function which calls other functions is referred as “CALLING
FUNCTION” and the function being called is referred as “CALLED
FUNCTION”
•When complier executes a function call
• Control jumps to statements that are part of called function.
• After completion, control returns back to calling function.
•Function
void
call can
2
be placed
fnt1() within fnt2()
a for-loop, while-loop etc., To
4 {:
call amain()
function multiple times.
{ :3
: :
{ :1 5
fnt2(); :
: 7 : 6 :
9 fnt1();
8 return; return;
:
} }
}
ADVANTAGES OF USING
FUNCTIONS
• It helps to build a separate, well-defined programs/sub-procedures to be
written and tested separately.
• Understanding, coding and testing becomes easier.
• Large programs can be divided and makes it easier to program.
• All libraries in C has inbuilt functions that can be used in other programs.
• When a big program is divided into comparatively smaller functions, then
different programmers working on project can divide work load.
• User can write their functions and can use them at different points in
program.
• Any function can be seen as black box.
Function
input output
TERMINOLOGY
• A function, f, that calls another function, g, is called “Calling
function” and function g is called “Called function”.
• Inputs to function are called arguments or parameters.
• When called function returns some result back to calling
function, it is said to RETURN that result.
• Calling function may or may not pass parameters to called
function.
• Function declaration is a statement that identifies a function
with its name, a list of arguments that it accepts and type of data
it returns.
• Function definition consists of a function header that identifies
the function, followed by the body of the function containing
executable code for that function.
ELEMENTS OF USER DEFINED FUNCTIONS
• Function declaration or Function prototype
• Function definition
• Function call
• Function declaration or Function prototype
•It provides the prototype of the function to the compiler. i.e. it
identifies function name, return data type or function type,
parameter or argument list, termination semicolon. The syntax
is:
return_data_type fnt_name(data_type of
parameters);
Eg. int sum(int a, float y); [or] int sum(int, float);
• If a function does not return any thing, it is called as void
function.
Eg. void fun_name(void);
FUNCTION DECLARATION / PROTOTYPE
•Important Points:
• Function declaration is global, i.e. it should be declared
before main() and can be called by any other function.
• After declaration of a function, there should be a semicolon.
• Use of arguments / parameters in the function declaration is
optional. But data type of arguments is must.
• Function cannot be declared within the body of another
function
• A function having void as its return type cannot return any
value.
• A function having void as its parameter list cannot accept
any value.
• If function declaration does not specify any return type, then
by default the function returns an integer value.
• Some compilers allows to use a function without prototype
• Syntax of function declaration is:
return_Data_Type fnt_name(datatype var1,
datatype var2……);
Eg. To find average of 3 real numbers:
a) If inputs are sent from calling function
float avgfnt(float, float, float);
b) If inputs are not sent from calling function
float avgfnt();
FUNCTION DEFINITION
• When a function is defined, space is allocated for that
function in memory.
• A function definition has 2 parts:
• A) Function header
• B) Function body
• Syntax of function definition is:
return_Data_Type fnt_name(datatype var1,
datatype var2……)
{ local variables;
executable statements; This line is
return(variable); called
} Function
header
FUNCTION DEFINITION
• Number of arguments and the order of arguments in function header
must be same as that given in Function Declaration or prototype
statement
• The list of variables in the function header of function definition is
referred to as FORMAL PARAMETER LIST. [In eg. var1, var2… are
formal parameters list]
• Parameter list can be ZERO or any no. of items depending on the
function declaration.
Eg. float avg(int x, int y, int z) function header
{ float res; local declaration
res=(x+y+z)/3.0; Executable
statement
return(res); return value
}
Explanation: a) x,y,z are formal variable list. b) res is local
FUNCTION CALL
• It invokes the required function.
• When a function is invoked or called, the control jumps to the called
function to execute the body of the called function.
• Once the called function is executed, program control transfers back to
calling function.
• Syntax to call a function is: fnt_name(var1,var2,….); -------if
function does not return
(or)
var = fnt_name(var1,var…….); ----------if function
returns a value
• var1, var2… are called as actual parameters.
• When a function is called, the actual parameters are copied into formal
parameters. The return value is assigned to var
• In case of inbuilt function, corresponding header file is to be included
POINTS TO NOTE WHILE
CALLING A FUNCTION
• In case of multiple parameters or arguments, it should be separated by a comma.
• Function name, no. of arguments and type of arguments in function call must be
same as that given in function declaration and function header of function definition.
• If parameters passed to a function are more that what is specified, then
extra arguments will be discarded.
Eg. Fnt call: fnt1(x,y,z); Fnt definition: fnt1(int a, int b)
The parameter z will be ignored.
• If parameters passed to a function are less that what is specified to accept
then the unmatched arguments will be initialized to some garbage value.
Some compilers may give compilation error.
Eg. Fnt call: fnt1(x,y); Fnt definition: fnt1(int a, int b, int c)
The parameter c will be initialized with garbage value.
• Name of variable in function declaration, function call and header of function
definition may vary.
EXAMPLES- FUNCTION TO
PRINT A LINE
#include<stdio.h>
void printline(); -------------------------- function
declaration/prototype
void main()
{ printline(); ---------------------------------- function call
printf(“\n Ex. For use of function \n”);
printline(); ----------------------------------- function call
}
void printline()
{ int i;
for(i=1;i<60;i++) ------------- function
definition
printf(“-”); Output:
-------------------------------------------------------
printf(“\n”);
---------------
} Ex. For use of function
-------------------------------------------------------
CATEGORY OF FUNCTIONS
• Category 1: Function with no arguments and no return value.
void fnt(void);
• Category 2: Function with arguments and no return value.
void fnt(var1, var2..)
• Category 3: Function with arguments and one return value.
return_Data_type fnt(var1, var2…)
• Category 4: Function with no arguments but returns a value
return_data_type fnt(void)
• Category 5: Function that return multiple values
CATEGORY 1: FUNCTION WITH NO
ARGUMENTS AND NO RETURN VALUE
• In this case there is no parameter sent to the called function from the
calling function and
there is no value returned to calling function from the called function.
• Hence the function is declared as void function.
eg void fnt_name(void) or void fnt_name()
• Consider the function to find average of 3 numbers
Fnt declaration or prototype: void avg(void);
Fnt definition: void avg()
{ int a,b,c; float res;
scanf(“%d%d%d”,&a,&b,&c);
res = (a+b+c)/3.0;
printf(“Average = %f \n”, res);
}
CATEGORY 1: EXAMPLE TO FIND AVG OF 3 NOS.
#include<stdio.h>
void avg();
void main()
{ avg();
}
void avg()
{ int a,b,c; float res;
printf(“Enter 3 numbers :
“);
scanf(“%d%d
%d”,&a,&b,&c);
res=(a+b+c)/3.0;
printf(“Average = %f”, res);
CATEGORY 2: FUNCTION WITH
ARGUMENTS AND NO RETURN VALUE
• In this case the called function receives certain inputs from calling
function. Hence in the function header of function declaration and
function definition, the data type of parameters to be passed has to be
mentioned.
•While calling the function, the parameter list should have the actual
variables. The actual variables will be copied into the formal variables
in the function definition header.
•Eg. void fnt(int, int); void fnt(int x, int y)
void main() { :
{ int a=4,b=5;Explanation:
}
fnt(a,b); 1. a,b are the actual parameters.
:
2. x,y are the formal parameters.
3. When fnt is called, value of a and b is copied
} into x and y
CATEGORY 2: EXAMPLE TO FIND AVG OF 3 NOS.
#include<stdio.h>
LOCATION VALUE
void avg(int, int, int); a
void main() b
{ int a,b,c; c
printf(“Enter 3 numbers : “);
scanf(%d%d%d”,&a, &b, &c);
avg(a, b, c);
}
void avg(int X, int Y, int Z) LOCATION VALUE
X
{ float res;
Y
res=(X + Y + Z)/3.0; Z
printf(“Average = %f”, res); res
}
CATEGORY 3: FUNCTION WITH
ARGUMENTS AND ONE RETURN VALUE
• In this case the called function receives certain inputs from calling function.
•The function after completing execution returns a value to the calling function.
• Hence in the function header of function declaration and function definition, the
data type of parameters to be passed has to be mentioned and return data type to
be mentioned.
•While calling the function, the parameter list should have the actual variables. The
actual variables will be copied into the formal variables in the function definition
header.
•Eg. int fnt(int, int); int fnt(int x, int y)
void main() { int p;
{ int c, a=4,b=5; :
c=fnt(a,b); return(p);
: }
}
CATEGORY 3: EXAMPLE TO FIND AVG OF 3 NOS.
#include<stdio.h>
LOCATION VALUE
float avg(int,int,int); a
void main() b
{ int a,b,c; float ans; c
printf(“Enter 3 numbers : “); ans
scanf(%d%d%d”,&a, &b, &c);
ans = avg(a, b, c);
printf(“Average = %f”, ans);
} LOCATION VALUE
float avg(int x, int y, int z) X
{ float res; Y
Z
res=(x+y+z)/3.0;
res
return(res);
}
EX: WRITE A PROGRAM USING
FUNCTIONS TO FIND NPR
#include<stdio.h> int factfnt(int x)
int factfnt(int); { int i, fact=1;
void main()
for(i=1;i<=x;i++)
{ int n, r, res;
fact = fact * i;
printf(“Enter value of n and r :
“); return(fact);
scanf(“%d%d”, &n, &r); }
res=factfnt(n) / factfnt(n-r); Output:
printf(“The result : %d\n”,res);
Enter value of n and r: 5 2
}
The result : 20
FIND THE ERRORS IN THE
FOLLOWING
A) void abc(int a, int b) B) int abc(int a, int b) c) int abc(int a,
int b)
{ int c; { : { double c;
: : c=a+b;
: } return(c);
return(c); }
} Ans: with int
A function Ans:with int return type should
A function
return type should have return of int datatype. But in
AAns:
function with void have return the example the return datatype is
return type should statement double.
not have return
statement
FIND THE OUTPUT IN THE
FOLLOWING
A) #include<stdio.h> B) #include<stdio.h>
void fnt(char); int add(int, int);
void main() void main()
{ char ch=66; { int a=2.b=3;
fnt(ch); printf(“%d %d %d\n”,a, b, add(a,b));
} }
void fnt(char x) int add(int a, int b)
{ printf(“%d”,x); { int c;
} c=a+b; return(c);
Ans: _________ } ANS:
___________
WRITE A FUNCTION TO FIND GCD OF
2 NUMBERS AND USE THE FUNCTION
TO FIND GCD OF 4 NUMBERS;
The function for Function declaration: int gcd(int , int);
GCD will be a Function definition:
category 3
function that int gcd(int x, int y)
takes 2 inputs { while(x != y)
from calling { if(x>y)
function and x=x-y;
returns the GCD else
of two numbers
to the calling y=y-x;
function }
return(x);
}
COMPLETE PROGRAM…
#include<stdio.h>
int gcd(int, int);
int gcd(int x, int y)
void main() { while(x != y)
{ int a,b,c,d,res; { if(x>y)
printf(“Enter 4 numbers : “); x=x-y;
else
scanf(“%d%d%d%d”,&a,&b,&c,&d); y=y-x;
res=gcd(a,b); }
res=gcd(res,c); return(x);
}
res=gcd(res,d);
printf(“The GCD of 4 numbers is : %d\n”,res);
}
SCOPE, VISIBILITY AND LIFETIME OF VARIABLES
• Various storage classes of variables in C are:
• Local variables or Automatic variables
• Global variables or external variables
• Static
• Register
•Local variables or Automatic variables
• If a variable is declared within a block then as soon as
control exits that block, the variable will cease to exist.
• Such variables are called LOCAL Variables or Automatic
variables.
• The scope and visibility of local variables is only within the
block where it is defined.
• A local variable is unknown to rest of the program.
LOCAL VARIABLES
• Storage class is automatic and key word to define is auto. Eg. auto int
x;
But by default any variable defined in a block is auto storage class
Eg. #include<stdio.h> void fnt1()
void fnt1(); { int x=100;
void fnt2(); printf(“X=%d in fnt1”,x);
void main() fnt2();
{ int x=10; }
printf(“X=%d in main \n”,x); void fnt2()
fnt1(); { int x=1000;
} printf(“x=%d in fnt2”,x);
}
GLOBAL VARIABLES OR EXTERNAL VARIABLES
• These are active throughout the program.
• It can be accessed by any function in the program.
• It is normally declared after pre-processor directives.
• eg. #include<stdio.h>
Variable n and x is
int n; float x=10.5;
available to be used and
void main() modified by any function
{ : in the program.
:
}
• If a name of local variable is same as global variable then,
precedence is that function will be to local variables.
GLOBAL VARIABLES
int fnt1()
#include<stdio.h>
{ x=x+10;
int fnt1();
}
int fnt2();
int fnt2()
int x;
{ x=x-5;
void main()
}
{ x=10;
printf(“X=%d in main\n”,x);
Output:
printf(“X=%d after fnt1()\
n”,fnt1()); X=10 in main
printf(“X=%d after fnt2() \ X=20 after fnt1()
n”,fnt2());
X=15 after fnt2()
}
GLOBAL VARIABLES AS PARAMETERS FOR FUNCTIONS
• Since all functions can access global variables, they can be used for
passing values between functions.
• Few issues whiles using global variables for passing values are:
• Values of global variables which are sent to called function may be
changed by called function.
• The characteristics of function that it is a independent module is lost by
use of global variables.
• It is not clearly seen to user which value are being sent to called
function.
• A function that uses global variables suffers from reusability.
• extern data class can be used to indicate a variable that will be
used as global variable by functions thatvariable
The define them.
y is now
main() fnt1() globally accessable by
functions main and
{ extern int y; { extern int y;
fnt1() without passing
: : as arguments
} }
WRITE A FUNCTION TO EXCHANGE 2
VALUES. USE IT IN MAIN FUNCTION
AND ILLUSTRATE
Function to exchange 2 values. Consider category 1 function
and global variables.
void xchg()
{ int temp;
temp=a;
a=b;
b=temp;
}
WRITE A FUNCTION TO EXCHANGE 2
VALUES. USE IT IN MAIN FUNCTION
AND ILLUSTRATE
Complete program is given below:
#include<stdio.h> void xchg()
int a,b; { int temp;
temp=a;
void main() a=b;
{ a=4;b=5; b=temp;
}
printf(“a=%d, b=%d before fnt\n”,a,b);
xchg();
printf(“a=%d, b=%d after fnt\n”,a,b);
}
RECURSIONS
• It is a concept wherein a function calls itself.
• A recursive function should have a well defined termination
condition.
• It can be effectively used to solve problems wherein solution
is expressed in terms of successively applying the same
solution to subsets of the problem.
•A recursive function should have a if statement indicating a
termination condition and a return value.
Eg. n=4
•Eg. Factorial of number. • n!1st=iteration:
n x (n-1) x return(4
(n-2) x ….. X2x1
* fact(3))
int fact(int n) • 2nd iteration: return(4 * 3 * fact(2))
{ int res;
• 3rd iteration: return(4 * 3 * 2 *
if(n==1)
fact(1))
return(1);
• 4th iteration: return(4 * 3 * 2 * 1)
else
COMPLETE PROGRAM
#include<stdio.h>
int fact(int);
int fact(int n)
void main()
{ int res;
{ int n;
if(n==1)
printf(“Enter a number : “); return(1);
scanf(“%d”,&n); else
printf(“The factorial of %d is %d\n”, n, fact(n));
} return(n*fact(n-1));
}
RECURSIONS – FIBO SERIES 1,1,2,3,5,8,13,21….
• Logic: nth term of fibonacii series is given as Fibo(n) =
Fibo(n-1) + Fibo(n-2)
int fibo(int n)
{ if((n==1||(n==2))
return(1);
else
return(fibo(n-1)+fibo(n-2));
}
Eg. n=5
• 1st iteration: fibo(4) + fibo(3)
• 2nd iteration: fibo(3) + fibo(2) + fibo(2) + fibo(1)
• 3rd iteration: fibo(2) + fibo(1) + fibo(2) + fibo(2) + fibo(1)
Therefore the return value = 1 + 1 + 1 + 1 + 1 = 5
RECURSIONS-FIBO SERIES (COMPLETE PROGRAM)
#include<stdio.h>
int fibo(int);
void main()
{ int i,n; int fibo(int n)
printf(“Enter a number : “); { if((n==1||(n==2))
scanf(“%d”,&n); return(1);
printf(“The series upto %d terms is\n”,n); else
for(i=1;i<=n;i++) return(fibo(n-
1)+fibo(n-2));
printf(“%d “,fibo(i));
}
printf(“\n”);
}
RECURSIONS – GCD OF 2 NUMBERS
int gcd(int a, int b)
{ if(a==b)
return(a);
else
if(a>b) Eg. a=12, b=18
return(gcd(a-b,b)); • 1st iteration: gcd(12,6)
else • 2nd iteration: gcd(6,6)
• 3rd iteration: returns 6 as answer
return(gcd(a,b-a));
}
RECURSIONS-GCD (COMPLETE PROGRAM)
#include<stdio.h>
int gcd(int a, int b)
int gcd(int,int);
{ if(a==b)
void main()
return(a);
{ int b,a;
else
printf(“Enter two numbers : “);
if(a>b)
scanf(“%d%d”,&a, &b);
return(gcd(a-
printf(“GCD = %d \n”, gcd(a,b)); b,b));
} else
return(gcd(a,b-
a));
}
End of module 3