#include <stdio.h> #include <stdlib.h> /* Puzzle L06 -- print the odd integers from 1 to 99, one per line */ int main() { int j; for (j=1; j<=99; j+=2 ) { printf("%3d\n", j); } 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); }
The 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 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 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 an optimizing compiler might produce the same machine code as the less clever version.