Vasu_candy - 5 months ago 47

C Question

I need to generate a modified Fibonacci series and it must be completely dynamic. Here f0 and f1 will be given, i.e f0=1 and f1=3 after generating the series. I should print the resulting value at a particular index.

Ex: f0 = 1, f1 = 3, testcase(n) = 3 (This can change not a particular value)

t1 = 4 t2 = 8 t3 = 11 and so on. Series should be generated for 11 elements by adding current element and previous element using: f[i] = f[i-1] + f[i-2]

It can be represented as:

`0=>1`

1=>3

2=>4

3=>7

4=>11

5=>18

6=>29

7=>47

8=>76

9=>123

10=>199

11=>322

I should print the values at indices 4,8 and 11 (which must be the output of my program), i.e.

`11 76 322`

Input Format:

f0,f1 and n (where n is the no of indices)

where ti=[t1,t2,....tn-1] (which specifies the index for R-Fibonacci series).

Output Format:

Print the values from the R-fibonacci series based on the given indices.

Sample Input:

1 3 3 4 8 11

Sample Output:

11 76 322

I have the code that generates the Fibonacci series for the above program but I want to display the value at 4,8,11 indices. Here is the code:

`int fib(int n)`

{

int f[n+1];

int i;

f[0]=1;

f[1]=3;

for(i=2;i<=n;i++)

{

f[i]=f[i-1]+f[i-2];

}

return f[n];

}

int main()

{

int n=11

printf("%d ",fib(n));

getchar();

return 0;

}

Answer

Like this? The array is defined in `main`

and passed to the function as an argument. The function fills in the array, returns nothing, and then in `main`

you can print the elements you want.

You will need a loop to do that, with another dynamic array holding the indices you are asked to print.

```
#include <stdio.h>
void fib(int n, int *f)
{
int i;
f[0] = 1;
f[1] = 3;
for(i = 2; i <= n; i++)
{
f[i] = f[i-1] + f[i-2];
}
}
int main()
{
int n = 11;
int f[n+1];
fib(n, f);
printf("%d ", f[8]);
printf("%d ", f[11]);
printf("\n");
getchar();
return 0;
}
```

Program output:

```
76 322
```

I will leave you some code to write, but suppose you make a dynamic array of the index values required, such as

```
int index[m];
index[0] = 4;
index[1] = 8;
index[2] = 11;
```

you can print the series term with such as

```
printf("%d ", f[ index[i] ]);
```