Hello all,
I've been given an excersize to simplify the following forloop but i think its already simplified, what are your thought, is there anything more i can do?
1 2 3 4 5 6
for( int j = 2 ; j != n; j++ ) {
c = b + a;
a = b;
b = c;
cout << "Fibonacci (" << j + 1 << ") = " << c << endl;
}
#include <iostream>
usingnamespace std;
void fibonacci(int a, int b, int c, int n)
{
cout << "Fibonacci (1) = 0" << endl;
cout << "Fibonacci (2) = 1" << endl;
//using an iterative approach for calculating
//the n_th number in the series
for( int j = 2 ; j != n; j++ ) {
c = b + a;
a = b;
b = c;
cout << "Fibonacci (" << j + 1 << ") = " << c << endl;
}
}
int main()
{
unsignedlong a = 0, b = 1, c = 0, n = 0;
cout << "How many Fibonacci numbers do you want to print?" <<endl;
cin >> n;
fibonacci(a,b,c,n);
return 0;
}
Line 23, 28: There is no need to declare a,b,c as variables in main() or to pass a,b,c as arguments. a,b,c can be decalred as locals inside Fibonacci ().
Are you required to use an iterative algorithm? A recursive algorithm is shorter, but runs the risk of stack overflow for large values of n.