Create a recursive function to print a multidigit number vertically. For example, 2378 should be printed
2
3
7
8
Test your program with numbers of different length.
Create a recursive function to print a multidigit number vertically. For example, 2378 should be printed
2
3
7
8
Test your program with numbers of different length.
in haskell because thats probably not what your assignment is in and it will not be helpful
print_num = print . unlines . map show . vertnums
vertnums n =
let (d,m) = divMod n 10
in case d of
0 -> [m]
x -> vertnums x ++ [m]
more code golf
toString c = [c]
print_num = print . unlines . map toString . show
this also works, i was surprised
print_num = print . unlines . map return . show
In quick-and-dirty python:
def recursive(x):
if x > 10:
print recursive(x/10)
return x%10
Ruby, 5 lines ... Oh wait, this isn't code-golf
#!/usr/bin/ruby
def rp n
rp n / 10 if n >= 10
puts n % 10
end
rp ARGV[0].to_i
Clojure, your instructor will love it, trust me
(defn rp [n]
(if (>= n 10)
(rp (quot n 10)))
(println (rem n 10)))
nroff, a job-interview must-have, oh wait...
.pl 1
.de f
. if \\$1>=10 \{\
. nr t \\$1/10
. f \\nt
. \}
. nr t \\$1%10
\\nt
. br
..
.f 2378
PostScript
/print_vertically {
% Init all stuff
/Palatino-Roman 12 selectfont % Long live Hermann Zapf!
24 720 moveto % Sounds like a safe place to begin printing, for A4 or letter
0 14.4 rmoveto % little trick to start 1 line higher than we will print
doprint_vertically % call the main routine
showpage % We're done!
} def
% The main routine
/doprint_vertically {
currentpoint exch pop 14.4 sub 24 exch moveto % move down one line
dup 10 mod 1 string cvs show % compute remainder mod 10 and print 10
10 idiv dup 0 ne % compute quotient
{ doprint_vertically } % if quotient != 0, recurse
{ pop } % else, clean up the stack
ifelse % Never got to devise a satisfactory coding style for PostScript...
} def
SO's pretty printer is really bad at displaying PostScript code... not really surprising ;-)
Brainfuck:
[>,----------][<][>[++++++++++.[-]++++++++++.----------]]
That's about as recursive as I can get it.