Today’s Topic:
1. User-defined Functions
Course No.: CSE 1281
Course Title: Computer and
Programming Language
Credit: 3.00
1
User-Defined Functions
> C functions can be classified into two categories.
▪ Library functions
▪ User-defined functions
> Library functions are printf, scanf, sqrt, cos, strcat, etc.
> Whereas ‘main’ function that we have used is an example of user-defined function.
2
Why Need User-Defined Functions?
> If we use only main function, then a number of problems may arise.
> The program may be too large for which debugging, testing and maintaining will be very
difficult.
> Therefore, if the program is divided into functional parts, then each part can be coded
independently and then merged to a single unit.
> The independently coded programs are called subprograms and are referred to as
functions.
3
4
Example
5
Elements of User-Defined Functions
> Both function names and variable names are identifiers and therefore they must adhere
to the rules for identifiers.
> Like variables, functions have types associated with them.
> Like variables, function names and their types must be declared and defined before they
are used in a program.
> Elements of functions are –
1. Function definition
2. Function call
3. Function declaration
6
Function Definition
1. Function Definition
❑ Function name
❑ Function type
❑ List of parameters
❑ local variable declarations
❑ Function statements
❑ As return statement
7
Function Calls
8
Points to Note
1. The parameter list must be separated by commas.
2. The parameter names need not to be the same in the prototype declaration and the
function definition.
3. The types must match the types of parameters in the function definition, in number
and order.
4. Use of parameter names in the declaration is optional.
5. If there is no parameter, void can be written.
6. The return type must be void if does not return any value.
9
Fibonacci Series using Function
10
Nesting of Functions
❑ C permits nesting of function freely. main can call finction1, which calls
finction2, which calls function3, ……………..and so on. There is in principle no limit
as to how deeply functions can be nested.
❑ Consider the following program:
float ratio(int x, int y, int z)
{
float ratio (int x, int y, int z);
if(difference(y, z))
int difference (int x, int y);
return(x/(y-z));
main( )
else
{
return(0.0);}
int a, b, c;
int difference(int p, int q)
scanf(“%d %d %d”, &a, &b, &c);
{
printf(“%f \n”, ratio(a,b,c));
if(p != q)
}
return (1);
else
return(0);
}
11
Recursion
> When a called function in turn call another function a process of ‘chaining’ occurs.
> Recursion is a special case of this process, where a function call itself.
12
Factorial of A number using Recursion
13
Reverse of A Number using Recursion
14
Checking Prime Number using Recursion
15
Pascal’s Triangle Using Function
16