In programming related on-line communities, sometimes students come asking for solutions to their programming problems.
Sometimes we like to be very helpful.
Recently, in the Not Just Tiny-C Facebook group, we had a pair asking for help writing a C program to make right triangles using (monospaced) character output on a terminal console, something like this:
Part of their assignment was to use a do while C loop.
Part of their assignment was to get the size of the triangle from the terminal input.
We gave them a few hints. And I refrained, at the time, from giving them the trivial tutorial solution in Forth. (This is a traditional tutorial problem, you see.)
Well, here is one typical version of the traditional trivial solution in Forth, with some tests mixed in to help the uninitiate.
Forth handles the conversion from terminal input to numeric for you. So that part of the solution is opaque.
And I used the traditional Forth counted loop instead of the Forth do while loop. (Forth do while loops don't translate to C do while loops unless you know both pretty well, anyway.)
(Tested in gforth and fig-Forth. Copy and paste, it should run as-is in quite a variety of Forths.)
: star ( --- ) ( Very traditional tutorial word! )
42 emit ;
: stars ( n --- ) ( Refining tradition a little. )
dup 0 > 0= if
: bracket ( n --- )
star dup 2 < if
2 - spaces star
: triangle-bottom ( n --- )
cr dup 1 > if
dup 1 do
i bracket cr
stars cr ;
: triangle ( n --- )
dup 0 > 0= if
Now isn't that just more fun than you've had all week?