Indeed, print
prints a newline. princ
does not.
To further control how you print stuff, there is format
. It works with directives that start with ~
. Thus, ~a
(or ~A
) prints the object given as argument æsthetically. ~&
prints a newline.
(format t "~a~&" 'a)
t
is for *standard-output*
.
See https://lispcookbook.github.io/cl-cookbook/strings.html#structure-of-format
This link also explains how to align strings to the right or to the left, which you might need (if you go the format route).
You can make your code shorter. There is make-string count :initial-element character
that can replace the loop. A character is written #\a
.
Also you could call triangle recursively only if k is > 0 (zerop
). With this and (format t "~a~&" (make-string k :initial-element #\a))
, my version has only one call to the print function and less “if” machinery:
(defun my-triangle (k)
(format t "~a~&" (make-string k :initial-element #\a))
(unless (zerop k)
(my-triangle (decf k))))
CLICK HERE to find out more related problems solutions.