# Some Loop-Based Problems

Here are the exercises we did in class on Wednesday. As you attack each one, remember to think in terms of the kinds of patterns that could apply here. The ones we studied on Monday—counting, accumulator, and indefinite-but-terminating— are not the only ones you'll encounter. They do encompass a wide range of problems, however.

### Approximating the value of π

The number *π = 3.141592653589793 ...* can be approximated by the series

4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - ... = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - ... )

Write a program that takes an integer, *n*, as a command-line argument and prints the value of this series, with the first *n* terms computed. (SOLUTION: this is actually given as an example in Monday's notes. However, try to solve it on your own here, first.)

### Time to double an investment

Given an initial investment (and no further contributions) and an anual percentage rate, how many years will it take for the initial investment to double (or more) in value? Write a program to solve this.

### Factorial calculation

Write a program that takes a single integer argument, *n*. The program should print the value of *n!* which is

n! = n * (n-1) * (n-2) * ... * 2 * 1

(Note that 0! = 1, because that makes the rest of the math work out.).

This is another one that was solved in the class notes from Monday, 02/16, but do make sure you can solve it on your own.

### Fibonnacci sequencr

The first two numbers of the Fibonnacci sequence are 1 and 1. After that, the *n ^{th}* number is the sum of the previous two numbers: 1,1,2,3,5,8,13,21,34, and so on.

Write a program that takes a single integer argument, *n*. The program should print the *n ^{th}* number in the Fibonnacci sequence.

John Lasseter