Page 164 - DCAP407_DATA_STRUCTURE
P. 164
Unit 9: Recursion
/* Variable x is passed onto the main function */
void main (x)
{
/* Add values of variable s and x and store in variable s */
s = s + x;
/* Print the value of x */
printf (“\n x = %d s = %d”, x, s);
/* If x value is equal to 5 then terminate successfully */
if (x==5) exit (0);
/* main function calls itself which holds post-incremented value of x */
main (++x);
}
Output:
x=1 s=1
x=2 s=3
x=3 s=6
x=4 s=10
x=5 s=15
In this example:
1. First, the stdio.h header file is included using the include keyword.
2. Then, the process.h header file that contains macros and function declaration
are included using the include keyword.
3. Then, the main() function is declared globally.
4. Then, integer variables x and s are initialized and 0 is assigned to s.
5. Execution begins with the void main (x) function which does not return any
value, but a variable x is passed onto it.
6. In this main() function,
(a) First, the values of variable s and x are added and stored in variable s.
(b) Then, the value of x is printed.
(c) Then, using an ‘if’ condition the value of x is checked. If x is equal to 5,
the loop is terminated successfully.
(d) Finally, the main function calls itself with the post-incremented value of
x.
Indirect Recursion
In indirect recursion, two or more functions are involved in recursion. When control passes from one
function and enters into another function, the former function’s local variables are destroyed.
A program that demonstrates indirect recursion between two functions.
/* A preprocessor directive that contains standard input and output operations */
# include <stdio.h>
/* A preprocessor directive that creates text user interfaces */
# include <conio.h>
/* A preprocessor directive that contains macros and function declaration used in
working with processes and threads */
# include <process.h>
/* Initialize integer variable s globally*/
LOVELY PROFESSIONAL UNIVERSITY 157