Why happen this loop?

Can anyone tell me why the result of the follow program is a loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

unsigned long fibonacci( unsigned long );

unsigned long number=0;
int main()
{

    for ( int counter = 0; counter <= 10; counter++ )
        cout << "fibonacci( "<< counter << " ) = "
        << fibonacci( counter ) << endl;

        cout << "fibonacci( 20 ) = "<< fibonacci( 20 ) << endl;
        cout << "fibonacci( 30 ) = "<< fibonacci( 30 ) << endl;
        cout << "fibonacci( 35 ) = "<< fibonacci( 35 ) << endl;

        return 0;
}
unsigned long fibonacci( unsigned long number )
{
    cout << number << endl;

    if ( ( number == 0 ) || ( number == 1 ) )
        return (number);

    else
        return fibonacci( number - 1) + fibonacci(number-2);
}

Um... because that's how you've written it? You have a "for" loop right there in your code.
I mean the perpetual loop that result from cout command (line 24) into the fibonacci equation.
It is not a perpetual loop, it is only a long loop.
Maybe you don't want to write the number parameter on screen, so delete line 24 to obtain a clean result.
That's right! I observed that without line 24, the result is clean. But why number parameter (line 24) result a long loop?
What do you mean by "loop"?

Surely not the recursion?
f(3) -> 3
  f(2) -> 2
    f(1) -> 1
    f(0) -> 0
  f(1) -> 1
When using cout<< number<< endl; command (line 24) i cannot take result because the program run continuously. This call loop.
The output is kind of slow so it makes your program take much longer time to complete. Do you understand how many times the fibonacci function is actually being called? Calling fibonacci(35) will result in 29 860 703 calls to the function. Printing that many numbers is going to take a while.
It won't run continuously. All the additional IO simply slows it down.

The f(3) in my example executes line 24 for five times.
f(4) prints nine numbers.
f(5) prints 15 numbers.
...
Therefore, f(35) will print quite many numbers.
I understand!! Thank you very much!
Topic archived. No new replies allowed.