Hi Guys !! good afternoon.
I need your help, I want do an array with recursive function, exactly like a function of fibonacci but with strings !!
Example:
int fib(int x) {
if (x == 1) {
return 1;
} else {
return fib(x-1)+fib(x-2);
}
}
int main() {
cout << fib(5) << endl;
}
but i won't use int, i want string !!
resulting.. A - B - BA - BAB - BABBA - BABBABAB ...
Thank you guys !!
1. Your code is likely to crash :)
2. Fibonacci series with an iterative function is always a good start
3. Recursive Function Fibonacci series are likely to be found on the internet.
4. We are not code printers :)
5. You are welcome
#include <iostream>
void fibonacci(int nb)
{
int i = 0;
int p = 0;
int x = 1;
while (i < nb)
{
std::cout << x << " ";
x = x + p;
p = x - p;
i = i + 1;
}
std::cout << std::endl;
}
int main()
{
int nb;
std::cout << "Enter a range for your fibonacci series" << std::endl;
std::cin >> nb;
fibonacci(nb);
return 0;
}
Output:
Enter a range for your fibonacci series
10
1 1 2 3 5 8 13 21 34 55
Dear Seiza, i'm sorry if you got it wrong.. but...
I'm looking for suggestions.. i won't code... I know that I can find on the internet but not recursive fibonacci with strings.. I found nothing.. well, i thank you for the wellcome. hehe
Giblit i can use for example " x[0]" like a vector in the recursive fibonacci function ?
If I understand: you just want suggestions for a program that "prints" or "store" the string result of a fibonacci serie using recursive method.
like Giblit said:
you start with:
1 2
std::string a = "A";
std::string b = "B";
so with an "iterative" way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void fibonacci(int nb)
{
int i = 1; // 1 because we already have "A"
std::string p = "A";
std::string x = "B";
std::cout << p << " ";
while (i < nb)
{
std::cout << x << " ";
x = x + p;
// x.size() - p.size() gives the previous size of x :)
p = x.substr(0, x.size() - p.size());
i = i + 1;
}
std::cout << std::endl;
}
Output:
Enter a range for your fibonacci series
8
A B BA BAB BABBA BABBABAB BABBABABBABBA BABBABABBABBABABBABAB
Now the tricky part for the recursive way is that you obviously need a way to recover the previous operation. You're just one step away for the recursive fibonacci.