A Compact for Loop

Difficulty: ★ ★ ☆ ☆

A for loop statement contains three parts: initialization, termination, and while-looping. If you omit any part, the compiler assumes the value one, or TRUE, as the value, so the statement for(;;) becomes an endless loop. The opposite of omitting is loading up: You can state multiple initialization and while-looping expressions in the statement, which can make a for loop truly compact.

The secret to adding multiple initialization or while-looping expressions is to use a comma to separate them. For example:

b = 10;
for( a=0; a<b; a++ )
    b--;
etc...

The code block above can be condensed to:

for( a=0, b=10; a<b; a++,b-- )

I just moved variable b‘s initialization and while-looping statements into the body of the for statement, using commas to separate the a and b items.

You can’t use a comma in the middle, termination expression. I don’t think one would ever be necessary as you can fuse together logical operators to accomplish the same thing. Regardless, all this prologue is background for this month’s C programming Exercise.

Your task is to generate random output in the range of zero through 99. Keep spitting out these random integers until one matches 99, then the loop stops. As each value is output, it’s counted sequentially.

Here’s sample output — the shortest one after a few sample runs where the average run was in the triple digits:

  1 : 0
  2 : 52
  3 : 17
  4 : 93
  5 : 9
  6 : 44
  7 : 24
  8 : 39
  9 : 17
 10 : 36
 11 : 60
 12 : 94
 13 : 52
 14 : 72
 15 : 58
 16 : 94
 17 : 99

The kicker is that all the action takes place in the for loop statement: initialization, termination, and while-looping. This approach reduces the overall line count in the code. Here’s your task list:

  1. Seed the randomizer.
  2. Configure the for loop statement, packing in all the initialization and while-looping goodness.
  3. The for loop contains a single printf() statement, the one that outputs the count and values.
  4. Finish the main() function with a return statement.

These are just the minimum requirements. Obviously, more statements may be required, but the point of the exercise is to stuff as much of the action into the for loop statement as possible.

As a suggestion, write the code as you normally would to ensure that the output looks like mine. Then relocate various expressions within the for loop statement.

Click here to view my solution, but please try this challenge on your own before you see what I did.

Leave a Reply