Itteration | |||||||||||||||||||||
Iteration is one of the most key elements of programming. There are many situations where it is desirable to perform multiple tasks numerous times. For example imagine an algorithm which works out the following pattern. 2,4,6,8,10,12,14,16. Clearly this is just the two times table. We want an algorithm which will print out all the numbers in the two times table for the first n terms as shown in the table below.
So the algorithm, given the value 4, should produce 2,4,6,8. Given the value 6 should produce 2,4,6,8,10,12 and so on. As the number N could be any number, it is impossible to list out all of the instructions. Here is what the code may look like if we tried.
Given N as 1,2 or 3 this algorithm will produce the correct result (try it!). However what about for N=4? We could add another IF statement but then we will be faced with the same problem for N=5. Clearly this is not a good algorithm. What we can do is use a special construct known as a FOR loop. A FOR has the form
The start value is the start of the loop, the first value the loop will act on. The end value is the last value the FOR loop will work on. Clearly we need a variable to keep count of which iteration we are currently working on. Lets look at the twosTable algorithm as a FOR loop.
This looks much simpler. Let's run through a trace. START N = 4 PRINT I=1 * 2 First iteration PRINT I=2 * 2 Second iteration PRINT I=3 * 2 Third iteration PRINT I=4 * 2 Forth iteration STOP So we pass in 4. The first iteration the variable I becomes 1. The next l line says PRINT I * 2, so that becomes PRINT 1 * 2. We then come to the line END FOR. At this point you must check if the final value has been reached. It does the check I = N. 1 does not equal 4 so it goes back to the start of the FOR loop and adds 1 to I. So the next time we get to PRINT I * 2 we will run PRINT 2 * 2. The psuedocode version of for loops looks a bit different for i=start to en As there are no hard and fast rules for pseudo code, it may be possible that you see different versions of the FOR loop. However they will always act the same. You should be able to work through a FOR loop by identifying.
|