Recitation 3: Counted Loops
Topics:
Patterns:
Objects:
C++ language:
System:
Exercises:
Overview:
These exercises let you practice simple counting loops. Remember to think about the problem first - specifying the task that has to be repeated, designing the counting method, figuring out what needs to be initialize, so the loop would start correctly, defining the update (counting) operation, and then designing the Loop Continuation Condition. To see the power of the counting loop we consider a number of different problems:
They first key idea is to separate setup tasks from the repeating task. The second key step is to understand how is each iteration step related to the proposed counting method. It helps to make a table of the iterations, writing on each line the values that are
are iteration-dependent. It may help you in discovering a pattern, designing a counting method, or designing the formula for computing iteration-dependent values.
Exercise strategies for student
The first ten exercises use just straight counting from one to some limit. There are two harder exercises in this set (exercises 5 and 10). Here you need to compute the total of some values that were used in the loop body. For this type of problems you must make sure that the variable that will keep the cumulative result is declared and initialized before the loop starts. In exercise 8 a variable that keeps track of the current total price of the purchase needs to be initialized to zero before the loop starts. It is incremented by the price of each purchase inside the loop and the final value is printed after the loop exit.
The next set of exercises uses more complex counting patterns. For each of these problems you should write down a table of values needed in the consecutive iterations of the loop and look for the relationship to the basic counting by one (either starting at one or starting at zero). Try to see if one of the patterns in the table of counting patterns applies. Then select the appropriate loop control and loop body formula for the desired values. It is important to work out a few example by hand to make sure your program will work correctly.
Exercise 11. shows three different methods that can be used when the task requires values that start at a value other that zero or one and increment by value other than one. Exercise 17 is another example of computing cumulative result.
Exercises:
Part 1: Solved problems
Simple counting:
Complex counting patterns:
* * * * *
* * * *
* * *
* *
*
x = xcenter + radius * cosdeg(a);
y = ycenter + radius * sindeg(a);