Unit 5
Unit 5
Structured Design-1
Mr. Pathan Bilalkhan R. Assistant Professor
Department of Computer Science & Engineering
CHAPTER-5
Functions & Recursion
Contents
1. Functions
2. Recursion
1. Function :
Function return type tells what type of value is returned after all function is executed. When we don’t want to return a
value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the function.
Note: Only one value can be returned from a C function. To return multiple values, we have to use pointers or structures.
Function Arguments:
Function Arguments (also known as Function Parameters) are the data that is passed to a function.
Example:
For Example:
• Functions that the programmer creates are known as User-Defined functions or “tailor-made functions”.
User-defined functions can be improved and modified according to the need of the programmer.
• Whenever we write a function that is case-specific and is not defined in any header file, we need to
declare and define our own functions according to the syntax.
// Driver code
int main()
{
int a = 30, b = 40;
// function call
int res = sum(a, b);
• The data passed when the function is being invoked is known as the Actual parameters.
• In the below program, 10 and 30 are known as actual parameters.
• Formal Parameters are the variable and the data type as mentioned in the function
declaration.
• In the below program, a and b are known as formal parameters.
Example:
Advantages of Functions in C
• The function can reduce the repetition of the same statements in the program.
• There is no fixed number of calling functions it can be called as many times as you
want.
• The function reduces the size of the program.
Once the function is declared you can just use it without thinking about the internal
working of the function.
Disadvantages of Functions in C
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a
recursive function
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}