On 13 Feb, 11:51, "mac" <andrei.croito...@gmail.com> wrote:
> Hi,
>
> I'm trying to write a fibonacci recursive function that will return
> the fibonacci string separated by comma. The problem sounds like this:
> -------------
> Write a recursive function that creates a character string containing
> the first n Fibonacci numbers - F(n) = F(n - 1) + F(n - 2), F(0) =
> F(1) = 1 -, separated by comma. n should be given as an argument to
> the program. The recursive function should only take one parameter, n,
> and should return the string. You will not use any extra function.
>
> Do not try to optimize for space or speed. Do not assume any maximum
> length for the result string. Also, please don't use global / static
> variables.
> -----------
>
> The code must be in C.
Really? Because this is a C++ newsgroup. comp.lang.c is just down the
hall and will be able to help you better if C++ is not allowed.
> I managed to create a function that returns the
> fibonacci value for the specified 'N' as a char*, but I didn't manage
> to get the entire string separated by comma.
> This is my function:
>
> char* Recursive(int n){
> char* a = malloc(n*sizeof(char));
> if(n == 0 || n == 1)
> sprintf(a, "%d", n);
> else
> sprintf(a, "%d", atoi(Recursive(n-1)) +
> atoi(Recursive(n-2)));
> return a;
> }
>
> How could I get the entire string?
> Thanks in advance for help!
There are problems with your program so far. You are seeing the nth
fibonacci number returned, but think about what memory the other
fibonacci numbers are stored in. You have explicit allocation with no
explicit deallocation, so you leak memory. The buffer you allocate
(size n*sizeof(char)) is not big enough if any of the fibonacci
numbers have more than one digit. This depends entirely on the value
of n. In C++, sizeof char is 1 by definition so multiplying n by
sizeof char is redundant. I would be surprised (but I am prepared to
be surprised) if the same is not true in C.
All of that should be fixable, but before looking for help here, can
you confirm which language you are working in? For help in C, ask in
comp.lang.c. They will be better able to help you. If you really are
happy with a C++ solution (for which the first change will be to ditch
char*, malloc and sprintf in favour of std::string) then come back
here and you will get plenty of help with that.
Gavin Deane
|