-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFig10_40.cpp
More file actions
43 lines (39 loc) · 1 KB
/
Fig10_40.cpp
File metadata and controls
43 lines (39 loc) · 1 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream.h>
/* START: Fig10_40.txt */
/**
* Compute Fibonacci numbers as described in Chapter 1.
*/
int fib( int n )
{
if( n <= 1 )
return 1;
else
return fib( n - 1 ) + fib( n - 2 );
}
/* END */
/* START: Fig10_41.txt */
/**
* Compute Fibonacci numbers as described in Chapter 1.
*/
int fibonacci( int n )
{
if( n <= 1 )
return 1;
int last = 1;
int nextToLast = 1;
int answer = 1;
for( int i = 2; i <= n; i++ )
{
answer = last + nextToLast;
nextToLast = last;
last = answer;
}
return answer;
}
/* END */
int main( )
{
cout << "fib( 7 ) = " << fib( 7 ) << endl;
cout << "fibonacci( 7 ) = " << fibonacci( 7 ) << endl;
return 0;
}