When the number of iterations is pre-determined, such as counting to 10 we use:
Homepage Show
Accessibility links
BBC Account Notifications
More menu Search Bitesize Search Bitesize
BITESIZE
KS3 Iteration in programmingWhen designing programs, there may be some instructions that need repeating. This is known as iteration, and is implemented in programming using FOR and WHILE statements. Part of Computer Science Programming
quiz Test
Count-controlled loopsThere are two ways in which programs can iterate or ‘loop’:
Each type of loop works in a slightly different way and produces different results. Count-controlled loopsSometimes it is necessary for steps to iterate a specific number of times. Consider this simple algorithm for adding up five inputted numbers:
This algorithm would allow five numbers to be inputted and would work out the total. Because it is known in advance how many times the algorithm needs to loop, a count-controlled loop is used. curriculum-key-fact A count-controlled loop is used when the number of iterations to occur is already known. A count-controlled loop is so called because it uses a counter to keep track of how many times the algorithm has iterated. The pseudocode for this algorithm might look like this: total to 0
count to 1
FOR as long as count is in the range 1 to 5
INPUT user inputs a number
STORE the user's input in the number variable
total = total + number
Add 1 to count
OUTPUT "The total is " + total Steps that are part of the loop are indented. Indentation is used to show which steps are to be iterated. In this example, the variable ‘count’ is used to keep track of how many times the algorithm has iterated. This variable controls the loop. The algorithm will continue to iterate until the value of count has reached 5. As soon as count reaches 5, the algorithm stops iterating.
KS3 Subjects
Which loop is used when number of iterations are predetermined?For-loops are typically used when the number of iterations is known before entering the loop. For-loops can be thought of as shorthands for while-loops which increment and test a loop variable.
When the number of iterations are known we use?For loops are typically used when the number of iterations is known before entering the loop. For loops can be thought of as shorthands for while loops which increment and test a loop variable.
Which loop will be the best choice if you know that you need exactly 10 iterations from the loop?The while loop is always the best choice in situations where the exact number of iterations is known.
What are the 3 types of iteration?We will study three forms of iteration: tail-recursion, while loops, and for loops. We will use the task of reversing a list as an example to illustrate how different forms of iteration are related to each other and to recursion. A recursive implementation of reverse is given below.
|