We said in 1.5 that when writing a program, you start from an algorithm, which is the series of steps to solve your problem, and can be written in pseudo code. For instance, to solve the following problem:
You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original?
you can use this algorithm (written in pseudo code, of course there are other ways):
Start: year = 0, rate=0.05, balance = 10,000 Repeat steps below until balance reaches 20,000 Add 1 to the year value; Compute the interest as balance x 0.05 (i.e., 5 percent interest); Add the interest to the balance Print the final value of year
1. Suppose your cell phone carrier charges you $29.95 for up to 300 minutes of calls, and $0.45 for each additional minute, plus 12.5 percent taxes and fees. Give an algorithm to compute the monthly charge from a given number of minutes. What should replace "?" in the following pseudo code?
Start: set number of minutes to x; If x ? 300 then charge = 29.95 else charge = 29.95+(x-300)*0.45 set tax = ? * charge (i.e., 12.5% ) set total charge = ? Print out total charge
2. Consider the following pseudo code for finding the most attractive photo.
Line up all photos in a row; Pick the first photo and call it "the best so far"; For each photo in the row, repeat the following till reach the end of row: If it is more attractive than the "best so far": discard "the best so far" call this photo "the best so far" else do nothing (well, it's okay to omit this line) Move to the next photo The photo called "the best so far" is the most attractive photo
Is this an algorithm that will find the most attractive photo? Can you modify this algorithm to find the most ugly photo? Donald Trump's photo? the biggest number? the smallest number?
3. Write an algorithm to create a tile pattern composed of black and white tiles, with a fringe of black tiles all around and two or three black tiles in the center, equally spaced from the boundary.
The inputs to your algorithm are the total number of rows x and columns y. (x=7, y=9 is shown here. You can try x=6, y=8 or x=4, y=5, see how the pattern will change)
4. Given an integer, print out each digit of that integer.
5. Given a 16-digit credit card number, print out the sum of all digits.