1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

#include <stdio.h>
float y0;
float y1;
float y2;
// Recursive function to compute y[k] where
// y[n+3] = 2y[n+2] + y[n+1] + 0.5y[n] and y[0], y[1] and y[2] are given
// Rewrite that as y[k] = 2y[k1] + y[k2] + 0.5y[k3]
// On input, y2=y[2], y1=y[1], y0=y[0].
// On output, y2=y[k], y1=y[k1], y0=y[k2]
float
iDiff(int k, float &y2, float &y1, float &y0)
{
if (k == 2) {
return y2;
} else {
iDiff(k1, y2, y1, y0);
// Now y2=y[k1], y1=y[k2] and y0=y[k3]
float result = 2*y2 + y1 + 0.5*y0;
y0 = y1;
y1 = y2;
y2 = result;
// Now y2=y[k], y1=y[k1] and y0=y[k2]
return result;
}
}
float Diff(int n)
{
float y2=::y2,y1=::y1,y0=::y0; // to avoid changing the globals.
return iDiff(n, y2,y1,y0);
}
float iterative(int n)
{
float y3 = 0.0;
for (int i = 3; i <= n; i++)
{
y3 = 2 * y2 + y1 + 0.5 * y0;
y0 = y1;
y1 = y2;
y2 = y3;
}
return y3;
}
int
main()
{
printf("y0: ");
scanf("%f", &y0);
printf("y1: ");
scanf("%f", &y1);
printf("y2: ");
scanf("%f: ", &y2);
printf("N: ");
int n;
scanf("%d: ", &n);
printf("Recursive: %f\n", Diff(n));
printf("Iterative: %f\n", iterative(n));
return 0;
}
 