FUNCTIONS
Function
✔ “Function is a small program or program segment that carryout some specific
well-defined tasks”.
Advantages of Functions
i. Reduces the Complexity.
✔ When a program contains more number of instructions (complex program), then such large
program can be divided into number of sub programs called as functions.
ii. Improves the Readability.
iii. Easy to debug the errors.
iv. Reusability: The set of instructions specifying the task performed by the function is written just
once but it can be used any number of times.
v. Easy to do the modifications.
Types of Functions
i. Library Functions/Pre-Defined/ Built-in Functions
✔ C Library of C Compiler has a collection of various functions which perform some standard
and pre-defined tasks.
✔ These functions written by designers of C Compilers are called as Library
functions/Pre-Defined/Built-in functions.
Ex:sqrt(n)- computes square root of n.
pow(x,y)- computes x .y
printf()- used to print the data on the screen.
scanf()- used to read the data from the keyboard.
abs(x)- computes absolute value of x.
ii. User-Defined/ Programmer Defined Functions
✔ The functions written by the programmer/user to do the specific tasks is called User-Defined/
Programmer Defined Functions.
✔ main( ) is the user defined function.
Elements of User-Defined Functions
✔ The three elements of user-defined functions are shown below:
i. Function Prototype/Declaration
ii. Function Definition
iii. Function Call
Function Prototype/Declaration
✔ As we normally declare the variables before they are used, the functions also should be
declared before they are used.
✔ The process of declaring the functions before they are used (or called) in the program is
called Function Prototype.
✔ The function prototype is also called as Function declaration.
✔ It is same as the Function Header but terminated with semicolon.
✔ It does not contain the body of the function.
Syntax
return_data_type function _name(data_type variable1, data_type variable2, . . . );
Where return_data_type: This is the data type of the value that the function is expected to
return (int, float, double, char).
function_name: It is the name of the function. It can be any valid Identifier.
data_type variable1, data_type variable2, . . . is a list of variables of specified data types they are
also known as parameters
Example: int add(int a, char b);
Function Definition
✔ The program module that is written to achieve a specific task is called function
definition.
✔ Each function definition consists of two parts:
Function Header
Function Body
Syntax:
return_data_type function _name(data_type variable1, data_type variable2, . . . )
{
declaration part;
executable part;
return statement;
}
Function header
return_type: This is the data type of the value that the function is expected to return (int, float,
double, char).
function_name: It is the name of the function. It can be any valid Identifier.
data_type variable1, data_type variable2, . . . is a list of variables of specified data types they are
also known as parameters.
Function Body
Declaration part: All the variables used in the function body should be declared in this part.
Executable par: This part contains the statements or instructions that perform the specified activity.
return statement: It is a keyword used to return the control to the calling function (main)
with/without a value.
Ex: int add(int a,int b)
{
int sum; //variable declaration
sum=a+b; //executable statement
return sum; //return statement
}
Function Call
✔ Once the function is defined, it has to be called so as to achieve the task. This method of
calling a function to achieve a specified task is called Function Call.
✔ The function can be called by writing the name of the function and passing the appropriate
number of arguments.
✔ The number of arguments in the function call and number of parameters in the function
definition must match.
✔ Also the order of arguments in the function call and parameters in the function definition
must match.
Syntax:
Function_name(variable1, variable2, . . . .);
Example: add(m,n);
Example Program: Write a C program to perform the addition of two numbers using function
#include<stdio.h>
int add(int a,int b); /*Function Prototype*/
int add(int a,int b)
{
int sum;
sum=a+b;
return sum;
}
void main()
{
int result;
result=add(10,20);
printf(“sum=%d\n”,result);
}
✔ The ‘main()’ is always the “Calling Function”.
✔ The ‘add()’ function is called “Called Function”.
Function Parameters
“The list of variables defined in the function header within the parenthesis are called
Function parameters”.
✔ There are 2 types of parameters in ‘C’ functions.
i. Actual parameters
ii. Formal parameters
i. Actual or Real Parameters
✔ The variables that are used when a function is invoked are called actual parameters.
✔ Actual parameters are used in the Calling function when a function is invoked.
✔ Actual parameters send values or addresses to the formal parameters. Formal parameters
receive them and use the same values.
✔ Actual parameters can be constants, variables or expressions.
Ex: res = add (m, n);
ii. Formal or Dummy Parameters
✔ The variables defined in the function header or function definition are called formal
parameters.
✔ All the variables should be separately declared and each declaration must be separated by
commas.
✔ The formal parameters receive values form the actual parameters.
✔ If the formal parameters receive the address from the actual parameters, then they should be
declared as pointers.
✔ The formal parameters should be only variables. Expressions and constants are not allowed.
Ex: int add(int a,int b);
Example Program: C Program to define actual and formal parameters.
#include<stdio.h>
int add(int a,int b) // Formal Parameters a, b
{
int sum;
sum=a+b;
return sum;
}
void main()
{
int m,n,res;
printf(“Enter the values for m,n\n”);
scanf(“%d%d”,&m,&n);
res=add(m,n); // Actual parameters m,n
printf(“Sum=%d\n”,res);
}
Location of Functions
✔ The placement of the function definition in relation to the main program is very important.
✔ There are a number of ways to arrange the main program and a function.
i. Functions immediately after #includes and #defines
✔ In this method, we can place the entire the function definition consisting of the function
header and function body in the beginning of the file immediately after #includes and #defines if
any.
Syntax:
ii. Functions after main
✔ In this method, immediately after #includes and #defines, we write all function prototypes.
✔ Next, we write the main function that is followed by the function definitions.
iii. Functions in Separate files (Separate Compilation)
✔ In this method, immediately after #includes and #defines we write all function prototypes.
✔ Next, we write the main function.
✔ All user function definitions will be in separate files.
✔ It puts the function in one file and the main program in another and compiles them separately.
Syntax: file method3.c file method4.c
separate file
Categories of Functions
✔ Based on the parameters and return value, the functions have been classified into four categories.
1. void and parameter less functions (Functions with no parameters and no return values)
2. non void and parameter less functions(Functions with no parameters and return values)
3. void with parameters functions (Functions with parameters and no return values)
4. non void with parameters functions (Functions with parameters and return values)
1. void and parameter less functions (Functions with no parameters and no return values)
✔ In this category there is no data transfer between the calling function and the called function.
✔ So calling function cannot send values and hence called function cannot receive the data and
it will not send any parameter back to function.
Example: Program showing function call with no parameters and returns no value.
2. non void and parameter less functions (Functions with no parameters and return values)
✔ In this category there is no data transfer from the calling function and the called function.
✔ But, there is data transfer from the called function to the calling function.
✔ When the function returns a value, the calling function receives one value from the called
function.
✔ We can write a function that has no parameters but returns an answer to the main program as
shown in the syntax.
Example: Program showing function call without parameters, with return value.
3. void with parameters functions (Functions with parameters and no return values)
✔ In this category, there is a data transfer from the calling function to the called function using
parameters.
✔ But, there is no data transfer from the called function to the calling function
Example: Program showing a function call with parameters and no return value.
4. non void with parameters functions (Functions with parameters and return values)
✔ In this category, there is data transfer between the calling function and the called function.
✔ When parameters are passed, the called function can receive values from the calling function.
✔ When the function returns a value, the calling function can receive a value from the called
function.
Example: Program showing a function call with parameters and with returns
value.
Argument Passing or Parameter Passing Methods
✔ There are mainly two parameter passing mechanisms in ‘C’ functions. They are:
i. Call by Value or Pass by Value
ii. Call by Address or Pass by Address
i. Call by Value or Pass by Value
✔ Calling (Invoking) a function by passing values or variables to the function is called as
call by value.
✔ The values of actual parameters are copied into formal parameters.
✔ Formal parameters contain only the copy of actual parameters. So, even if the values of the
formal parameters changes in the called function, the values of the actual parameters are not
changed.
Example Program:
#include<stdio.h>
void fun(int,int);
void main()
{
int x=5,y=7;
fun(x,y);
printf(“x=%d y=%d”,x,y);
}
void fun(int x, int y)
{
x=7;
y=5;
printf(“x=%d y=%d\n”,x,y);
}
Output
x=7 y=5
x=5 y=7
ii. Call by Reference or Pass by Address
✔ Call by reference is done indirectly by passing the address of the variables in the function
call and changing the value of the variable through its address.
✔ In the called function, the formal parameters should be declared as pointers with the same
type as the actual parameters.
✔ The addresses of actual parameters are copied into formal parameters. Using these addresses
the values of the actual parameters can be changed.
✔ In call by reference if any change in formal parameters imply then there is a change in
actual parameters.
Example Program:
#include<stdio.h>
void fun(int *,int *);
void main()
{
int x=5,y=7;
fun(&x,&y);
printf(“x=%d y=%d”,x,y);
}
void fun(int *x, int *y)
{
*x=7;
*y=5;
printf(“x=%d y=%d\n”,*x,*y);
}
Output
x=7 y=5
x=7 y=5
Write a C program to swapping of 2 numbers using call by reference and call by value.
#include<stdio.h>
void swap_value(int, int);
void swap_reference(int *, int *);
void main()
{
int a=1, b=2, c=3, d=4;
printf(“\n in main(), a=%d and b=%d”, a,b);
swap_value(a,b);
printf(“\n in main(), a=%d and b=%d”, a,b);
printf(“\n in main(), c=%d and d=%d”, c,d);
swap_reference(&c,&d);
printf(“\n in main(), c=%d and d=%d”, c,d);
}
void swap_value(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf(“\n in function, a=%d and b=%d”, a,b);
}
void swap_reference(int *c, int *d)
{
int temp;
temp=*c;
*c=*d;
*d=temp;
printf(“\n in function, c=%d and d=%d”,*c,*d);
}
Using Arrays with Functions
The arrays can be passed to functions using two methods:
i. Passing individual elements of the array
ii. Passing the whole array
Pass individual elements of array as parameter Pass complete array as parameter
Here, each individual element of array is passed to Here, the complete array is passed to the function.
function separately.
Example: Example:
#include<stdio.h> #include<stdio.h>
int square(int); int sum(int [ ]);
int main( ) int main( )
{ {
int num[5], i; int marks[5], i;
num[5] ={1, 2, 3, 4, 5}; marks[5] ={10, 20, 30, 40, 50};
for(i=0; i<5; i++) sum(marks);
{ }
square(num[i]); int sum(int n[ ])
} {
} int i, sum=0;
int square(int n) for(i=0; i<5; i+
{ +)
int sq; {
sq= n * sum = sum+n[i];
n; }
printf(“%d ”, sq); printf(“Sum = %d ”, sum);
} }
Recursion
✔ “The process in which a function calls itself again and again is called as Recursion”.
✔ A function which calls itself again and again is called as Recursive function.
✔ While using recursion, user need to be careful to define exit condition from function; otherwise
it will go in infinite loop.
✔ Recursive functions are very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.
Syntax:
Ex: Recursive definition of factorial is
Fact(n)= 1 if n=0 base case
n*fact(n-1) if n>0 general case
Limitations of Recursion
Recursive solutions may involve extensive overhead because they use function calls.
Each time you make a call, you use up some of your memory allocation. If
recursion is deep, then you may run out of memory.
Example: Program to calculate factorial of a given number using recursion.
#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
void main()
{
int n,fact;
printf(“Enter a number=”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“\nFactorial of given number=%d”,fact);
}