C program Write a program recursive c that takes as input an
C program
Write a program recursive. c that takes as input an integer n and evaluates the function f(n) = {0 n = 0, f(|n| - 1) + 6 if n notequalto 0 is even, f(|n| - 1) - 5 if n is odd. The program prompts the user for a value until they wish to stop. It should use the recursive function int evaluate (int) that takes an integer .v and returns f(x). (-) $ a.out Integer: 5 f(5) = -3 Continue [y/n]? y Integer: 6 f(6) = 3 Continue [y/n]? y Integer: 3 f(3) = -4 Continue [y/n]? y Integer: -2 f(-2) = 1 Continue [y/n]?nSolution
Please find the required program along with its output. Please see the comments against each line to understand the step.
#include <stdio.h>
#include <stdlib.h>
int f(int n){
if(n==0)
return 0;
else if(n%2 == 0) {
return (f(abs(n) - 1) + 6); //abs fndtion will return the positive value
} else if(n%2 == 1) {
return (f(abs(n) - 1) - 5);
}
}
int main(void) {
int n;
char c;
while(1){ //infinite loop
printf(\"\ Integer:\");
scanf(\"%d\",&n); //read the integer
printf(\"f(%d) = %d\",n,f(n)); //print the result by calling recursive function
printf(\"\ Continue[y/n]:\"); //get user input whether he needs to continue
scanf(\"%s\",&c);
if(c==\'n\') //if user enter n (for not to continue) then break from the loop
break;
}
return 0;
}
--------------------------------------
OUTPUT:
