Both the for loop and the do-while loop can be transformed into a simple while l
ID: 3770713 • Letter: B
Question
Both the for loop and the do-while loop can be transformed into a simple while loop. For each of the following examples, write equivalent code using a while loop instead (a) int factorial ( int n) { int i, ret =1; for (i =2; i <= n; i++) ret = i; return ret; } (b) #include double rand_double () { / generate random number in [0 ,1) / double ret =(double )rand (); return ret /(RANDMAX+1); } int sample_geometric_rv(double p) { double q; int n= 0; do { q = rand double (); n++; } while (q >= p); return n; } Note: You only need to modify the sample_geometric_rv() function.
Explanation / Answer
(a) int factorial ( int n)
{
int i=2, ret =1;
while( i <= n)
{
ret = i;
i++;
}
return ret;
}
(b) #include
double rand_double ()
{
/ generate random number in [0 ,1) /
double ret =(double )rand ();
return ret /(RANDMAX+1);
}
int sample_geometric_rv(double p)
{
double q;
int n= 0;
while (q >= p)
{
q = rand_double ();
n++;
}
return n;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.