In: Computer Science
C programming
Rewrite the following function using no loops, and only
tail call recursion
double question5 (int in)
{
int i;
int result;
for (result = rand(), i = 0; i < in; i += 3)
{
result /= i;
result += rand();
}
return result;
}
1). ANSWER :
GIVENTHAT :
This program causes floating point exception
Reason:
for(result = rand(),i=0;i<in;i+=3)
Initial i value is 0
result/=i;
It means that result = result/i that is result / 0 causes floating point exception.
If the i value is 1 then the equivalent program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double question5(int in) // recursive calling function
{
srand(time(0)); //seed random number generator
if(in<=1) // Loop runs until in greter than
return 0; // stop of recursion
return (rand()/(in-1)) + rand() + question5(in-1); // recursive calling
}
int main(void) {
int in=5; // Assign the value of in as 5
printf("%f",question5(in)); // calling function pass in value
return 0;
}
Output:
