# Horizontal version of Print[]

With the following code I produce the binary digits of n=13:

n=13;

Q = Quotient[n, 2];

While[Q != 0, Print[Mod[n, 2]]; Q = Quotient[n, 2]; n = Q]


The problem is that it outputs the digits as

1

0

1

1


but I want them to appear horizontally 1101. What is the most direct way to produce the desired effect regarding the output's style?

• Commented Sep 21, 2023 at 0:51

Updated to reverse the result of OP's loop

This makes a list (which needs to be reversed):

Q = Quotient[n, 2];
result = {};
While[Q != 0, AppendTo[result, Mod[n, 2]]; Q = Quotient[n, 2]; n = Q]

Reverse[result]


{1, 1, 0, 1}

If you want a string:

StringJoin[ToString /@ Reverse[result]]


"1101"

There's also

BaseForm[13, 2]


IntegerString[13, 2]


"1101"

BaseForm[13,2]


or more generally

BaseForm[n,base]


What is the most direct way to produce the desired effect?

Do not use Print. I am sure there are at least 10 ways to do this, one way could be to replace Print by Sow and keeping your main logic as is. But this can also be done with explicit loop

doit[n_Integer?Positive]:=Module[{m=n,q},
q=Quotient[m,2];
While[q!=0,
Sow[Mod[m,2]];
q=Quotient[m,2];
m=q
]
]


And now do

r = First@Last@Reap@doit[13];
StringJoin[ToString /@ Reverse[r]]
ToExpression[%]


"What is the most direct way to produce the desired effect?"

BaseForm[13, 2]