1

I want to to display the numbers in the following format using smalltalk code

     1
     1 2
     1 2 3
     1 2 3 4

I wrote the following code

| i j y k |
i :=1.
j :=1.
y:= ('y' at: 1 put: $ )out.

(i<=4)ifTrue: [
i to: 4 by:1 do:[:i |


     (j<=i)ifTrue: [
     j to: i by: 1 do:[:j |

         ( j print++y print)out.

         ]
            ]

     ]
]

when i executed the above program, its displaying the numbers in following format

output:

1 ' '
1 ' '
2 ' '
1 ' '
2 ' '
3 ' '
1 ' '
2 ' '
3 ' '
4 ' '

can anyone please help me out in displaying the out in the pyramid format and way to get new line in smalltalk

Sampath Rudra
  • 21
  • 1
  • 4

3 Answers3

5

Try the following piece of code.

|n|
Transcript cr.
n := 4.
1 to: n do: [:i |
    1 to: i do: [:j |
        Transcript show: j].
    Transcript cr].

To answer your question: You get a newline by Transcript cr which will in turn send it to Character cr.

pintman
  • 61
  • 2
2

You could create a string with a single carriage return with

(String with: Character cr)

But you should learn how to use Stream rather than concatenating strings, see messages writeStream, #nextPut:, #nextPutAll: and class WriteStream

EDIT I didn't want to give a ready-made solution, but since you have many others, here is a possible one sticking with strings. I presume that #out generates its own CR as your question suggests. My own solution would then be to #inject:into: to accumulate rather tha re-create whole String at each loop:

(1 to: 4) inject: String new into: [:str :num |
    (str , num printString , ' ') out; yourself]

or with a traditional Transcript:

(1 to: 4) inject: String new into: [:str :num |
    | newStr |
    newStr := str , num printString , ' '.
    Transcript cr; show: newStr.
    newStr]

I hope it opens some perspective about higher level Collection iterators than dumb #to:do:

aka.nice
  • 9,100
  • 1
  • 28
  • 40
0
| max resultString |
max := 5 .
resultString := String new.
1 to: max do: [ :line |
    1 to: line do: [ :number |
        resultString add: number asString, ' '
    ].
    resultString lf.
].
resultString
User
  • 14,131
  • 2
  • 40
  • 59