#include <stdio.h> #include <stdlib.h> /* Puzzle A07 -- print the first N odd integers. Ask the user for N. */ int main(int argc, char *argv[]) { int j, N; printf("Enter n: ");
scanf("%d", &N );
for (j=0; j < N; j++ ) { printf("%3d\n", 2*j+1 ); } system("PAUSE"); return 0; }
Comment: The loop is a counting loop. It counts from
zero to N-1
. The counts, j
, are transformed into odd numbers
by using 2*j+1
. The value 2*j
is always even, of course.
Adding 1 to that gives an odd number.
To check that this works, look at what happens when j==0
. This
gives 2*0+1 == 1
, the first odd number. Now you need to worry that
successive odd numbers are calculated, and that the last one calculated is the
N'th odd number. Practice worrying about this.
It is good to practice worrying. As a programmer, you will worry about fussy details a lot.