Sams Teach Yourself C++ in 21 Days

(singke) #1
int i; //declare outside the for loop
for (i = 0; i<5; i++)
{
std::cout << “i: “ << i << std::endl;
}

i = 7; // now this is in scope for all compilers
return 0;
}

Summing Up Loops ............................................................................................


On Day 5, you learned how to solve the Fibonacci series problem using recursion. To
review briefly, a Fibonacci series starts with 1, 1, 2, 3, and all subsequent numbers are
the sum of the previous two:
1,1,2,3,5,8,13,21,34...
The nth Fibonacci number is the sum of the n-1 and the n-2 Fibonacci numbers. The
problem solved on Day 5 was finding the value of the nth Fibonacci number. This was
done with recursion. Listing 7.15 offers a solution using iteration.

LISTING7.15 Solving the nth Fibonacci Number Using Iteration
1: // Listing 7.15 - Demonstrates solving the nth
2: // Fibonacci number using iteration
3:
4: #include <iostream>
5:
6: unsigned int fib(unsigned int position );
7: int main()
8: {
9: using namespace std;
10: unsigned int answer, position;
11: cout << “Which position? “;
12: cin >> position;
13: cout << endl;
14:
15: answer = fib(position);
16: cout << answer << “ is the “;
17: cout << position << “th Fibonacci number. “ << endl;
18: return 0;
19: }
20:
21: unsigned int fib(unsigned int n)
22: {
23: unsigned int minusTwo=1, minusOne=1, answer=2;
24:

196 Day 7

Free download pdf