Download presentation
Presentation is loading. Please wait.
Published byMartin Kaufer Modified over 5 years ago
1
TM111 Introduction to computing and information technology 1
Block 2 Part 4 Loops
2
Introduction All programming languages include structures for causing instructions to be executed repeatedly. such structures are known as loops There are three general types of loop: loops whose contents execute a fixed number of times loops whose contents execute indefinitely (potentially forever) loops whose contents execute repeatedly dependent on some Boolean condition. You have already encountered the first two types of loop in the form of the OUBuild looping blocks repeat[ ] { } and forever{ }. You will be introduced to loops that are controlled by a Boolean condition, known as conditional loops. Do Activity 4.1 (exploratory) involving conditional loops. the block repeat_until< > { } These blocks are run repeatedly until the condition that is in the repeat_until<>{} block’s input box reports 'true' – that is, until the finish line is reached.
3
4.1 Forever loops and conditional loops
The forever{ } block, refer to as a forever loop. See activity 4.2 To stop use the stop[ ] block And use the if< >then{ } block with Boolean condition Ex. In the define[ ] script define number of iterations (i) to 10. Means i = 1 ; in OUBuild define[i=1] Now, repeat i*1 The code will be: repeat_until i=10 { i * 1 } This will repeat the multiplication 10 times. You can expect the result will report numbers from 1 to 10 as follows: OUBuild implements loops that execute forever with the forever{ } block forever{ } is a foot block: nothing can be attached underneath it. It runs indefinitely, therefore no code can sensibly follow it. As its name suggests, the blocks inside a forever{ } block’s jaws – the loop contents – are repeatedly run, indefinitely. A flow chart illustrating the forever{ } block is very simple, as follows:
4
Suitable incorporation of a stop[ ] block into a program enables a forever loop to be stopped intentionally as an aspect of a program. stop[ ] blocks can be used to control the execution of scripts within a program. A stop[ ] block takes one of three possible input values, as follows: all: stops all scripts in the program this_script: stops just the script that contains this block other_scripts_in_sprite: stops all other scripts in the sprite concerned, except the one that contains the stop[ ] block.
5
4.1.2 Conditional loops In Part 3 you met Boolean blocks and their use as Boolean conditions for if< >then{ } and if< >then{ }else{ } blocks. Loops that work like this are called conditional loops. The repeat_until< >{ } block instructs OUBuild to keep executing its contents – the blocks between its jaws – until the Boolean condition reports 'true'. When OUBuild encounters a repeat_until< >{ } block, it first checks the value of the Boolean condition. If it is 'true', then the loop contents are not run at all and OUBuild moves on to any blocks after the repeat_until< >{ } block. If it is 'false', the loop contents are run, from the first block to the last, and then OUBuild again checks the value of the condition. If it is now 'true', then the loop contents are not run again and OUBuild moves on to run any blocks after the repeat_until< >{ } block; if it is 'false', then the loop contents are run again, and so on. Before each potential run of the loop contents, OUBuild checks the condition to determine whether or not to run the loop contents.
6
Depending on the precise requirements, it can therefore be necessary to consider carefully:
whether and how to ensure that loop contents are run at least once – that is, that the loop’s condition reports 'false' initially whether and how to ensure that loop contents are not run indefinitely – that is, that the loop’s condition reports 'true' at some point. DO Activity 4.3 Ex. Find the mean (average) of two numbers: a and b and report it in Av. Follow the figure of repeating inputs as shown above and continue as what you have learn in meeting two. The steps are: Enter the two variables a and b Make a temporary summation s as follows: s = a + b Calculate the average Av as follows: Av = s / 2 Do rounding if necessary. Report the result Av. Do activity 4.4 and exercise in Activity 4.5
7
repeat_until ( (m<=5) ) { m = m + 1 }
TEST Question 1 For the following algorithm: input m if m<0 then { m = -m } repeat_until ( (m<=5) ) { m = m + 1 } What is the value of (m) to skip the loop? What is the value of (m) to enter the loop only once? Answer A: any value m>5 or m<-5 B: m = 5 TEST Question 2 What will the following algorithm print? repeat[5] { repeat[3] { print(“*”) } Answer: it will print the folowing: * * *
8
4.2 Fixed loops and string processing
the repeat[ ]{ } block, which refer to as fixed loops. runs the blocks inside its jaws – the loop’s contents – a specific number of times, given by the value in its input box, which should be a non-negative integer. Once the contents have been executed the specified number of times, the execution moves on to the next block, as illustrated in the flow chart: The repeat[10] as in the figure repeats the loop ten times. The fixed number is determined in advance of the program running. We will use the term iteration to refer to a single run of the loop contents
9
4.2.2 String processing Text processing refers to the manipulation of text – words – by a computer. Text may need to be manipulated in many different ways. Think of a word processor, for example, which, given a piece of text, might: search for the first occurrence of a specific word or character replace every occurrence of a specific word or character with another insert a character according to a particular rule, for example, a space after each full stop search for all invalid ‘words’, that is, words that don’t appear in a dictionary Do Activity 4.8 A variable such as position is known as an index variable, so called because it is used to index or provide access to an individual item of data within a collection. Here, the characters within a string are accessed in turn using their successive positions within the string. We say that an index variable enables a program to iterate over a string – that is, to repeatedly step through the string’s characters, processing them one by one.
10
the looping block that is used, repeat[5]{ }, has input value 5, this script only works with words of five letters. (Try entering words of different lengths to see why.) With length_of[word] as the loop’s input value, the number of iterations is the same as the number of characters in the user’s word. The iterations work just as before, except that they now process all of the characters in the input word, however many there are. At the end of looping a string, the value of position increases beyond the final position in the word. At that point, the block letter[position]of[word] reports the empty string (‘ ‘) and the loop condition reports 'false'. Then you can stop looping. An index variable enables different iterations of a loop’s contents to process different items of data within a collection. The basic idea of using an index variable to iterate over a string’s characters one by one is quite easily adaptable with a bit of imagination. For example, a simple adaptation of the technique enables iteration to start at a character further on in the string or finish at a character before the final one. Whenever it is required to process characters in a string in some regular, predictable way, a loop in conjunction with an index variable is often the way to proceed. DO Activity 4.9 and Activity 4.10
11
4.3 List processing Strings and lists have much in common.
A string is a sequence of characters, each at a numbered position. A list is a sequence of data items (numbers or strings), again each at a numbered position. You have seen that OUBuild provides some similar blocks for each, for example: there is a block that reports the length of a string, and there is a block that reports the length of a list there is a block that reports the character at a specific position in a string, and there is a block that reports the item at a specific position in a list. Create a List sentence and by using the add[ ]to[ ] block we don't know how many words the user will want to enter? Instead, you can use this with a repeat_until< >{ } block in conjunction with what is known as a sentinel value. This is simply a value used to indicate that the loop should end. If the user enters this value to indicate that they have no more words to enter, the loop stops; the loop continues until the sentinel is entered. Ex. repeat_until word = “Q” { … } Q is the sentinel value.
12
Example: Enter “tea for two”
13
You can change the list, replacing each occurrence of a word by another using the replace[ ]by[ ] block, and then use sentence itself in the display. A list allows a collection of data to be stored together and processed together. Loops can be important tools in enabling user input to be stored in lists and also in processing data held in lists. Of course, just as with strings, considerable variation is possible. For example, a list may be iterated over in reverse order by using an index variable whose value decreases. Parallel lists are lists such that each item in one list is related in some way to the item in the same position in the other list. Do Activity 4.12 (self-assessment)
14
4.3.2 Numerical processing with lists
Once a list holds a collection of numbers, the numbers can be processed, and looping techniques are often useful. It might be required, for example, to: find the largest number in the list, or the smallest find the mean (average) of the numbers list the numbers in order, from smallest to largest. Important : explore Activity 4.13 Ex. In a supermarket, suppose you are adding up your list of items so as not to exceed your budget limit. Having a list of items that must buy, you may give priority to some items and remove others when necessary. (use the block change[ ]by[ ] to add to total_budget the number at the current position)
15
The change[ ]by[ ] block provides a simple way of increasing or decreasing a variable’s value, but it would be possible instead to use the [ ]+[ ] block How can the smallest (in other words, the lowest, or minimum) number in a list be found by iterating over the numbers in the list? can be found using the following strategy: Set a variable, smallest_number, say, to the first number in the list, as is done in the incomplete script. Compare the second number in the list with the value of smallest_number; if the second number is less than the value of smallest_number, set smallest_number to the second number. Compare the third number in the list with the value of smallest_number; if the third number is less than the value of smallest_number, set smallest_number to the third number. Continue in this manner to the end of the list. Note that the iterations – the repeated comparisons – should start at the second number in the list, and to get from there to the final number in the list, there must be n – 1 iterations, where n is the length of the list.
16
List techniques The idea of iterating over a list using an index variable is fundamental to processing data in lists, and can be applied in many circumstances. Lists as databases In OUBuild, lists enable the user to maintain simple databases. Parallel lists enable relationships between collections of data to be maintained, Activity 4.14 (exercise) To convert from a temperature in Celsius to one in Fahrenheit, you multiply by 1.8 and then add 32. So the formula for converting a temperature, c, in degrees Celsius to the equivalent, f, in degrees Fahrenheit is f = 1.8 × c + 32.
17
4.4 Problem-solving with loops
We could express sentences to use terms and thus give a clearer steer to repetition in an algorithm. Examples: Repeat (length of list) times • Input the age of the child with the current name • Input the address of the child with the current name Repeat (length of password) times • If the current item is the space character, then add 1 to the count Repeat until (the running total is at least 100) • Add the current number to the running total Repeat forever • Play the music Repeat until (space character found or length of word exceeded) • Move to the next character Important: Do Activity 4.15 (exploratory)
18
Common repetition errors
If a test fails, then, in trying to trace and fix a bug, it is useful to bear in mind common errors that tend to be made in programs of the sort we are testing. Three kinds of error specific to repetition are: a loop condition is incorrect data involved in a loop condition is not changed correctly within the loop’s iterations an index variable is not changed correctly within the loop’s iterations or is not initialized correctly. These sorts of error can lead to various problems, such as: a loop not executing at all when it should, executing indefinitely when it shouldn’t, accessing the wrong item, or attempting to access a non-existent item in a list or string. Small slips in creating a loop condition or in manipulating an index variable often lead to either the first or last item being processed incorrectly whilst the other items are processed correctly. Do Activities (exploratory) to Activity 4.19
19
Have a nice day.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.