You're getting the wrong results because the nth element of the series is not (n-1) + (n-2), but the the sum of the previous two elements of the series (and if n=0 or n=1, the elements are 0 or 1 respectively). In short, you implemented the wrong algorithm.
Thanks for clearing the doubt, guys. I see that I am at the very early stages of learning the language. And the seeplus solution looks really amazing. On that note can you suggest to me what books I should study to learn the language basic to advanced.
In the meantime, I would modify my algorithm in a beginner way as the seeplus solution using vectors is something I have not studied yet but I will learn about it. I was also interested in using an array to solve this and will update the algo today and post it back here.
Thanks again, guys. I would like to hear from you about those books.
Thanks.
PS: I just looked it and vectors are nothing but dynamic arrays. :) Computer programming is very interesting.
vectors are an implementation of dynamic arrays wrapped up into a class with an easy-to-use interface. There are also queue/list/deque/stack etc which are part of C++ 'containers'
You have a function that returns an integer value:
1 2 3 4 5 6 7 8 9
// function
int fibseries( int nth )
{
// something
return 0;
}
// used:
fibseries( count );
But when you call it, you don't take the returned value and use it.
If there is no reason to return a value from a function, then it is better to not do so. Set the return type void:
1 2 3 4 5 6 7 8
// function
void fibseries( int nth )
{
// something
}
// used:
fibseries( count );
Note how your function does two things. It computes a value and shows a value. That actually restricts where you can use the function. What if you need the value, but do not want to show anything?
Then it is better to return the value and let the caller use it:
1 2 3 4 5 6 7 8 9 10
// function
int fibseries( int nth )
{
int result = 0;
// calculate result, but no output
return result;
}
// used:
std::cout << ' ' << fibseries( count );
If you are calculating consecutive terms of the series from the start, then you don't need an array for more than just two most recent terms:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
int num = 10, count = 1;
int one = 0;
int two = 1;
while (count < num)
{
std::cout << count << ' ' << two << '\n';
one += two;
std::swap( one, two );
++count;
}
}
There is also recursive approach (and Fibonacci series is often used as an example, even though there are more efficient algorithms for it).