Wednesday 23 June 2010

Challenging problem to test your 'for loop' basics

While scouting through the web I came across this fun puzzle:

In the following code:


#include<iostream>

using namespace
std;

int
main()
{

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

cout << "x" << endl;
}


return
0;
}




by changing only ONE character in the above code, meaning you cannot change 20 to 31, because you will have changed two characters, you can change 20 to 21, because you only changed the 0, do the following:

find 3 ways to make the above code print x 20 times (by changing only one character).


Give it a try, if you can do it then look at the answer below.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The first one should be simple:
i-- becomes n--
.
.
.
.
.
.
.
I guess this is the second one you got
i<n becomes i+n
.
.
.
.
.
.
.
.
.
.
The third one which is tricky, In fact there are two similar solutions is:

i<n becomes, -i<n,
i
<n becomes, ~i<n

remember BODMAS


No comments:

Post a Comment