Wednesday, December 1, 2010

wu riddles - for loops

I like logic problems and code puzzles. I find that the naive solution generally comes without effort and I can manage better attempts as I invest more time and effort. Unfortunately, I wasn't born with an 'it just clicks' mind; I've actually got to work at my solutions.

I found a little teaser yesterday that I enjoyed and was able to get fairly quickly. This (and much, much more) can be found at wuriddles. This particular riddle lives in the CS section.

The original problem provides a C for loop that, as it is constructed, prints an infinite number of '-' characters. The code is:

/* Original code provided */
int i, n=20;
for (i=0; i < n; i--) {printf("-");};

The goal of the challenge is to modify that code by either adding or modifying only a single character to make the loop print the '-' character exactly 20 times. There are three ways to modify the above code to meet the requirements of the challenge. Give it a shot before looking at the solutions below.

Here are the solutions I was able to come up with.

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

No comments :

Post a Comment