Page 174 - DCAP407_DATA_STRUCTURE
P. 174
Unit 9: Recursion
/* Fibonacci recursion function */
long fibonacci (long n)
{
/* Check if the value of n is equal to 1 */
if (n==1)
{
/* Return 0 */
return 0;
}
/* Check if the value of n is equal to 2 */
if (n==2)
{
/* Return 1 */
return 1;
}
/* Otherwise */
else
{
/* Fibonacci function is invoked within itself and the value is returned */
return fibonacci (n-1) + fibonacci (n-2);
}
}
Output:
Input an integer: 5
Fibonacci (5) = 0, 1, 1, 2, 3
In this example:
1. First, the stdio.h header file is included using the include keyword.
2. Then, fibonacci function is declared globally. It returns and accepts a long
data type.
3. Then, the int main (void) program is defined. This returns an integer value.
4. In main ():
(a) First, initialize the long variables result and number.
(b) Then, accept the value for number.
(c) Then, call the fibonacci function and store its value in a variable result.
(d) Then, print the value of result.
(e) Finally, return the value 0.
5. Then the function fibonacci is defined.
LOVELY PROFESSIONAL UNIVERSITY 167