110 likes | 221 Views
The LC-3 – Chapter 5. COMP 2620. Methods of Loop Control. Recall from last class, we designed a loop to implement the addition of 12 integers That is, a loop is a sequence of instructions that executed a number of times in repetition
E N D
The LC-3 – Chapter 5 COMP 2620 Dr. James Money COMP 2620
Methods of Loop Control • Recall from last class, we designed a loop to implement the addition of 12 integers • That is, a loop is a sequence of instructions that executed a number of times in repetition • The code the executes in the loop is called the body of the loop • Each time the loop executes, this is called one iteration
Methods of Loop Control • There are two common methods for controlling loops that are used in programming • You probably have seen both of these in your C/C++/Java courses in some form
Methods of Loop Control • The first method is the one we used last class • It requires a counter variables and the loop terminates when the counter variable reaches a certain value • That is, we execute the loop n times by setting a counter to n and decrementing each time
Methods of Loop Control • Then, we of course check to see when the loop counter reaches 0. • If it is not zero, we set the PC to the start of the loop and continue with another iteration • Alternatively, we could start the loop counter at 0 or 1 and increment up to n
Methods of Loop Control • The second method of loop control is called a sentinel • This is usually used when we do not know ahead of time how many iterations we need to run • We choose a value that can never occur in processing to indicate termination of the loop • This value is called the sentinel
Methods of Loop Control • For a sequence of positive numbers this could be a negative value • For a list of pointer values, it could be NULL value for the current pointer • When we find this value, the loop terminates
Sentinel Example • We consider a similar example to adding the 12 integers, but this time we assume the numbers are all positive • In this case, we could choose any negative value for the sentinel • As convention many times, we choose the number -1
Sentinel Example • Pseudocode: • addr= 0x3100 • sum=0 • Load value from memory[addr] • Is value the sentinel? – if yes, end loop • Sum=sum+value • addr=addr+1 • Load value from memory[addr]