0% found this document useful (0 votes)
22 views53 pages

CH 9 UDF

Chapter 9 discusses user-defined functions in C programming, emphasizing their necessity for modularity, ease of debugging, and code maintenance. It outlines the advantages of using functions, types of functions (library and user-defined), and the elements involved in defining and calling functions. Additionally, it covers different categories of functions based on their arguments and return values, as well as parameter passing methods, including pass-by-value and pass-by-reference.

Uploaded by

jekotag796
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views53 pages

CH 9 UDF

Chapter 9 discusses user-defined functions in C programming, emphasizing their necessity for modularity, ease of debugging, and code maintenance. It outlines the advantages of using functions, types of functions (library and user-defined), and the elements involved in defining and calling functions. Additionally, it covers different categories of functions based on their arguments and return values, as well as parameter passing methods, including pass-by-value and pass-by-reference.

Uploaded by

jekotag796
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

CHAPTER 9

“USER-DEFINED FUNCTIONS”
NEED FOR USER-DEFINED FUNCTIONS
C is a modular programming language.
 The program may become too large and complex
and as a result the task of debugging, testing
and maintaining becomes difficult.
 If a program is divided into functional parts,
then each part may be independently coded and
later combined into a single unit. These
independently coded programs subprograms
that are much easier to understand, debug, and
test. In C, such subprograms are referred to as
“Functions”.
 There are times when certain types of operations
2
or calculations are repeated at many points
throughout a program.
ADVANTAGES OF USING THE FUNCTION
 Separating the programs into functions increase
the ease of maintenance and enhancement of
the program.
I t w i l l m a k e t h e p r o g r a m m o r e
understandable for the user.
 It will avoid the duplication of code and
errors.
 Debugging of the program will be easier.

It facilitates top-down modular


programming. In this programming style, the
high level logic of the overall problem is solved
first while the details of each lower-level function
are addressed later. 3

 A function may be used by many other programs.


TYPES OF FUNCTIONS
 There are basically two types of functions.
1. Library Functions
2. User Defined Functions

1) Library Functions: To perform some very


commonly required task, ready-made functions are
also available with C compiler. These functions are
known as Library function.
 The library functions are declared in different files
which are known as header files.
 Header file: math.h

sin(x), cos(x), pow(x,y), sqrt(x) etc.


4
2) User Defined Functions: Functions defined by
the user are called user defined functions.
Elements of User-Defined Functions:
(1) Function definition
 It is an independent program module that is specially
written to implement the requirements of the function.
 A function definition, also known as function
implementation shall include the following
elements:
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements
6. A return statement
 All the six elements are grouped into two parts,
namely, 5
 Function header (first three elements- 1,2 & 3)
 Function body (Last three elements- 4,5 & 6)
Elements of User-Defined Functions:
(1) Function definition
 Syntax:-

Return_Type Function_Name(Arguments or Parameter list)


{
local variable declaration;
executable statment1;
executable statment2;
…………….
…………….
return statement;
}

6
Elements of User-Defined Functions:
(1) Function definition
 Example,

int add ( int x, int y ) // definition of the function


{
int sum;
sum = x + y; // x & y will be taken as input
from the calling func.
return(sum); // returns integer value
}

7
Elements of User-Defined Functions:
(2) Function Call
 In order to use this function we need to invoke it at a
required place in the program. This is known as the
function call.
 The program (or a function) that calls the
function is referred to as the calling program
or calling function.
 The statement which activates the functions with
the required input values (called arguments or
actual arguments) is called calling of the function.
 Ex - answer = add (5,3);
 Here the function add is called in the main
program with the input values 5 and 3. As
defined earlier, add function add this two values
8
and returns the sum which will be assigned to
answer.
Elements of User-Defined Functions:
(3) Function Declaration
 The calling program should declare any function (like
declaration of a variable) that is to be used later in
the program. This is known as the function
declaration or function prototype.
 It consists of four parts:
 Function type (return type)
 Function name
 Parameter list
 Terminating semicolon

 Syntax:
Return_type Function_Name (Arguments);
 Ex - int add (int, int);

