int F ( int n )
{
return ( n < 1 ? 1 : 2*n + F(n-1) );
}
Determine the value of F(5).
+-----+----------------+----------+ | n | 2*n + F(n-1) | return | +-----+----------------+----------+ | 5 | 10 + F(4) | 31 | | 4 | 8 + F(3) | 21 | | 3 | 6 + F(2) | 13 | | 2 | 4 + F(1) | 7 | | 1 | 2 + F(0) | 3 | | 0 | --- | 1 | +-----+----------------+----------+
int Search ( const char s[], char c )
{
int i;
int pos = -1;
for (i = 0; s[i] != '\0'; i++)
if (s[i] == c) pos = i;
return pos;
}
int Search ( const char s[], char c, int i, int p )
{
if (s[i] == '\0')
return p;
else if (s[i] == c)
return Search(s,c,i+1,i);
else
return Search(s,c,i+1,p);
}
char *Convert ( const char name [] )
{
char *result;
int n = strlen(name);
int i,j,k;
result = (char*)calloc(n,sizeof(char));
for (i = 0; i < n; i++) /* search for the comma */
if (name[i] == ',') break;
k = 0; /* k will run through result */
for (j = i+2; j < n; j++) /* store the first name */
result[k++] = name[j];
result[k++] = ' '; /* space separates first and last name */
for (j = 0; j < i; j++) /* store the last name */
result[k++] = name[j];
result[k] = '\0'; /* place the sentinel */
return result;
}
x(n) = 1 + c*x(n-1) - x(n-2), n >= 2, x(0) = 0, x(1) = 0where c is some float.
float xrec ( int n, float c )
{
if (n <= 1)
return 0.0;
else
return 1.0 + c*xrec(n-1,c) - xrec(n-2,c);
}
float xitr ( int n, float c )
{
float previous, current, new;
int i;
previous = 0;
current = 0;
for (i = 2; i <= n; i++)
{
new = 1 + c*current - previous;
previous = current;
current = new;
}
return current;
}
int Search ( char *items[], const char *item, int first, int last )
{
int middle,rescmp;
if (first == last)
if (strcmp(items[middle],item) == 0)
return first;
else
return -1;
else
{
middle = (a+b)/2;
rescmp = strcmp(items[middle],item);
if (rescmp == 0)
return middle;
else if (rescmp < 0)
return Search(items,item,middle+1,last);
else
return Search(items,item,first,middle-1);
}
}
int Search ( char *items[], const char *item, int first, int last )
{
int tmpfirst,tmplast,middle,rescmp;
tmpfirst = first;
tmplast = last;
while (tmpfirst != tmplast)
{
middle = (tmpfirst+tmplast)/2;
rescmp = strcmp(items[middle],item);
if (rescmp == 0)
return middle;
else if (rescmp < 0)
tmpfirst = middle + 1;
else
tmplast = middle - 1;
}
if strcmp(items[tmpfirst],item)
return tmpfirst;
else
return -1;
}
Apply divide and conquer and use integ to implement the function float adapint ( float a, float b, float eps ); which returns the value of the integral where every call to integ gave a value for err strictly less than the given eps.
float adapint ( float a, float b, float eps )
{
float val,err;
integrate(a,b,&val,&err);
if (err < eps)
return val;
else
return adapint(a,(a+b)/2,eps) + adapint((a+b)/2,b,eps);
}
FINAL EXAM in LC C3 on Monday 30 April 2001 at 1:00-3:00PM.