Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to solve the puzzle regarding this code

Tags:

c++

c

puzzle


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

I have been rattling my brain but have not been able to solve this.

Delete any single character or operator from above code and the program should print "-" 20 times

Please help!

like image 323
Sadique Avatar asked Jul 23 '10 20:07

Sadique


4 Answers

I don't think you can do it by deleting a character, but I have three solutions that replace (well, one of them adds a character, but only because you have no whitespace in your program. If you had whitespace, it would replace a space).

Solution 1

int i,n=20;
for(i=0;-i<n;i--) // -i < n 
    printf("-");

Solution 2

int i,n=20;
for(i=0;i<n;n--) // n-- 
    printf("-");

Solution 3

int i,n=20;
for(i=0;i+n;i--) // while i + n is not zero 
    printf("-");
like image 185
IVlad Avatar answered Sep 28 '22 02:09

IVlad


I found a reference to the problem on C Puzzles. (It's in a comment, so it's surely not the original source.)

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.

Note that the instructions say:

...you have to fix the above code, by changing exactly one character.

One solution is to change i-- to n-- in the header of the for loop.

like image 28
Bill the Lizard Avatar answered Sep 28 '22 03:09

Bill the Lizard


The problem, as stated, has no solution. Either you or whoever gave that problem to you have stated it incorrectly.

like image 22
AnT Avatar answered Sep 28 '22 03:09

AnT


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

I don't know if replacing is ok but changing i-- to n-- should do the trick

like image 22
Eric Avatar answered Sep 28 '22 03:09

Eric