Re: How to print an array of char backward.



Tomás Ó hÉilidhe wrote:
On May 30, 8:34 pm, hank <ilona-radema...@xxxxxxxxxxx> wrote:

do {
if (dec % 2 == 0)
strcat(bin, "0");
else {
strcat(bin, "1");
dec--;
}
dec = dec / 2;
} while (dec > 0);


This algorithm can be written differently depending on whether you do
or do not want leading zeroes.

My major criticism of your original code is that it takes a human
approach rather than a computer approach. A computer approach would be
to use (x & 1) instead of (x % 2), and also to use shifting instead of
division by 2.

I disagree.
The code as written, is easy to understand.
If he were doing decimal representation,
he would be dividing by 10 instead.

It's entirely possible and likely that a compiler
will know as much as you do about these simple micro-optimizations
and generate the same machine code for (x & 1) as it does for (x % 2).

If the code is shown to be not fast enough,
then I would investigate the changes that you suggest,
otherwise legibility is a higher priority.

--
pete
.