Code and document the following functions using ITERATIVE and RECURSIVE function
ID: 3912402 • Letter: C
Question
Code and document the following functions using ITERATIVE and RECURSIVE functions (two implementations for each function: iteratively and recursively) Test the functions by calling them from a simple interactive main() function using a menu, with different values used to select the choice of function. Overall, you should have one C program (call it firstnameLastnameLab1.c) containing one main function and 10 other functions, where the functions are called based on the user input to the menu choices. The program should contain a loop that permits users to enter a new choice of function for each loop, until exit from the loop explicitly. Factorial(0)-1 1 Factorial(n)n * (n-1)* ..'2 1 Requirement: n0; reject with error message otherwise Fibonacci(0)0 Fibonacci(1)-1 Fibonacci(n) Fibonacci(n-1) Fibonacci(n-2) Requirement: n0; reject with error message otherwise gcd (x,y) x, if y o 3 |gcd (x, y)-gcd (y, XMOD y), if y > 0 Requirement: x and y both 2 0; reject with error message otherwise 4 Power(a.b) -ab Requirement: a> 0, b20, b is an integer; reject with error message otherwise digProduct (x) = x if xExplanation / Answer
#include <stdio.h>
// factorial iterative approach
int factorial_iter(int n)
{
if(n < 0)
{
printf("Invalid");
return -1;
}
// looping for n times to multiply numbers
int result = 1, i;
for(i=1; i<=n; i++)
{
result = result * i;
}
return result;
}
int factorial_recur(int n)
{
if(n < 0)
{
printf("Invalid");
return -1;
}
if(n <= 1)
return n;
// calling recursively and each time multiplying with n
return n*factorial_recur(n-1);
}
int fibonacci_iter(int n)
{
int a = 0, b = 1, i;
// looping for n-2 times to update a and b
for(i = 2; i<=n; i++)
{
int temp = a;
a = b;
b = b + temp;
}
return a;
}
int fibonacci_recur(int n)
{
if(n < 0)
{
printf("Invalid");
return -1;
}
if(n <= 1)
{
return n;
}
// calling recursively with n-1 and n-2
return fibonacci_recur(n-1) + fibonacci_iter(n-2);
}
int main(void) {
// SAMPLE runs
printf("Fibonacci-Iterative: %d ", fibonacci_iter(8));
printf("Fibonacci-Recursive: %d ", fibonacci_recur(8));
printf("Factorial-Iterative: %d ", factorial_iter(5));
printf("Factorial-Recursive: %d ", factorial_recur(5));
return 0;
}
/*SAMPLE OUTPUT
Fibonacci-Iterative: 13
Fibonacci-Recursive: 13
Factorial-Iterative: 120
Factorial-Recursive: 120
*/
// Note: 4 sub parts at a time please -- Policy of Chegg