CSC 180 Notes for Tutorial #2 To be given week of 23rd September Monday 23 Sept Wednesday 25 Sept ============ Notes for the tutorial ============================================ AN ALGORITHM FOR COMPUTING FIBONACCI SEQUENCES =============================================== Problem ======= The following sequence of numbers, called the Fibonacci sequence, 1 1 2 3 5 8, 13, 21, ... has the property that each term after the first two terms is the sum of the two proceeding terms. Develop an algorithm to generate the first 50 terms of this sequence. Solution ======== Work them towards something like: termA = 1 print termA termB = 1 print termB set i to 2 repeat as long as i < 50 ( <-- mention that 50 is a "constant" ) i = i + 1 termC = termA + termB print termC termA = termB termB = termC end repeat Try to work with their suggestions - and if they are wrong, try to get them to figure out what is wrong with their ideas. Motivate: the use of counters in a loop, the fact that we don't need to store all of the computed terms in their own variables - only the two needed for the next calculation, how we need to update the variables at the bottom of the loop in preparation for the next iteration. Get them to figure out the termination conditions for the repetition. Point out that in the repetition, some of the statements are "for the current iteration" in the repetition and some of the statements "prepare for the next iteration." Please perform a trace of the algorithm that you develop. I haven't done tracing yet in class, so go very slowly for at least 3 iteration so that they can see the "flow" through the variables i, termA, termB and termC. Using formats with scanf and printf ==================================== Problem ======= Write a program that formats product information entered by the user. A session with the program shoud look like this: Enter item number: 583 Enter unit price: 13.5 Enter purchase date (mm/dd/yy): 10/24/95 Item Unit Purchase Price Date 583 $ 13.50 10/24/95 (The item number and date should be left justified; the unit price should be right justified. Allow dollar amounts up to $9999.99. Hint: Use tabs to line up the columns.) A solution ========== /* Program to demonstrate the use of formats for Input/Output. */ int main() { int itemNumber; double unitPrice; int month, day, year; /* the purchase date */ /* Prompt for and get the item number. */ printf("Enter item number: "); scanf("%d",&itemNumber); /* Prompt for and get the unit price. */ printf("Enter unit price: "); scanf("%lg",&unitPrice); /* Prompt for and get the purchase date . */ printf("Enter purchase date (mm/dd/yy): "); scanf("%d/%d/%d",&month,&day,&year); /* Print out the given information in a formatted table. */ printf("Item\t\tUnit \t\tPurchase \n"); printf(" \t\tPrice\t\tDate \n"); printf("%-d \t\t$%7.2f\t%2d/%2d/%2d\n", itemNumber, unitPrice, month, day, year); return 0; }