The First Two Programs
September 7, 2012
In their book The C Programming Language, Brian Kernigan and Dennis Ritchie say that the first program every programmer should write is a program that writes “Hello, world!” to the console. Then they give the second program that produces a fahrenheit/celsius temperature conversion table, with fahrenheit temperatures every 20 degrees from 0 to 300 and the corresponding celsius temperature to the nearest degree, each pair written on its own line with the two temperatures separated by tabs.
Your task is to write the first two programs. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
FORTH version. It’s actually a bit tricky to get the rounding correct when using integer math…
http://pastebin.com/0g8XeqxS
bulky version :)
Rather straightforward in Python.
This produces:
>>> hello()
Hello, world!
>>> temp_table()
0 -18
20 -7
40 4
60 16
80 27
100 38
120 49
140 60
160 71
180 82
200 93
220 104
240 116
260 127
280 138
300 149
Hello world is so dull I decided to do it three ways. It’s still dull.
The normal Haskell way:
main = putStrLn "Hello World"
The silly Haskell way:
main = mapM_ putChar "Hello, World\n"
The sillier Haskell way:
main = foldM (const putChar) () "Hello World\n"
The temperature one isn’t horrible:
main = mapM_ putStrLn [show f ++ "\t" ++ show c | counter <- [0..15], let f = counter*20, let c = round $ 5/9 * (fromIntegral $ f-32)]
Och, I forgot about a nice bit of Haskell syntax that really comes in handy here, making the table slightly shorter and substantially clearer.
main=mapM_ putStrLn [show f ++ "\t" ++ show c | f<-[0,20..300], let c = round $ 5/9 * (fromIntegral $ f-32)]
Silly me…. I can make it even slightly clearer:
main=mapM_ putStrLn [show f ++ "\t" ++ show c | f<-[0,20..300], let c = round $ 5/9 * fromIntegral (f-32)]
“me” gave a bulky version in Racket. Here’s a non-bulky one:
(do ((f 0 (+ f 20)))
((> f 300))
(display f)
(write-char #\tab)
(display (round (* (/ 5 9) (- f 32))))
(newline))
[…] doing, right? This time we have another two problems from Programming Praxis, aptly title “The First Two Problems“. The whole thing is based on the idea from Brian Kernighan and Dennis Ritchie that the first […]
I made a version for R7RS scheme: https://gist.github.com/3675478
I think I may have overdone it. The problem was easy enough, so I decided to make it a bit harder by drawing the characters to the screen using turtle graphics rather than just printing them. The lion’s share of the time was spent actually making the font, but I think it turned out relatively well.
Here’s the post: The First Two Problems @ jverkamp.com
Reblogged this on Garima Goswami.
(displayln “Hello, world!”)
;; An even-less-bulky Racket temperature converter
(for ([f (in-range 0 301 20)])
(printf “~a\t~a\n” f (round (* 5/9 (- f 32)))))
A Clojure solution: