C Programming Unit-5 User Defined Functions
C Programming Unit-5 User Defined Functions
INTRODUCTION
One of the strength of C functions are easy to define and use. C functions can be
classified into two categories, namely, Library ( Not required to be written by us ) and
User-Defined (developed by the user at the time of writing a program) functions. main is
an example of user-defined functions. printf and scanf belong to the category of library
functions. However, a user-defined function can later become a part of the C program
library. In fact, this is one of the strength of C language.
Page 1 of 26
The “division” approach clearly results in a number of advantages.
1. It facilitates top-down modular programming style. In this, the high-level logic of
the overall problem is solved first. While the details of each lower-level functions
are addressed later.
2. The length of a source program can be reduced by using functions at appropriate
places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs. This means that a C
programmer can build on what have others have already done, instead of starting
allover again from scratch.
Page 2 of 26
The main functions calls the user-defined printline function two times and the library
function printf once. We may notice that the printline function itself calls the library
function printf 39 times repeatedly. Any function can call any other function. In fact, it
can call itself. A ‘called function’ can also call another function. A function can be
called more than once. In fact, this is one the main features of using functions.
Except the starting point, there are no other pre-determined relationships, rules of
precedence or hierarchies among the functions that make up a complete program. The
functions can be placed in any order. A called function can be placed either before or
after the calling function. However it is the usual practice to put all the called functions
at the end (Modular programming).
Modular Programming
Page 3 of 26
Modular Programming is a strategy applied to the design and development of Software
systems. It is defined as organizing a large program into small, independent programs
segments called modules that are separately named and individually callable program
units. These modules are carefully integrated to become a software system that satisfies
the system requirements. It is basically a “Divide-and-Conquer” approach to problem
solving. In C, each module refers to a function that is responsible for a single task.
Characteristics of modular programming:
● Each module should do only one thing.
● Communication between modules is allowed only by a calling module.
● A module can be called by one and only one higher module.
● No communication can take place directly between modules that do not have
calling-called relationship.
● All modules are designed as single-entry, single-exit systems using control
structures.
In order to make use of a user-defined function, we need to establish three elements that
are related to functions.
1. Function Definition: An independent program module, specially written to
implement the requirements of the function.
2. Function Call: Used to invoke function at a required place in the program.
3. Function Declaration / Prototype: Like declaration of a variable, function should
be declared to use later in the program.
Page 4 of 26
Definitions of Functions:
It is also known as Function Implementation, include the following elements,
● Function Name
● Function Type Function Header
● List of Parameters
● Local Variable Declarations
● Function Statements Function Body
● A return Statement
All the six elements are mainly grouped into two parts, namely,
Function Header ( The First Three Elements ) &
Function Body ( The Second Three Elements )
The general format of a function definition to implement above two parts is given below:
Page 5 of 26
The first line function_type function_name( parameter list ) is known as the Function
Header and the statements within the opening and closing braces constitute the function
body, which is compound statement.
Page 6 of 26
Remember, there is no semicolon after the closing parenthesis and the declaration of
parameter variables cannot be combined. Example: int sum ( int a, b ) is illegal.
A function need not always receive values from the calling program, in such cases,
functions have no formal parameters, and then we use void between the parentheses as in
void printline (void) or void printline ( )
{
.....
.....
}
This function neither receives any input values nor returns back nay value. It is a good
programming style to use void to indicate a null parameter list.
NOTE
● When a function reaches its return statement, the control is transferred back to the
calling program. In the absence of a return statement, the closing brace acts as a
void return.
● A local Variable is a variable that is defined inside a function and used without
having any role in the communication between functions.
Page 7 of 26
Return Values and Their Types:
A function may or may not send back any value to the calling function. If it does, it is
done through the return statement. It is possible to pass to the called function any
number of values; the called function can only return one value per call, at the most.
The return statement can take one of the following forms
return; /* ‘plain’ return does not return any value, the control is immediately
passed back to the calling function when a return is encountered. */
Example: if(error)
return;
return(expression); /* returns the value of the expression */
Example: int add(int a, int b)
{
return(a+b);
}
All functions by default return int type data. One can force a function to return a
particular type of data by using a type specifier in the function header. When a value is
returned, it is automatically cast to the function’s type. For instance, the function
int product (void)
{
return ( 2.5 * 3.0 ) ;
}
will return the value 7, only the integer part of the result. The return value will be
truncated to an integer.
Function Calls:
A function can be called by simply using the function name followed by a list of actual
parameters or arguments, if any enclosed in parentheses.
Example: main()
{
int y;
y = mul(10,5); /* Function Call */
printf(“%d\n”,y);
}
When the compiler encounters a function call, the control is transferred to the function
mul(). This function is then executed line by line as described and a value is returned
when a return statement is encountered. This value is assigned to y.
Page 8 of 26
The function call sends two integer values 10 & 5 to the function.
int mul(int x, int y) which are to x = 10 and y = 5 respectively. The function computes
the product x and y , assigns the result to the local variable p, and then returns value 25 to
the main where it is assigned to y .
There are different ways to call a function. mul() function can be invoked:
mul(10,5)
mul(m,5)
mul(10,n)
mul(m,n)
mul(m+5,10)
mul(10,mul(m,n)) /* uses its own call as its one of the parameter */
mul(expresssion1 ,expression2) /*expression should be evaluated to single
values that can be passed as actual parameters. */
A function which returns a value can be used in expression like any other variable.
Example:
printf(“%d\n”, mul(p,q));
y = mul(p,q) / ( p+q) ;
if (mul(m,n) > total )
printf(“%d”, max );
A function cannot be used as mul(a,b) = 15 ; is invalid.
A function that does not return any value may not be used in expressions, but can be
called in to perform certain tasks specified in the function.
Example: main()
{
printline(); /* Note that the presence of a semicolon at the end */
}
Function Call
Page 9 of 26
A function call is a postfix expression. When a function call is used as a part of an
expression, it will be evaluated first, unless parentheses are used to change the order of
precedence. In a function call, the function name is the operand and the parentheses set
(..) which contains the actual parameters is the operand. The actual parameters must
match the function’s formal parameters in type, order and number. Multiple actual
parameters must be separated by commas.
Note:
1. If the actual parameters are more than the formal parameters, the extra actual
arguments will be discarded.
2. If actual parameters are less than the formal parameters, the unmatched formal
arguments will be initialized to some garbage.
3. Any mismatch I data types may also result in some garbage values.
When a function does not take any parameters and does not return any value, its
prototype is written as: void function_name (void) ;
A prototype declaration may be placed in two places:
Page 10 of 26
1. Above all the functions ( including main() ) ; /* In the global declaration section,
referred as a global prototype , available for all function in the program. */
2. Inside a function definition ; /* in the local declaration section, referred as a local
prototype , are used by the functions containing them */
The place of declaration of a function defines a region in a program in which the function
may be function may be used by other functions. This region is known as the scope of the
function. It is good programming style to declare prototypes in the global declaration
section before main(). It adds flexibility, provides an excellent quick reference to the
functions used in the program, and enhances documentation (readability).
Category of Functions:
A function, depending on whether arguments are present or not and whether a value is
returned or not, may belong to one of the following categories:
Category-1: Functions with no arguments and no return values.
Category-2: Functions with arguments and no return values.
Category-3: Functions with arguments and one return value.
Category-4: Functions with no arguments and but return a value.
Category-5: Functions that return multiple values.
Page 11 of 26
from the called function. In effect, there is no data transfer between the calling function
and the called function. This indicates that there is only a transfer of control but no data.
The actual and formal arguments should match in number, type and order. The values of
actual arguments are assigned to the formal arguments on a one to one basis, staring with
the first arguments.
Page 12 of 26
Figure: Arguments matching between the function call and the called function
Ensure that the function call has matching arguments. In case, the actual arguments are
more than the formal arguments ( an > An ), the extra actual arguments are discarded. On
the other hand, If the actual arguments are less than the formal arguments, the unmatched
formal arguments are initialized to some garbage values. Any mismatch in data type may
also result in passing of garbage values without generating the error message.
Remember that, when a function call is made, only a copy of the values of actual
arguments is passed into the called function. What occurs inside the function will have
no effect on the variables used in the actual arguments list.
Page 13 of 26
behave like a ‘black box’ that receives a predefined form of input and outputs a desired
value. Such functions will have two-way data communication.
Page 14 of 26
Functions that Returns Multiple Values:
We have studied functions that return just one value using a return statement. That is
because; a return statement can return only value. Suppose, however, that we want to get
more information. We can achieve this in C using the arguments not only to receive
information but also to send back information to the calling function. The arguments that
are used to “send out” information are called output parameters.
The mechanism of sending back information through arguments is achieved using the
Address Operator ( & ) and Indirection Operator ( * ).
Example: swapping the content of Two Numbers
Page 15 of 26
Passing Parameters to Functions:
The called function receives the information form the calling function through the
parameters. The variables used while invoking the called function are called actual
parameters. And the variables used in the function header of called function are called
formal functions. There are two types of passing parameters to the functions:
1. Pass by value ( Call by Value )
2. Pass by Pointers (Call by Pointers / Address / Reference)
Pass by Value (Call by Value): When a function is called with actual parameters, the
values of actual parameters are copied into formal parameters. If the value of the formal
parameters changes in the function, the values of the actual parameters are not changed.
Note: In pass by value (call by value) any change done on formal parameters will not
affect the actual parameters.
Pass by Pointers / Address / Reference (Call by Pointers): In pass by reference, a
function is called with address of actual parameters. In the function header, the formal
parameters receives the address of actual parameters. Now, the formal parameters do
not contain values, instead they contain addresses. any variable that contains an address
is called a pointer variable. Using pointer variables, the value of the actual parameters
can be changed.
Note: In pass by reference (call by reference) any change done on actual parameters
indirectly using will affect the actual parameters. This way of changing the actual
parameters using formal parameters is called pass by reference or call by reference.
Page 16 of 26
In Pass by Pointers ( or Call by Pointers / References / Address ), the memory addresses
of the variables rather than the copies of values are send to the called function. The called
function directly works on the data in the calling function and the changed values are
available in the calling function for its use. This method is used when manipulating
arrays and strings. And also used when multiple values to be returned by the called
function.
Nesting of Functions:
C permits nesting of functions freely. main can call function-1, which calls function-2,
which calls function-3,. . .,and so on.there is in principle no limit as to how deeply
functions can be nested. Nesting of function calls is also possible. For example:
GCD = gcd( a, gcd( b , c) ); /* GCD of three integers */
add_matrices ( add_matrices ( a, b ), c ); /* Sum of Three Matrices a, b & c */
Note: The nesting dos not mean defining one function within another.
Page 17 of 26
Passing Arrays to Functions:
One-Dimensional Arrays:
To pass a one-dimensional an array to a called function, it is sufficient to list the name of
the array, without any subscripts, and the size of the array as arguments.
Example: big = largest ( a, n) ; will pass the whole array a to the called function.
The called function expecting this call must be appropriately defined. The largest
function header might be int largest ( int array[] , int size )
The declaration of the formal argument array is made as int array[];
In C, the name of the array represents the address of its first element. By passing the
array name, we are, in fact, passing the address of the array to the called function. The
array in the called function now refers to the same array stored in the memory. Therefore,
any change in the array in the called function will be truly reflected in the original array.
Passing addresses of the parameters to the functions is referred to as pass by address or
pass by pointers or pass by reference.
Note: We cannot pass a whole array by value as we did in the case of ordinary variables.
Rules to Pass an Array to a Function
1. The function must be called by passing only the name of the array.
2. In the function definition, the formal parameter must be an array type; the size of
the does not need to be specified.
3. The function prototype must show the argument is an array.
Two-Dimensional Arrays:
Like simple arrays, we can also pass multi-dimensional arrays to functions. It is similar to
the one-dimensional arrays. The rules are simple.
1. The function must be called by passing only the array name.
2. In the function definition, we must indicate that the array has two dimensions by
including sets of brackets ( i.e., [] [] )
3. The size of second dimension must be specified.
4. The prototype declaration should be similar to the function header.
Example:
trace_matrix(a, m, n) ; /* Function Call */
trace_matrix(int array[][n], int m, int n) /* Function Header / Function Definition */
trace_matrix(int array[][n], int m, int n) /* Function Declaration / Prototype */
Page 18 of 26
Passing Strings to Functions:
The strings are treated as character arrays in C, the rules for passing strings to functions
are very similar to those for passing arrays to functions. Like arrays, strings in C cannot
be passed by values to functions.
Example: void display ( char item_name[] ) /* Function Definition */
void display ( char str[] ) ; /* Function Declaration */
display ( names ) ; /* Function Call */
where name must be properly declared in the calling function.
char name [15] ;
Programming Examples
/*
Program : B15.C
Write C User Defined Functions
(i) To input N integer numbers into a single dimension array.
(ii) To conduct a Linear Search.
Using these functions, write a C program to accept the N integer
numbers and given key integer number and conduct a Linear Search.
Report success or failure in the form of a suitable message.
*/
#include <stdio.h>
#include <process.h>
#define SIZE 10
main()
{
int n, key;
clrscr();
linear_search(n,key);
getch();
}
Page 19 of 26
for(i=0 ; i<n ; i++)
{
if(a[i] == key)
{
printf("\nSearch Successful, Key found at position %d", i+1);
getch();
exit(0);
}
}
printf("\nKey Not found / Search Failed...");
return; /* transfer control to the main/calling function */
}
/*
Program : B16.C
Write C User Defined Functions
(i) To input N integer numbers into a single dimension array.
(ii) To sort the integer numbers in ascending order using BUBBLE SORT
technique.
(iii) To print the single dimension array elements.
#include <stdio.h>
#include <process.h>
#define SIZE 10
main()
{
int n;
clrscr();
getch();
}
void bubble_sort(int n)
{
int i,j,k, temp;
Page 20 of 26
{
for(i=0 ; i<n-j ; i++)
{
if(a[i] >= a[i+1])
{
temp = a[i] ;
a[i] = a[i+1] ;
a[i+1] = temp ;
}
}
printf("\nPartial sorted elements after %d pass \n",j);
for(k=0 ; k<n ; k++)
printf("%d ", a[k]);
printf("\n");
}
return; /* transfer control to the main/calling function */
}
/*
Program : B17.C
Write C User Defined Functions
(i) To input N integer numbers into a single dimension array.
(ii) To sort the integer numbers in ascending order using SELECTION
SORT technique.
(iii) To print the single dimension array elements.
#include <stdio.h>
#include <process.h>
#define SIZE 10
main()
{
int n;
clrscr();
Page 21 of 26
/* Function call for Selection Sort */
selection_sort(n);
getch();
}
void print_sorted(int);
void selection_sort(int n)
{
int i,j,k,pos,temp;
temp = a[pos] ;
a[pos] = a[j] ;
a[j] = temp ;
/*
Program : B18.C
Write C User Defined Functions
(i) To input N real numbers into a single dimension array.
(ii) Compute their MEAN.
(iii) Compute their VARIANCE.
(iv) Compute their STANDARD DEVIATION.
Using these functions, write a C program to input N real numbers into
a single dimension array, and compute their mean, variance and standard
deviation. Output the computed results with suitable headings.
*/
#include <stdio.h>
#include <math.h>
#include <process.h>
Page 22 of 26
int i, n; /* Global Declaration */
float x[10], sum, m, v, d; /* Global Declaration */
main()
{
clrscr();
return v;
}
return m;
}
Page 23 of 26
/*
Program : B19.C
Write C User Defined Functions:
(a) To read the elements of a given matrix of size M x N.
(b) To print the elements of a given matrix of size M x N.
(c) To compute the product of two matrices.
Using these functions, write a C program to read two matrices A(MxN) and
B(PxQ) and compute the product of A and B after checking compatibility
for multiplication. Output the input matrices and the resultant matrix
with suitable headings and format.
(Using two dimension arrays where array size M,N,P,Q <= 3)
*/
#include <stdio.h>
#define SIZE 5
int i, j, k;
main()
{
int m, n, p, q, a[SIZE][SIZE], b[SIZE][SIZE], c[SIZE][SIZE];
clrscr();
printf("\nEnter the Size of 2-Dimension Arrays i.e., M,N,P,Q <= 3 Only...");
if ( n != p )
{
printf("\nInvalid array size, Multiplication is not possible...");
getch();
exit(0);
}
product_matrix(a,b,c,m,n,q);
void product_matrix(int a[][SIZE], int b[][SIZE], int c[][SIZE], int m, int n, int q) /* Multiplication of MAT-A with MAT-B,
assigns result to the MAT-C */
Page 24 of 26
{
for(i=0; i<m ; i++)
{
for(j=0; j<q ; j++)
{
c[i][j] = 0 ;
for(k=0 ; k<n ; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j] ;
}
}
}
void write_matrix(int c[][SIZE], int m, int q) /* Function to Display 2-D Matrix */
{
getch();
}
/*
Program : B20.C
Write a C program to read a matrix A(MxN) and to find the following
using User Deifned Functions:
(a) Sum of the elements of the specified row.
(b) Sum of the elements of the specified column.
(c) Sum of all the elements of the matrix.
Output the computed results with suitable headings.
*/
#include <stdio.h>
#define SIZE 5
int i, j, a[SIZE][SIZE];
main()
{
int m, n, col, row, rsum, csum, trace;
clrscr();
Page 25 of 26
a:
printf("\nEnter the ROW number less than %d to find its Sum : ",m+1);
scanf("%d",&row);
if(row>m)
{
printf("\nThe ROW number should not be greater than %d ",m);
goto a;
}
rsum = row_sum(row,n);
printf("\nSum of the elements of ROW-%d = %d\n",row,rsum);
b:
printf("\nEnter the COLUMN number less than %d to find its Sum : ",n+1);
scanf("%d",&col);
if(col>n)
{
printf("\nThe COLUMN number should not be greater than %d ",n);
goto b;
}
csum = col_sum(m,col);
printf("\nSum of the elements of COLUMN-%d = %d\n",col,csum);
trace = matrix_sum(m,n);
printf("\nThe sum of all elements of the given MATRIX : %d",trace);
getch();
}
void accept_matrix(int y, int z)/* Function to read MATRIX */
{
for(i=0; i<y ; i++)
for(j=0; j<z ; j++)
scanf("%d", &a[i][j]);
}
void print_matrix(int y, int z) /* Function to Print MATRIX */
{
for(i=0; i<y ; i++)
{
for(j=0; j<z ; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
}
int row_sum(int row, int n) /* Function to sum specifed ROW */
{
int rsum = 0;
for(j=0; j<n ; j++)
{
rsum = rsum + a[row-1][j] ;
}
return rsum;
}
int col_sum(int m, int col) /* Function to sum specifed COLUMN */
{
int csum = 0;
for(i=0; i<m ; i++)
{
csum = csum + a[i][col-1] ;
}
return csum;
}
int matrix_sum(int m, int n) /* Function to sum of all elements */
{
int sum = 0;
for(i=0; i<m ; i++)
for(j=0 ; j<n ; j++)
sum += a[i][j];
return sum;
}
Page 26 of 26