View this PageEdit this Page (locked)Attachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide
Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

Discussion 4 - Oh Kil Kwon

From Summer 2001 Midterm Review

Reading Code
anArray aString

anArray := #('abc' 'def' 'ghi','jkl').
aString := ''.
anArray do: [:each |
aString := aString, each.].
Transcript show: aString.

Q What appears on the Transcript ?
A It will appear "abcdefghi,jkl". This is an array of String. If you want to have a space between each element, you can simply
put ' ' between aString and each in the loop.

How many times did the body of the do: loop get executed?
Since the array size is 4, it executed 4 times.

i test
i := 1.
test := (i < 10).
[test] whileTrue: [Transcript show: 'hello'.
i := i + 1.].

Q How many times does hello get printed in this example?
A Well, this will give you infinite loop. Since test object is initialized to 'true', it will always be 'true' in the loop. Therefore,
this will cause the codes run infinitely. In order fix this, there are many things we can do. We can put (i < 10) in front of whileTrue statement.
Or, we can even make (i < 10) a block and assign to test object. So, it will look like [ i < 10]. Remember, we can assign a block to a variable in Squeak.
So, now each element will be evaluated at each time(loop).

"Fixed version"
i test
i := 1.
test := [i < 10].
(test) whileTrue: [Transcript show: 'hello'.
i := i + 1.].

Now, this will print out 'hello' 9 times.(1 2 3 4 5 6 7 8 9)

Links to this Page