Lesson+7

**LESSON 7** //**Repetitive structures: Counters and Accumulators**// **//Counters//** OK. Most of you have been using counters since the animation assignment. When one needs to count how many times a program executes a loop (without using a counted loop), one uses a counter. Counters need two things in order to function: 1) **an Initial Value**, and; 2) **an Incremental Value**. The initial value is usually (but not always) zero, and must be located outside the loop. It tells the program what number to begin counting at. The incremental value, on the other hand, tells the program what to count by (one's usually, but it could be any number) and must be located inside the loop. Try this:

**%Program to count ten passes through a conditional loop** **var counter: int:=0** **loop** ** counter:= counter +1 ** **put counter, " "..** ** exit when counter = 10 ** **end loop**

Try changing the increment from 1 to 2. What happens? **//Accumulators//** Accumulators are identical to counters with one difference. While they must have both an initial value and an incremental value; //**the incremental value is determined by a variable**//. Accumulators are used to keep a running total of numbers during successive passes through a loop. Try this:  var answer: string var gasbill, totalbill: real var billnumber:int:=1 totalbill:=0 loop put "Enter the value of gas bill number ", billnumber, "." put "Type 0 to exit program." get gasbill if gasbill = 0 then put "Are you sure? (Y/N)" get answer exit when answer = "y" or answer = "Y" end if totalbill:= totalbill + gasbill billnumber:= billnumber +1 end loop put "You had ", billnumber - 1, " gas bills." put "they totalled ", totalbill, " dollars."

//** Task: **// 1) Modify task 5.2. When the user is finished with the quiz, the program will output the number of correct and incorrect answers, with their percentages in graphical form.

2) Create a program which will calculate interest for an investment. The user will provide the term (length in years) of the investment, the interest rate (% interest calculated annually), the amount of the investment, and the compounding period (how often the interest is awarded). The program will allow four possible compounding periods (Annual, Monthly, Weekly, Daily). The program will output a table displaying term, interest rate, amount, interest awarded, and total amount as headings. It will allow the user to choose the reporting period (i.e., what has happened each day, or week or month or year). Limit each page of output to 24 lines. Allow the user to advance to the next page by pressing any key.