| Basic Smalltalk terminology. Simple message expression. Using LearningWorks. Programming Tutorial. |
|
Home
Tutorials | 1. Starting Smalltalk, and Terminology | 2. Precedence Rules | 3. Classes - Strings | 4. Class Browser | 5. Variables | 6. Error Messages | 12. Control Structures | 16. Dialogs | 23. Collection class | 39. OpenGUI | Information | Smalltalk Books | Student Software & Books | Hints & Tips | Sites | Download Smalltalk | Coloured code | Feedback | Download Documents | ASCII Codes | M206 & Smalltalk Index |
|
| Updated 10 June01 |
IntroductionStudents who have programmed in other languages will find this tutorial fairly easy. Students new to programming MUST ensure that they understand how the control structures of iteration (loops) and decision making (branching) work. In order to help new students, I have written a lesson showing how these structures work in English, with an example of making a cup of coffee. New students should click on this link, Loop and Decision Structures, read this extra lesson then click your browsers back button to return to this tutorial number 12. For the exercises in this lesson. Start the LearningWorks
program provided by the OU (Open University) M206 course. Use
either LearningBooks LB 12, 13 or 14. Up to now all the expressions that have been used have been executed one after the other, in the order that they were written, top to bottom. They have consisted of:
Question 1. What punctuation
is used to separate the expressions in an expression series? Question 2. What punctuation is used to separate the messages in a cascading expression? Go to Answer 2. Question 3. What is the difference between an expression series, and cascading messages? Go to Answer 3.
In order to make computers do more than execute such very simple programs you require methods that will allow you to:
Conditional Expressions Conditional Expressions sometimes called Boolean Conditional
Expressions return a boolean answer of either true
or false.
Note that the parenthesis surrounding a conditional expression is optional. The course convention is to use parenthesis.The use of parenthesis along with indentation makes code easier to read. This in turn means that it is easier to debug if it is not working.
Comparison Operators
Messages that answer true or falseThe following message selectors are in a way comparing. They answer with either true or false, and therefore can be used as a boolean conditional expression, with our control messages that follow in this tutorial.
BlocksMost of the messages that you are going to look at in this lesson use blocks. A block of code is enclosed in square brackets [ ] . The brackets are required, they mark the start and end of the block.
Tips when using blocks, especially if you have nested blocks.
Use of PeriodsIn the following methods, pay special attention to periods, especially where they are NOT needed. As the code starts to get more complicated, students appear to forget the basics.
Decision makingSometimes called Conditional Logic.
ifTrue: ifFalse: ifTrue:ifFalse: ifFalse:ifTrue: whileTrue: whileFalse:
ifTrue: and ifFalse:
ifTrue:ifFalse: and ifFalse:ifTrue:
Question 4. In the example ( 4 = 4 )
ifTrue: [ ^true ] .
What does the caret do?Go to Answer 4.
Question 5. In the example ( 'a' = 'a' )
ifTrue: [ ^true ]
ifFalse: [ ^false ] .
^'Another answer'
State why the 3rd answer 'Another answer' could never be returned. Go to Answer 5. How to obtain a 3rd answer is discused later in this tutorial. You will be coding how to return 1 of 3 different answers later in this tutorial. & (Logical AND)More complicated conditions can be created by combining more that 1 condition using the boolean operators AND or OR. In smalltalk & is used for AND. The general formats for using & is ( (condition 1) & (condition 2) )
ifTrue: [ "Code here is evaluated only if both conditions are true" ]
ifFalse: [ "Code here is evaluated only if either one or both conditions are false" ] .
| (Logical OR)In smalltalk | is used for OR. On UK keyboards the | key is usually the key to the left of the Z key, it is used in conjunction with the shift key. The symbol marked on the key usually has a small gap in the middle of the vertical line. The general format for using | is ( (condition 1) | (condition 2) )
Summarised RulesWhen using & (logical AND) both must be true to produce a true answer. When using | (logical OR) either or both must be true to produce a true answer. In both the above anything else is false. Question 6. In the following table, look at the boolean conditions . Work out whether condition 1 and 2, are true or false and enter your answer into their respective columns.. Looking at these 2 results you have entered, and noting whether the expression is an AND or an OR structure. Use the Summarised Rules to work out the answer that will be returned in the last column
Go to Answers 6. The comparisons above have all been very simple. Normally conditional expressions use either 1 or 2 variables or objects. Examples ( numer1 < number2 ) ( number3 >= 5 ) ( frog1 = frog2 ) ( aLetter < 'm' ) This makes it harder to see whether the expression will answers with true or false. The value of the variable must be worked out. Exercise 1a. Using &, ifTrue:ifFalse. Testing Code. The following code using the logical AND and the variable age. The code checks if the the age is within the teenager age group 13-19, and 1 of 2 answers is returned. Question 7a. Work out what answer will be returned? "T12. Exercise 1 (a) Using &, ifTrue:ifFalse"
|age|
age := 24.
( (age >= 13) & (age < 19) )
ifTrue: [ ^'You are a teenager' ]
ifFalse: [ ^'You are NOT a teenager' ] .
Go to Answer 7a.Copy the above code and its "T12. Exercise 1a. Using &, ifTrue:ifFalse" comment, and paste it into the workspace. Evaluate it, check that the correct answer is returned, then Test the Code.Question 7b. List the ages that you would use to test this code is working correctly. Go to Answer 7b. Check that the code is working correctly by changing the age of 24 and evaluating with the different ages given in the Answer 7. Go to Ex.1a. test results. correct the following section of code (age < 19)to (age <= 19)Well done if you had already spotted this error. Question 7c. Will (age <=19) produce the same results as (age < 20) Go to Answer 7c.
Test your code with 19.25. We are only dealing with integers at the moment, therefore we will leave the the expression at (age <=19). Later in this tutorial is a message that will check if an object is an interger. Later in the course you will learn how to program input checks into your code that will prevent an entry such as 19.25, '18', or 'twelve' etc.
Exercise 1b. Using &, ifTrue
Go to final solution Exercise 1b.
Exercise 1c. Obtaining 3 different answers. You are now required to write some code that will return 1 of 3 possible answers, using code from the previous solution as a start.
Exercise 1d. This is an alternative way of solving the problem, using a:- Nested conditional expression
Go to solution 1d Iteration. (Loops)Iteration in programming is to repeat a section of code repetitively. The code that does this is commonly called a loop. The loop structures allow you to execute a section of code a number of times and depending on the code this could be from 0 to infinitive.
timesRepeat:The message timesRepeat: executes a block of code a specified number of times. The format of the message is:number timesRepeat: [ block of code to be repeated ] can be any expression that results in an integer.
Exercise 2. Question 8 Examine the Code below. Without copying the expression into the workspace and evaluating, attempt the question that follows the code.
| total | total := 0. 4 timesRepeat: [ total := total + 1]. total a. What does the expression series do ? b. What is the answer returned ? Go to Answers 8.
Questions 9. The following information will aid you answering 8e and f, class is a unary message that can be sent to an object. Answers with the class of that object. E.g. 'abc' class would answer ByteString
In the expression 4 timesRepeat: [ total := total + 1].a. What is the receiver ? b. What is the message selector? c. What is the message? d. What is the argument? e. What is the class of the receiver? f. What is the class of the argument? Go to Answers 9. Now evaluate in the Workspace. Experiment by altering the number in front of times. Further experiment by altering the 1 to some other number, to change the increment value. Confirm your understanding of what this code does by these experiments.
Question 10. Examine the Code below. Without copying the expression into the workspace and evaluating, attempt the question that follows the code. | aNumber total count |
aNumber := 4.
total := 0.
count := 0.
aNumber timesRepeat: [ count := count + 1.
total := total + count ].
total.
It is normal to check the results of loops by a physical "step through" the code, checking how variables are changed, and performing any calculations, to ensure that results obtained by execution, are as expected from your "step through". This type of check should find any logical errors in your code. Calculate the answer that will be returned. You may like to try this now, before reading the following.
A brief description of what the code does is in the following table. If you are still stuck, then the second table shows you how it should be done.
A table similar to the table below is the ideal way to check results. The table has been been partially filled in, to help you. Complete the 5 remaining cells.
Exercise 3. Copy the code from question 10,into the Workspace and evaluate it.
If you are having difficulty understanding how the figures were worked out in the above question, you can amend the code as follows in the next 3 exercises. This is a technique that can be used if you are receiving unexpected results from the execution of code. Another useful technique is to step through your code using the debugger. Exercise 4a. Set the value of aNumber to 1 and evaluate. Note the answer which is the value of total. Check it against the value under total/After repeat 1in the table Exercise 4b. Repeat the above setting the value of aNumber to 2, then again with 3, and finally 4 Exercise 4c. Repeat the above exercises but amend the last line from total to count. Re-examine the code and note the following points.
whileTrue: and whileFalse:The general format for a whileTrue: expression is:[ a Boolean Condition Block ]
whileTrue: [ aBlock of code that is repeatedly executed while the condition remains true ]
The whileTrue: message allows you to repeatedly execute a [aBlock of code] while the preceding [Boolean Conditional Block ] evaluates to true.
The general format for a whileFalse: expression is: [ aBooleanConditionBlock ]
whileFalse:[ aBlock of code that is repeatedly executed while the condition remains false ]
Tip. When writing your code care must be taken to avoid producing an endless loop. Note in the following example whileTrue:, how the value of a variable, count used in the [ Boolean Condition Block ], is incremented within the [ Block of code that is repeatedly executed ]. This alteration of the variables value, should eventually reverse the true/false value of the Boolean Condition Block, thus ending the loop. You must be careful that you think carefully whether you increment or decrement the value, often you do both, one in the whileTrue block, and the other in the whileFalse block.
Exercise 5a Compare the 2 sets of code in the table below. The one using timesRepeat: you have just used. The new one using whileTrue: .
Go To Answer 11. Exercise 5b. Copy and paste the code to the workspace and evaluate to check the above answer. An expression series that can be written using the message selector timesRepeat: can also be written using the whileTrue: or whileFalse: message selector. and vice versa. Being able to convert between these constructions shows your understanding of them. Consequently the M206 OU course, usually has the students doing this in a TMA. LB 20 practical 2 has you doing this. Tip. Re study the code in the table above and ensure how they both work.
Exercise 5c. optimisation was not possible Now delete the [ ] from [ aNumber < 4 ] and execute the expression series. Note the exception message and add the Unhandled exception: optimisation was not possible message to your list Note you have a different version of this message for frogs in the list. Replace the brackets. This is another frequently made error.
Exercise 6. NonBoolean receiver Change [ aNumber < 4 ]to [ aNumber := 4 ]and execute the expression series. Note the exception message and add the NonBoolean receiverproceed for truth message to your list of error messages. Explanation. Writing code that does not answer with true or false will become a NonBoolean receiver. An assignment was used and a Boolean conditional expression was required .
The OU (Open University) M206 course uses additional loop methods, with thecollection Classes. These methods are: do: keysAndValueDo: detect: detect:None: and will be covered later.
AnswersAnswer 1.An expression series uses . (periods) to separate the expressions. Return to Question 1.
Answer 2. A cascading expression uses ; (semi colons) to separate the messages. Return to Question 2.
Answer 3. In a cascading message series only one receiver is written followed by a ; (semicolon). This is followed by successive cascading (consecutive) messages. In an expression series different receivers may be used, each expression being separated by a period. Each expression starts with a receiver. Return to Question 3.
Answer 4. Because the condition is true the caret forces true to be returned as the answer. Return to Question 4.
Answer 5. Both the ifTrue: and the ifFalse: blocks contain carets. Therefore one of these carets must be executed. A caret forces the return of an answer and the termination of the code. Return to Question 5.
Answers 6.
Answer 7a. 'You are a teenager' Return to Question 7a.
Answer 7b. 12, 13, 14, 18, 19, 20. These are the boundary values at both lower and upper limits of the "teenager" range i.e. 13 to 19 inclusive. Write down these numbers, you will need them in the next exercise. Return to Question 7b.
Answer 7c. 'If the input is an integer then the answer is yes, but no for a floating point number. Consider a teenager who is 19 years 3 months, and enters 19.25, an incorrect answer of 'You are NOT a teenager' will be returned. Return to Question 7c.
Answer 8. a.In the expression 4 timesRepeat: [ total :=total + 1].The code, total :=total + 1, is evaluated 4 times, the value of total being incremented by 1 on each repeat. b. 4 Return to Question 8.
Answer 9. a. 4 b. timesRepeat: c. timesRepeat: [ total :=total + 1] e. [ total :=total + 1] f. Evaluate this code in the workspace to find out 4 class. b. Evaluate this code in the workspace to find out | total | total := 0. 4 timesRepeat: [ total := total + 1 ] class. Return to Question 9.
Answer 10.
Answer 11. Yes Return to Question 11. Exercise SolutionsSolution Exercise 1a "T12. Exercise 1a and b Using &,ifTrue:ifFalse:"
Return to exercise 1a
Solution Exercise 1b. Correct Error. Insert a period at the end of the ifTrue: [ ^'You are a teenager' ] line "T12. Exercise 1b. Using 1 ifTrue:"
|age|
age := 24.
( (age >= 13) & (age < =19) )
ifTrue: [ ^'You are a teenager' ] .
[^'You are NOT a teenager' ] .
Return to exercise 1b to continue.
Final solution Exercise 1b. "T12. Exercise 1b. Using 1 ifTrue:"
|age|
age := 24.
( (age >= 13) & (age <= 19) )
ifTrue: [ ^'You are a teenager' ] .
^'You are NOT a teenager'.
Note the solution aboveis also required for the next
exerciseAnother possible solution would have been to place value after the final block "T12. Exercise 1e. Using 1 ifTrue:"
|age|
age := 24.
( (age >= 13) & (age < =19) )
ifTrue: [ ^'You are a teenager' ] .
[^'You are NOT a teenager' ] value .
Go to next exercise 1c
Solution Exercise 1c "T12. Exercise 1c. Using 3 ifTrue:'s"
|age|
age := 24.
( (age >= 13) & (age <= 19) )
ifTrue: [ ^'You are a teenager' ] .
(age < 13)
ifTrue: [ ^'You are too young to be a teenager'] .
(age > 19)
ifTrue: [ ^'You are too old to be a teenager'] .
Return to exercise 1c.
Solution Exercise 1d. "T12. Exercise 1 (d). Nested conditional expression"
|age|
age := 24.
( (age >= 13) & (age < =19) )
ifTrue: [ ^'You are a teenager' ]
ifFalse: [ (age < 13)
ifTrue: [ ^'You are too young to be a teenager' ] .
^'You are too old to be a teenager' ] .
Note
Return to exercise 1d.
| Previous Tutorial 3. Strings | Next Tutorial 16 Dialog Boxes | Top of Page |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||