39

Possible Duplicate: Help with C puzzle

This morning i had a job interview and they gave me this problem:

You should change one character to print "*" 42 times. You can replace, add or remove ONLY one character.

Still i cant figured it, i've tried over and over again.

#include <stdio.h>
main(){
    int i,n = 42;

   for(i = 0; i < n; i--){
       printf("*");
   }
}
138

One option would be to change the < to a +:

#include <stdio.h>
main(){
    int i,n = 42;

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

The reason this works is that C treats nonzero values as "true" and zero values as "false." The value of i + n starts at 42 and then counts down 41, 40, 39, ..., 1, 0. When it hits zero, it must mean that i == -n, at which point you're done.

71 accepted
#include <stdio.h>
main(){
    int i,n = 42;

   for(i = 0; -i < n; i--){    //added a minus here
       printf("*");
   }
}

But to be honest, I think that this is a silly interview question.

68
for(i = 0; i < n; n--){        
    printf("*");    
}

Looks like you change the i-- to n--.

Seems like a strange interview question. What was it for, if you don't mind me asking?

10

How about:

for(i = 0; -i < n; i--) {
           ^
10

What about changing the - to a +? :)

I changed the source a tiny little bit.


$ cat 4927230.c
#include <stdio.h>
int main(void) {
  int i, n = 42;
  for (i = 0; i < n; i--) {
    printf("*");
  }
  puts("");
  return 0;
}
$ tr \- \+ < 4927230.c | gcc -xc - && ./a.out
******************************************
$ 

hehe

9

That's easy:

#include <stdio.h>
main(){
    int i,n = 42;

   for(i = 0; i < n; n--){
       printf("*");
   }
}
6

While this is a "puzzle" rather than a programming task, I think it is actually a rather good interview question, as it tests a number of skills valuable in a programmer. If you can't solve this, then you may have a lot of trouble reasoning about complex code.

The first thing I noted is that i is initialized twice, so its initialization to 42 is irrelevant unless the second initialization is eliminated, e.g. by changing it to i + 0. The next thing I noted is that we're stuck with -- as it cannot be usefully modified by a single character. So we're decrementing a counter but using < for the test, so we need to do an inversion of some sort. -i < n does that handily, as does n-- by decrementing the limit rather than the counter. The i + n solution, which is equivalent to -i != n, is harder to come up with.