application of the fibonacci function with loop?

I have a program that calculates the Fibonacci recursion function
and I want to calculate the Fibonacci function by a loop
someone help me please


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include "/home/src/prog.hpp"
unsigned fibo(unsigned n) {
	return n<=2?1:fibo(n-1)+fibo(n-2);
}

unsigned n;

int main(int argc, char* argv[]) {
   if(argc != 2) { 
   cout<<argv[0]<<":syntax error, incorrect number of arguments\n";
   exit(1);
   }
   n = atoi(argv[1]); 
   cout<<"fibo("<<n<<")=" << fibo(n)<<endl;
   return 0;
}
The way to do it in a loop is to keep the two previous values in variables f1 and f2. Then each time through the loop you compute the next value and update the previous ones:
nextval = f1+f2;
f2 = f1;
f1 = nextval;

Hope this helps.
thank you for your help :)
Topic archived. No new replies allowed.