View this PageEdit this PageAttachments 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 - Matthew Plowden

Reading Code

| anArray aString |
anArray := #('abc' 'def' 'ghi','jkl'). "There shouldn't be a comma here."

aString := ''.
anArray do: [:each |
aString := aString, each.].
Transcript show: aString.

1. What appears on the Transcript ?

The loop will go through each element of the array, concatenating all of the elments into one string, then will print it out.

The transcript will show:
abcdefghi,jkl

2. How many times did the do: loop get executed?

The do: [:each] operator makes the loop execute once for each element of the array that it is called on.
Since there are 5 elements in the array, the loop will execute 5 times, once for each element.


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


3. How many times does hello get printed in this example?

In this case, hello will print infiintely. This happens because test:= (i < 10) causes the variable test to be set to true since at the time this statement is executed, i is less than 10. Because of the way the assignment is used, the update of i inside the loop will have no effect on the condition of the loop. The way the loop is set up, it is equivalent to writing

[true] whileTrue: [Transcript show: 'hello'.].

which is clearly an infinite loop. Assuming the intent was to print hello 10 times, you would simply want to use the condition
[i < 10] and not use the assignment of the variable test.

Link to this Page