Comments on Loopy C Puzzle

Post Comment

Ryan said:

int i;
for (i = 0; abs(i) < 6; i--)
    printf(".");
01 Oct 2011 04:26 GMT (#1 of 9 comments)

Ryan said:

int i;
for (i = 0; -i < 6; i--)
    printf(".");
01 Oct 2011 04:46 GMT (#2 of 9 comments)

Sean said:

Changing the loop condition to i ^= 6; is another solution.

01 Oct 2011 04:48 GMT (#3 of 9 comments)

Ryan said:

Ah-ha, a tricky one:

int i;
for (i = 0; i ^= 6; i--)
    printf(".");
01 Oct 2011 04:54 GMT (#4 of 9 comments)

Ryan said:

Ah, Sean beat me to it. :(

01 Oct 2011 04:54 GMT (#5 of 9 comments)

Martin DeMello said:

for (i = 0; i + 6; i--)

will stop when i + 6 = 0.

01 Oct 2011 05:11 GMT (#6 of 9 comments)

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.

01 Oct 2011 11:58 GMT (#7 of 9 comments)

Ryan said:

Susam, absolute value is a mathematical operator. You didn't specify the set of acceptable operators. :P

01 Oct 2011 17:51 GMT (#8 of 9 comments)

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.

01 Oct 2011 18:08 GMT (#9 of 9 comments)
Post Comment