Comments on Loopy C Puzzle
Ryan said:
int i;
for (i = 0; -i < 6; i--)
printf(".");
Sean said:
Changing the loop condition to i ^= 6;
is another solution.
Ryan said:
Ah-ha, a tricky one:
int i;
for (i = 0; i ^= 6; i--)
printf(".");
Ryan said:
Ah, Sean beat me to it. :(
Martin DeMello said:
for (i = 0; i + 6; i--)
will stop when i + 6 = 0.
Susam Pal said:
All solutions except the one in the first comment are correct. The first
one involves abs()
function. The code would indeed end up
printing 6 dots but it doesn't meet the requirement in the question
since abs()
is not an operator.
There is another very simple solution similar to the obvious solution I have provided in the post. Instead of post-increment operator, use the pre-increment operator.
int i;
for (i = 0; i < 6; ++i)
printf(".");
The one involving the bitwise XOR operator is the one I had in my mind while mentioning that one of the solutions is very interesting. I find it interesting because it is not obvious at the first glance why it works. Another curious property of this solution is that it works only for an even number of dots. I'll write about this in another post.
Ryan said:
Susam, absolute value is a mathematical operator. You didn't specify the set of acceptable operators. :P
Susam Pal said:
Ryan,
I am used to referring to abs()
as the absolute value
function. But yes, I see your point. The problem statement could have
specified that exactly one operator from the C programming language must
be added to or modified in the given code snippet. That would have ruled
out this little ambiguity.
Ryan said: