#include <stdio.h> #include <stdlib.h> /* Puzzle A06 -- print the odd integers from 1 to 99, one per line */ int main(int argc, char *argv[]) { int j; for (j=1; j<=99; j+=2 ) { printf("%3d\n", j); } system("PAUSE"); return 0; }
Comment: The above is probably the best solution. The following loop is another solution, but it is more complicated, and does twice as much work for the same effect:
for (j=1; j<=99; j++ ) { if ( j%2 == 1 ) printf("%3d\n", j); }
Recall that the modulo operator (%
) evaluates to the remainder
after integer division. So, 1%2
gives 1
, 2%2
gives 0
, 3%2
gives 1
, 4%2
gives 0
, and so on.
So even and odd can be detected with %
.
But you must be careful with negative integers
(not a problem in this puzzle).
An overly clever programmer might realize that in C, any integer other than zero counts as true, so that the above might be further simplified as:
for (j=1; j<=99; j++ ) { if ( j%2 ) printf("%3d\n", j); }
But this is not really simplification. It does not actually express what you want to say, and is harder to understand, and with a good compiler probably produces the same machine code as the less clever version.