Comments

On Loopy C Puzzle
Post Comment

Ryan wrote:

int i;
for (i = 0; abs(i) < 6; i--) {
    printf(".");
}
01 Oct 2011 04:26 UTC | #1 of 8 comments

Ryan wrote:

int i;
for (i = 0; -i < 6; i--) {
    printf(".");
}
01 Oct 2011 04:46 UTC | #2 of 8 comments

Sean wrote:

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

01 Oct 2011 04:48 UTC | #3 of 8 comments

Ryan wrote:

Ah-ha, a tricky one:

int i;
for (i = 0; i ^= 6; i--) {
    printf(".");
}
01 Oct 2011 04:54 UTC | #4 of 8 comments

Ryan wrote:

Ah, Sean beat me to it. :(

01 Oct 2011 04:54 UTC | #5 of 8 comments

Martin DeMello wrote:

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

will stop when i + 6 = 0.

01 Oct 2011 05:11 UTC | #6 of 8 comments

John Tromp wrote:

The value in variable i decrements to INT_MIN after |INT_MIN| + 1 iterations.

No; i decrements to INT_MIN after |INT_MIN| iterations. For example, if i were a signed 1-bit integer, making INT_MIN equal to -1, than i becomes -1 upon executing --i after the first iteration.

Of course, you're correct that |INT_MIN| + 1 dots are output, due to the extra (and final) iteration starting with i = INT_MIN.

22 Dec 2023 11:46 UTC | #7 of 8 comments

Susam Pal wrote:

John, You are absolutely right. Thank you for taking a close look at this post and reporting the off-by-one error in my explanation. I have updated the post now to correct it.

12 Jan 2024 21:38 UTC | #8 of 8 comments
Post Comment