Q2 Consider the function fn 5fn16fn2 n 2 f0 0 f1 1 Write
Q2) Consider the function f(n) = 5f(n1)6f(n2), n 2, f(0) = 0, f(1) = 1. Write a program that calculates f(n) recursively.
At the start of the program, prompt the user to input an integer number by printing \"Input an integer:\ \". If the input is negative, then print \"Input must be nonnegative.\ \". If the input is nonnegative, then print the value of f(n) as \"f(<n>) = <f(n)>\ \", where <n> and <f(n)> are replaced with the values of n and f(n), respectively.
You should use the following function prototype:
Example input/output pairs (without the prompt) are provided below.
(a) Input: 0; Output: f(0) = 0 (b) Input: 1; Output: f(1) = 1
(c) Input: 3; Output: f(3) = 19
1
(d) Input: 4; Output: f(4) = 65
Note: Include all of your code in one file named recursion.c.
Solution
We use recursive function nothing but calls the function itself for each value.
RecursiveFun(int n)
5*recursive fun(n-1)-6*recursive fun(n-2)
#include <stdio.h>
int RecursiveFunction(int n);
int main()
{
int number, result;
printf(\"Enter a positive integer: \");
scanf(\"%d\", &number);
result = RecursiveFunction(number);
printf(\"sum=%d\", result);
}
int RecursiveFunction(int num)
{
if (num==0){
return 0;
else if (num==1)
return 1;
else{
if (num!=0)
return num + 5*RecursiveFunction(num-1)-6*RecursiveFunction(num-2); // sum() function calls itself
else
return num+1;
}
}
}