9
Elements of User-Defined Functions:
(3) Function Declaration
A prototype declaration may be placed in
two places in a program:
1. Above all the functions (including main) in the
global declaration section, this prototype is
referred to as a global prototype. Such
declarations are available for all the functions
in the program.
2. Inside a function definition (in the local
declaration section), the prototype is called a
local prototype. Such declarations are
primarily used by the functions containing
them.
10
Write a C program that perform addition of two
numbers entered by the user.
#include <stdio.h> /* Function Definition */
int sum(int p, int q)
int main()
{
{
int a,b, answer; /* Variable declaration */ int sum;
int sum(int,int); //Function declaration sum = p+q;
printf("Give the first integer number : \n"); return(sum);
scanf("%d",&a); }
printf("Enter second integer number : \n ");
scanf("%d",&b); Output
answer=sum(a,b); /* Call to the
Give the first integer number : 4
function sum */ Enter second integer number : 8
The sum is 12
printf(“The sum is %d",answer);
return 0;
}

11
Write a C program to find reverse number using UDF.

12
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 but
return a value.
13
 Category 5: Functions that return multiple
values.
Category 1:
Functions with no arguments and no return values.
 When a function has no arguments, it does
not receive any data from the calling
function.
 Similarly, when it does not return a value,
the calling function does not receive any
data from the called function.
 In effect, there is no data transfer between
the calling function and the called function.

14
Category 1:
Functions with no arguments and no return values.
For example, Write a C program to find
addition of two integer numbers using UDF.

#include <stdio.h> void add(void)


{
void add(void); int a,b,sum;
printf("Enter the value
int main() of a & b.");
{ scanf("%d%d",&a,&b);
add(); sum = a+b;
return 0; printf("Addition of a and
} b is %d",sum);
} 15
Category 2:
Functions with arguments and no return values
 Here called function receives the data from
calling function.
 Similarly, when it does not return a value, the
calling function does not receive any data from
the called function.
 In effect, there is one way data transfer between
the calling function and the called function.

16
Category 2:
Functions with arguments and no return values
For example, Write a C program to find addition of
two integer numbers using UDF.
#include <stdio.h> void add(int a,int b)
//Argument calls formal
void add(int a,int b); arguments
{
int main() int sum;
{ sum = a+b;
int a,b,sum; printf("Addition of a and b
printf("Enter a & b."); is %d",sum);
scanf("%d%d",&a,&b); }
add(a,b); // Argument are
called actual arguments
return 0; 17
}
Category 3:
Functions with arguments and one return value
 Here called function receives the data from
calling function.
 Similarly, when it does return a value, the
calling function does receive any data from the
called function.
 In effect, there is two way data transfer between
the calling function and the called function.

18
Category 3:
Functions with arguments and one return value
For example, Write a C program to find addition of
two integer numbers using UDF.
#include <stdio.h> int add(int a,int b)
{
int add(int a,int b); int sum;
int main() sum = a+b;
{
return sum;
int a,b,sum;
//return(a+b);
printf("Enter the value of a
& b."); }
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("Addition of a and b is
%d",sum);
return 0; 19
}
Category 4:
Functions with no arguments but return a value
 When a function has no arguments, it does not
receive any data from the calling function.
 Similarly, when it does return a value, the
calling function does receive any data from the
called function.

20
Category 4:
Functions with no arguments but return a value.
For example, Write a C program to find addition of
two integer numbers using UDF.
#include <stdio.h> int add(void)
int add(void); {
int main() int a,b,sum;
{ printf("Enter the value of
int sum;
a & b.");
sum=add();
scanf("%d%d",&a,&b);
printf("Addition of a and b is
%d",sum); sum = a+b;
return 0; return sum;
} //return(a+b);
}

21
Category 5:
Functions that return multiple values
 The return statement can return only one value.
 Suppose, however, that we want to get more
information from a function. We can achieve this in C
using the arguments not only to receive information
but also to send back information to the calling
function. The arguments that are used to “send-out”
information are called output parameters.
 The mechanism of sending back information through
arguments is achieved using what are known as the
address operator (&) and indirection operator (*).

22
PARAMETER PASSING METHODS

 Inall the function prototype and


definition examples we have seen thus far,
parameters are specified as if they were
simple variables, and the process of
parameter passing is comparable to the
process of assigning a value to a variable:
 Each parameter is assigned the value of its
corresponding argument
 Although the value of a parameter may change
during the course of a function, the value of
the corresponding argument is not affected by
the change to the parameter
PASSING BY VALUE
EXAMPLE
The program below illustrates what happens when arguments are passed by
value. A tracing of the changes in the program’s variables is shown on the right.
int multiply (int, int); a b c x y
2 5 10 2 5
int main()
{
50 10 10
int a, b, c;
a = 2;
b = 5; 5
c = multiply(a,b);
a = multiply(b,c); 50
return 0;
}
When the program ends, the variables
int multiply (int x, int y) remaining in memory have the values
{ shown in red
x = x * y;
return x;
}
LIMITATIONS OF PASS BY VALUE

 Recall that a function can have either one return value


or no return value
 If we want a function’s action to affect more than one
variable in the calling function, we can’t achieve this
goal using return value alone – remember, our options
are one or none
 The next example illustrates this problem
EXAMPLE – SWAP FUNCTION
Suppose we want to write a function that swaps two values: that is, value a is
replaced by value b, and value b is replaced by the original value of a. The function
below is an attempt to achieve this goal.

void swap (int x, int y) The function appears to work correctly. The next
{ step is to write a program that calls the function so
int tmp = x; that we can test it:
x = y;
y = tmp; int main()
} {
int a=2, b=6;
printf(“Before swap, a=%d and b=%d”,a,b);
Output: swap(a,b);
Before swap, a=2 and b=6 cout << “After swap, a=%d and b=%d”,a,b);
After swap, a=2 and b=6 return 0;
}
WHAT WENT WRONG?

 In the swap function, parameters x and y were


passed the values of variables a and b via the
function call swap(a, b);
 Then the values of x and y were swapped
 When the function returned, x and y were no
longer in memory, and a and b retained their
original values
 Remember, when you pass by value, the
parameter only gets a copy of the
corresponding argument; changes to the copy
don’t change the original
BUILDING A BETTER SWAP FUNCTION:
INTRODUCING REFERENCE
PARAMETERS
REVISED SWAP FUNCTION
We indicate the intention to pass by reference by appending an ampersand (&)
to the data type of each reference parameter. The improved swap function
illustrates this:

void swap (int& x, int& y) The reference designation (&) means that x and
{ y are not variables, but are instead references
int tmp = x; to the memory addresses passed to them
x = y;
y = tmp; If we had the same main program as before,
} the function call:
swap(a,b);
indicates that the first parameter, x, is a
reference to a, and the second parameter, y, is
a reference to b
HOW PASS-BY-REFERENCE WORKS

 In the example on the previous slide, x and y


referenced the same memory that a and b referenced
 Remember that variable declaration does two things:
 Allocates memory (one or more bytes of RAM, each of which
has a numeric address)
 Provides an identifier to reference the memory (which we use
instead of the address)
 Reference parameters are simply additional labels that
we temporarily apply to the same memory that was
allocated with the original declaration statement
 Note that this means that arguments passed to
reference parameters must be variables or named
constants; in other words, the argument must have its
own address
EXAMPLE
Earlier, we looked at a trace of the program below, on the left. The program
on the right involves the same function, this time converted to a void function
with an extra reference parameter.
Nesting of functions
 C permits nesting of functions freely.
 main() can call function1, which calls function2,
which calls function 3, which can call function 4, …
… … and so on.
 There is in principle no limit on as to how deeply
functions can be nested.

33
Nesting of functions
For example, Write a C program to find delta. [Hint.
Delta = b2 – 4*a*c]
#include<stdio.h> int delta(int y,int x,int z)
{
int delta(int,int,int); int d;
int square(int); d=square(y)-4*x*z;
return d;
void main()
}
{
int a,b,c,d;
printf("Enter the value of a,b int square(int b)
& c"); {
scanf("%d%d%d",&a,&b,&c); return b*b;
d=delta(b,a,c); }
printf("\nD=%d",d);
return 0; 34
}
Example: Fing factorial of a number
Write a C program to find factorial of a given number
[Hint: Factorial of 3 = 3 * 2 * 1 = 6]
#include <stdio.h> Output:
Enter a number to
int main() calculate it's factorial
{ 5
int c, n, fact = 1;
Factorial of 5 = 120
printf("Enter a number to
calculate it's factorial\n");
scanf("%d", &n);

for (c = 1; c <= n; c++)


fact = fact * c;

printf("Factorial of %d =
%d\n", n, fact); 35
return 0;
}
Recursion
 When a called function in turn calls another
function a process of ‘chaining’ occurs. Recursion
is a special case of this process, where a
function calls itself.
A very simple example of recursion is
presented below:
main()
{
printf(“This is an example of recursion.\n”);
main();
}
36
Recursion
Write a C program to find factorial of a given number
using concept of recursion. [Hint: Factorial of 3 = 3 *
2 * 1 = 6]
#include<stdio.h> long int factorial(int no)
long int factorial(int no); {
void main() long int fact;
{ if(no==1)
int no;
return 1;
long int fact;
else
printf("Enter the number=");
scanf("%d",&no); fact=no*factorial(no-1);
fact=factorial(no); return fact;
printf("Factorial of number= }
%ld",fact);
return 0;
} 37
Factorial with Recursion - Explained
5! 120

5 * 4! 5 * 24

4 * 3! 4*6

3 * 2! 3*2

2 * 1! 2*1

1
38
Passing arrays to functions: One-Dimensional arrays:
 Like the values of simple variables, it is also possible
to pass the values of an array to a function.
 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.
 For example,
int a[10],n=10;
largest(a,n);
will pass the whole array a to the called function.
 Otherwise we have to pass the first element address
to called function.
 Like, 39

largest(&a[0],n);
Passing arrays to functions: One-Dimensional arrays:
 The called function expecting this call must be
appropriately defined. The function header might
look this:
int largest(int a[], int size)

 Three 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 array does
not need to be specified.
3. The function prototype must show that the
argument is an array.
40
Write a C program to find out largest number in array using
function.
#include<stdio.h> int largest(int a[],int n)
{
int largest(int [],int);
int large,i;
void main() large=a[0];
{ for(i=0;i<n;i++)
int i,j,large; {
int a[10],n; if(large<a[i])
printf("Enter the elements of the
array=\n");
large=a[i];
for(i=0;i<10;i++) }
{ printf("a[%d]=",i+1); return large;
scanf("%d",&a[i]); }
}
large=largest(a,10);
printf("Largest = %d",large);
return 0; 41
}
Passing strings to functions
 The strings are treated as character arrays in C and
therefore the rules for passing strings to functions
are very similar to those for passing arrays to
functions.
 Basic rules:

1. The string to be passed must be declared as a


formal argument of the argument of the function
when it is defined.
Example,
void display(char item_name[])
{
………
……… 42

}
Passing strings to functions
 Basic rules:
2. The function prototype must show that the
argument is a string. For the above function
definition, the prototype can be written as
void display(char str[]);
3. A call to the function must have a string array name
without subscripts as its actual argument.
display(names);
where names is a properly declared string array in
the calling function.

 We must note here that, like arrays, strings in C


cannot be passed by value to functions. 43
The scope, visibility and lifetime of variables
 InC not only do all variables have a data type,
they also have a storage class. The following
variable storage classes are most relevant to
functions.
1. Automatic variables
2. External variables
3. Static variables
4. Register variables

44
The scope, visibility and lifetime of variables
 The scope of variable determines over what region of
the program a variable is actually available for use
(‘active’).
 The Longevity refers to the period during which a
variable retains a given value during execution of a
program (‘alive’).
 The visibility refers to the accessibility of a variable
from the memory.

 The variables may also be broadly categorized,


depending on the place of their declaration, as
internal (local) or external (global).
 Internal variables are those which are declared
within a particular function. 45

 External variables are declared outside of any


function.
The scope, visibility and lifetime of variables:
1. Automatic variables
 Automatic variables are inside a function in which
they are to be utilized. They are created when the
function is called and destroyed automatically
when the function is exited, hence the name
automatic.
 Automatic variable is also known as local variable or
internal variable.

46
The scope, visibility and lifetime of variables:
1. Automatic variables

47
The scope, visibility and lifetime of variables:
2. External variables
 Variables that are both alive and active
throughout the entire program are known as
external variables.
 They are also known as global variables.
 In a case local variable and a global variable have
the same name, the local variable will have
precedence over the global variable one in the
function where it is declared.
 global variables are initialized to zero by
default.

48
Write a multifunction program to illustrate how global
variables work.
#include<conio.h> function1(void)
#include<stdio.h> {
int function1(void); a=a-10;
int function2(void); }
int function3(void); int function2(void)
int a; /*global or external {
variables*/ int a; /*automatic or local
void main() variable*/
{ a=10;
clrscr(); return(a);
a=50; /*global a*/ }
printf("a=%d\n",a); function3()
printf("a=%d\n",function1()); {
printf("a=%d\n",function2()); a=a+20; /*global a*/
printf("a=%d\n",function3()); }
getch(); 49

}
The scope, visibility and lifetime of variables:
3. Static variables
 As the name suggests, the value of static
variables persists until the end of the program.
 A variable can be declared static using the
keyword static like
static int x;
static float y;
A static variable is initialized only once,
when the program is complied. It is never
initialized again.

50
The scope, visibility and lifetime of variables:
3. Static variables

51
The scope, visibility and lifetime of variables:
4. Register variables
 We can tell the compiler that a variable should
be kept in one of the machine’s registers,
instead of keeping in the memory.
 Since a register access is much faster than a
memory access, keeping the frequently
accessed variables (e.g., loop control variables)
in the register will lead to faster execution of
programs. This is done as follows:
register int x;

52
Thank You

You might also like