tags:

views:

592

answers:

7
+21  Q: 

Help with C puzzle

I found a site with some complicated C puzzles. Right now I'm dealing with this:

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesn't work.

#include <stdio.h>
int main()
{
    int i;
    int n = 20;
    for( i = 0; i < n; i-- )
        printf("-");
    return 0;
}

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are three known solutions. See if you can get all those three.

I cannot figure out how to solve. I know that it can be fixed by changing -- to ++, but I can't figure out what single character to change to make it work.

+26  A: 

Here is one solution:

for( i = 0; -i < n; i-- )
        printf("-");

Here is a second one, thanks to Mark for helping me!

for( i = 0; i + n; i-- )
    printf("-");

And Mark also had the third one which is

for( i = 0; i < n; n-- )
    printf("-");
Gab Royer
The second one would not work. You will get `-20, -21, -22,...`. But `i + n` should do it.
Felix Kling
Indeed, I just noticed it.
Gab Royer
I think the second one needs `i+n` rather than `i-n` and you have it. Nice.
Mark Wilkins
You're right! I was sure it was related to this somehow but had abandoned hope a bit early in the process :P
Gab Royer
That second one is awesome. Thank you. Thanks to Mark too, who apparently contributed a lot.
Javier Badia
+17  A: 

Change i-- to n-- is another.

Okay - Gab made the fix, so I removed the other solution. He wins!

Mark Wilkins
Didn't think of this one!
Gab Royer
@Gab: Heh - I'm glad since you beat me by a minute with yours :)
Mark Wilkins
I accepted the other answer because it includes all three solutions, but thanks a lot.
Javier Badia
@Javier: Good decision. Gab thought of two before I did. Fun problem.
Mark Wilkins
A: 

Here's one of them, I think:

for( i = 0; i < n; n-- )
jwismar
Nice catch mate
+2  A: 
    for( i = 0; i < n; n-- )  
    printf("-");  

Changed i-- to n--

FromCanada
A: 

The comparison in the for loop can be any expression - you can negate i.

for (i = 0; -i < n ; i--)
rlotun
+7  A: 

Third answer:

for( i = 0; i + n; i-- )  
    printf("-"); 

Thanks to Gab Royer for inspiration.

Explanation: Eventually , i + n will result in -20 + 20 = 0 which is false.

Felix Kling
changed 2 chars
Aha, that's clever!!
FrustratedWithFormsDesigner
@user294702: I had a copy and paste error, fixed it.
Felix Kling
A: 

Solution 1

#include <stdio.h>
int main()
{
    int i;
    int n = 20;
    for( i = 0; i < n; n-- ) // Change i-- to n--
        printf("-");
    return 0;
}

Solution 2

#include <stdio.h>
int main()
{
    int i;
    int n = 20;
    for( i = 0; -i < n; i-- ) // Compare to -i
        printf("-");
    return 0;
}

Haven't figured a third.

Robert Davis