Rewrite printf with print

Hello,

using Printf
function twoTimesTable()
    for h = 1 : 12
        @printf("%2d x 2 = %2d\n", h, h*2)
    end
end # twoTimesTable
twoTimesTable()

How can I make this printf with print?

Thank you.

In this simple case you can manage the spacing manually

       function twoTimesTable2()
         for h = 1:12
           strh = string(h)
           out = h*2
           strout = string(h*2)
           print(' '^(2-length(strh)), strh, " x 2 = ",
                 ' '^(2-length(strout)), strout, "\n")
         end
       end

but are you sure want to reimplement Printf features in general? That’s a lot of work that was already done for you. twoTimesTable2 is also noticeably slower and allocates more ((160 allocations: 4.523 KiB) > (48 allocations: 1.406 KiB)), and it’ll also be a lot of work to optimize things up to par.

1 Like