PLease explain code SAMPLE PROBLEM # 4 ON RECURSIVE FUNCTIONS A function f(n) is
ID: 2249985 • Letter: P
Question
PLease explain code
SAMPLE PROBLEM # 4 ON RECURSIVE FUNCTIONS
A function f(n) is given to be f(n) = 2 + 4 + 6 + …+ 2n.
Show that this function f(n) can be represented as a recursive function.
Write down the sequence of steps which the compiler will go through in order to recursively compute the value of f(n) for a sample value n=3 of n.
Design a program in C using a prototype function and the recursive process to compute the value of f(n) for a user-specified value of n.
SOURCE CODE:
int f(int n){
if(n==0){ // Baseline condition
return 0;
}
else{
return 2*n+f(n-1);
}
}
int main(){
int n;
printf("Please enter an n: ");
scanf_s("%d",&n);
printf("f(%d)=%d ",n,f(n));
return 0;
}
Explanation / Answer
initially there should be a command to enter the code in "C"
#include<stdio.h>
this is called standard input and output header file.
comes to the programming
initially
the compiler went to the main function.
int n; means it declares an integer n.
then it will print please enter an n:
you have to give an integer
if you given n=3;
next we have a printf statement it needs n and f(n), we know n but not f(n);
f(n) is a function and also n=3; so it goes f(3);
so n is not equal to "0". so it will return "2*n+f(n-1)". but here n=3, so it will return "2*3+f(3-1)"=="6+f(2)".
now also f(n)is called with n=2. then it goes to the function again checks for n is again not equals to "0".
so it will return "2*n+f(n-1)" here n=2 so it will return "2*2+f(2-1)"="4+f(1)".
no again f(n) is called with n=1. it again goes to the function here n=1 which is not equal to "0".
so ti will return "2*1+f(1-1)"="2+f(0)". here again we call the function so it will goes to it
with n=0; here n=0 so it will return =0;
now total answer="2*3+2*2+2*1+0"
for n=3 returns"2*3+f(2)"=="2*3+2*2+2*1+0"=6+4+2+0=12.
for n=2 returns"2*2+f(1)"
for n=1 returns"2*1+f(0)"
for n=1 returns"0"
then the answer is 12.
what is you are given is the code for prototype recursive programme for f(n).
Thank You.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.