(Fibonacci Series) The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, ... begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms. (a) Write a nonrecursive function fibonacci(n) that uses type int to calculate the nth Fibonacci number. (b) Determine the largest int Fibonacci number that can be printed on your system. Modify the program of part (a) to use double instead of int to calculate and return Fibo- nacci numbers, and use this modified program to repeat part (b).

What will be an ideal response?


```
// Nonrecursively calculate Fibonacci numbers.
#include
using namespace std;

int fibonacci( int ); // function prototype
int main()
{
// calculate the fibonacci values of 0 through 10
for ( int counter = 0; counter <= 10; counter++ )
cout << "fibonacci( " << counter << " ) = "
<< fibonacci( counter ) << endl;

// display higher fibonacci values
cout << "fibonacci( 20 ) = " << fibonacci( 20 ) << endl;
cout << "fibonacci( 30 ) = " << fibonacci( 30 ) << endl;
cout << "fibonacci( 35 ) = " << fibonacci( 35 ) << endl;
} // end main

// fibonacci nonrecursively calculates nth Fibonacci number
int fibonacci( int n )
{
int fib0 = 0; // after iteration, holds fib(i-1), initially fib(0) = 0
int fib1 = 1; // after iteration, holds fib(i), initially fib(1) = 1
int temp; // temporary holder for updating fib0 and fib1

if ( n == 0 ) // special case if n is 0
return 0;

// loop until nth number reached
for ( int i = 2; i <= n; i++ )
{
// note at this point:
// fib0 = fib(i-2)
// fib1 = fib(i-1)

temp = fib1; // temporarily hold fib(i-1)

// update fib1 to hold fib(i), fib(i) = fib(i-1) + fib(i-2)
fib1 = fib0 + fib1;
fib0 = temp; // update fib0 to hold fib(i-1)

// note at this point:
// fib0 = fib(i-1)
// fib1 = fib(i)
} // end for

return fib1;
} // end function fibonacci
```

Computer Science & Information Technology

You might also like to view...

A program written in Java will run on any computer on which Java has been installed.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology

You can type comments to yourself in the ____ for a specific slide while working in Normal view.

A. Slide pane B. Notes pane C. Theme pane D. Navigation pane

Computer Science & Information Technology

The purpose of the Dock is to give you quick, easy access to the most frequently used items on your computer.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology

It is easier to add fields to new or existing tables in Datasheet view.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology