Lecture 6:
Function
Engr. Md Arif Hasan Chowdhury
Assistant Professor
Department of Computer Science and
Engineering
Southern University Bangladesh
Function in C
A function is a block of code that performs a specific
task.
Dividing a complex problem into smaller chunks
Types of function
•Built-in/Standard library functions
•User-defined functions
User Defined Function in C
1.Function Declaration
2.Function Definition
3.Function Calls
Function in C
Function Declarations
Syntax
return_type name_of_the_function (parameter_1,
parameter_2);
Return type
Name of the funtion
List of parameters
Terminating semicolon
Example
int sum(int a, int b);
int sum(int , int);
Function in C
Function Definition
Syntax: return_type function_name( parameter
list )
{
body of the function
}
•Return Type
•Function Name
•Parameters
•Function Body
Example
float findArea(float length, float
width)
{
float area; //variable declaration
area = length * width;
return area; //return statement
}
Function in C
Function Call
Syntax: function_name( var1, var2, ...... , varN );
Example: float num1=12.34, num2=34.67, result;
result = my_sum( num1, num2 ); /* This is function call */
Example: Function in C
// C program to show function
// call and definition
#include <stdio.h>
// Function that takes two parameters
// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
return a + b;
}
// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);
printf("Sum is: %d", add);
return 0;
}
Example: Function in C
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Example: Function in C
Program: Sum of two numbers using user defined function*/
#include<stdio.h>
float my_sum(float x, float y); /* Function Prototype */
void main()
{
float num1=12.34, num2=34.67, result;
result = my_sum(num1, num2); /* Function Call */
printf("Sum is : %f.",result);
}
float my_sum(float x, float y) /* Function definition */
{
float sum; sum = x + y; return(sum);
}
Output:
Sum is : 47.010000.
Function in C
Advantages of user-defined function
1.Reduction in Program Size: Since any sequence of statements which
are repeatedly used in a program can be combined together to form a
user defined functions. And this functions can be called as many
times as required. This avoids writing of same code again and again
reducing program size.
2.Reducing Complexity of Program: Complex program can be decomposed
into small sub-programs or user defined functions.
3.Easy to Debug and Maintain : During debugging it is very easy to
locate and isolate faulty functions. It is also easy to maintain
program that uses user defined functions.
4.Readability of Program: Since while using user defined function,
a complex problem is divided in to different sub-programs with
clear objective and interface which makes easy to understand the
logic behind the program.
5.Code Reusability: Once user defined function is implemented it
can be called or used as many times as required which reduces code
repeatability and increases code reusability.
Types of Function Call
Types of Function calls in C
1.Call by Value
2.Call by Reference
•Formal Parameter: A variable and
its type as they appear in the
prototype of the function or
method.
•Actual Parameter: The variable or
expression corresponding to a
formal parameter that appears in
the function or method call in the
calling environment.
Call by value
The value of the actual parameters is copied
into the formal parameters.
The variable is used in the function call in
the call by value method.
Can not modify the value of the actual
parameter by the formal parameter.
In call by value, different memory is
allocated for actual and formal parameters
since the value of the actual parameter is
copied into the formal parameter.
The actual parameter is the argument which
is used in the function call whereas formal
parameter is the argument which is used in
the function definition.
Example Call by value
// C program to illustrate
// call by value
#include <stdio.h>
void func(int a, int b)
{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7;
// Passing parameters
func(x, y);
printf("In main, x = %d y = %d\n", x, y);
return 0;
}
Output:
In func, a = 12 b = 7 In main, x = 5 y = 7
Example:Call by value
#include <stdio.h>
void swap(int x, int y)
{
int temp = x; x = y;
y = temp;
}
int main()
{
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n",
x,y);
swap(x,y);
printf("Values after swap: x = %d, y = %d",
x,y);
}
Output
Values before swap: x = 10, y = 11
Values after swap: x = 10, y = 11
Call by Reference
The address of the variable is passed into
the function call as the actual parameter.
The value of the actual parameters can be
modified by changing the formal parameters
since the address of the actual parameters
is passed.
The memory allocation is similar for both
formal parameters and actual parameters.
All the operations in the function are
performed on the value stored at the
address of the actual parameters, and the
modified value gets stored at the same
address.
Example: Call by Reference
// C program to illustrate
// call by reference
#include <stdio.h>
void swapnum(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp; Output:
} a is 20 and b is
10
int main(void)
{
int a = 10, b = 20;
// passing parameters
swapnum(&a, &b);
printf("a is %d and b is %d\n", a, b);
return 0;
}
Example: Call by Reference
#include <stdio.h>
void swap (int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n",
x,y);
swap(&x,&y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
Values before swap: x = 10, y = 11
Values after swap: x = 11, y = 10
Call by Value vs Call by
Reference
No. Call by value Call by reference
1 A copy of the value is An address of value is
passed into the function passed into the function
2 Changes made inside the Changes made inside the
function is limited to function validate outside
the function only. The of the function also. The
values of the actual values of the actual
parameters do not change parameters do change by
by changing the formal changing the formal
parameters. parameters.
3 Actual and formal Actual and formal
arguments are created at arguments are created at
the different memory the same memory location
location
Recursion in C
• Recursion is the process of calling a function itself
repeatedly until a particular condition is met.
• A function that calls itself directly or indirectly is
called a recursive function and such kind of function
calls are called recursive calls.
Syntax of Recursion
Syntax:
void recursive_fun() //recursive function
{
Base_case; // Stopping Condition
recursive_fun(); //recursive call
}
int main()
{
recursive_fun(); //function call
}
Direct and Indirect
Recursion
1. Direct Recursion
Direct recursion in C occurs when a function_01()
function calls itself directly from {
inside. Such functions are also called function_01();
direct recursive functions. }
2. Indirect Recursion
Indirect recursion in C occurs when a function_01()
{
function calls another function and if
function_02();
this function calls the first function }
again. Such functions are also called function_02()
indirect recursive functions. {
function_01();
Following is the structure of indirect }
recursion.
Example: Sum of Natural Numbers Using
Recursion
#include <stdio.h>
int fact(int);int main() {
int num, factorial;
printf("Enter a positive integer: ");
scanf("%d", &num);
factorial = fact(num);
printf("Factorial = %d", factorial);
return 0;
}
int fact(int num) {
if (num == 0){
return 0;
}
else if (num == 1){
return 1;
}
else
return num*fact(num - 1); // fact() function calls itself
}
Output:
Enter a positive integer: 8
40320
Working of Recursive function in the above example
Cycle Else return If return Result from if-else
1st Execute Not Execute return 8*fact(7) = 40320
2nd Execute Not Execute return 7*fact(6) = 5040
3rd Execute Not Execute return 6*fact(5) = 720
4th Execute Not Execute return 5*fact(4) = 120
5th Execute Not Execute return 4*fact(3) = 24
6th Execute Not Execute return 3*fact(2) = 6
7th Execute Not Execute return 2*fact(1) = 2
8th Execute Not Execute return 1*fact(0) = 1
9th Not Execute Execute N/A
Example Recursion
program that calculates the factorial of an entered number
#include <stdio.h>
int factorial (int n) {
if (n > 0) // exiting condition for the recursive call
{
return n * factorial (n-1) ; //recursive call
}
else {
return 1 ;
}
}
int main( )
{
int n;
int result =0;
printf(“Enter the Number: \n”);
scanf(“%d”, &n);
result = factorial(n); // function called
printf(“The result is: %d”, result);
return 0;
}
Output:
Enter the Number: 5
The result is: 120
Advantages and Disadvantages of
Recursion
Advantages of Recursion in C
•Makes the program elegant.
•It adds clarity to the program code and also
reduces the time to write the code.
•Reduces time complexity.
•It is best for solving problems based on tree
structures.
Disadvantages of Recursion in C
•It is slower than non recursive programs due to
the overhead of maintaining the stack.
•It requires more memory for the stack.
•For better performance, use loops instead of
recursion. Because recursion is slower.
Argument vs Parameter
S.No. Argument Parameter
1 The values that are declared The variables that are
within a function when the defined when the function is
function is called are known declared are known as
as an argument. parameters.
2 These are used in function These are used in the
call statements to send function header of the called
value from the calling function to receive the value
function to the receiving from the arguments.
function.
3 During the time of call each Parameters are local
argument is always assigned variables which are assigned
to the parameter in the values of the arguments when
function definition. the function is called.
4 They are also known as They are also known as Formal
Actual Parameters. Parameters.