-
Binocchi numbers
Hello guys,
I’m doing a beginner course in C++.
I was given as an exercise to display “Binocchi” (spelled right?) numbers using arrays.
(1, 1+1=2, 1+2=3, 2+3=5, 5+3=8, 5+8=13, etc.)
(hence: 1 1 2 3 5 8, etc.)
After long consideration I got this:
Code:
#include <iostream.h>
int main()
{
int myarray[5];
myarray[0] = 1;
myarray[1] = 1;
for(int i = 2; i<5; i++)
{
myarray[i] = myarray[i-1] + myarray[i-2];
}
cout << myarray << endl;
return 0;
}
As far my logic goes the array should display 1 1 2 3 5 8.
I’m still not familiar with these arrays, for loops, etc. I mean, I’m having fun but its getting a bit frustrating.
Also would be nice if I could get a user to enter a number for the iterations.
If someone wants to shed some light. Thanks.
-
>> was given as an exercise to display “Binocchi” (spelled right?) numbers using arrays.
thats "Fibonacci" and your output looks good. check the tutorials on this site for how to take input if you want the user to specify the number.
-
If you want to get user input for the number of iterations, you can create an int variable, and do this:
Code:
int iterations;
cout << "Enter number of iterations: ";
cin >> iterations;
Then, you can dynamically allocate the array (int* myArray = new int[iterations]; ). In the loop, you then use 'iterations' instead of '5'. I believe you'll have to use another loop at the end to display the elements of the array one by one. Then at the very very end, once you're done with myArray, call delete[] myArray; to free the memory.
**EDIT
Yeah, read up on user input in the tutorials. It'll help :)
-
>> thats "Fibonacci" and your output looks good.
It looks good , but it doesnt return the value.
I run the program and I get rubbish.
-
Code:
cout << myarray[0] << endl;
cout << myarray[1] << endl;
for(int i = 2; i<5; i++)
{
myarray[i] = myarray[i-1] + myarray[i-2];
cout << myarray[i] << endl;
}
-
swoopy:
jeez! thanks for that.
Thats a bit better... but still not returning "Fibonacci" numbers (?)
-
do you mean it's starting at 2? the reason behind that is because that's actually where you're starting in the sequence. The way you did it before with calculating it all in the first place, then displaying it was the right way to do it, you just implemented it wrong :)
What you need to do is initialize the array, just like you're doing right now, THEN output the whole array, starting at slot zero, this will output the fibonnacci sequence starting with 1 1 2 instead of 2
-edit-
:wait, just read the first two lines of swoopy's posted code:
ok, i didn't see that......
That method works perfectly fine, the method above also works too, just different implementation. (And the first method is technically faster)
-
> cout << myarray[i] << endl;
Did you move this cout to within the for-loop? When I run it I get 1,1,2,3,5.
-
Oh yes. :-)
Sorry I missed that (its 5am here. I better go to sleep)
Thanks a lot the reply
Goodnight/morning