#include <stdio.h> #include <stdlib.h> /* Puzzle L02 -- print the integers from 1 to 15, one per line */ int main(int argc, char *argv[]) { int j; for (j=1; j<=15; j++ ) { printf("%3d\n", j); } return 0; }
Comments: It also works to use this for
statement:
for (j=1; j<16; j++ )
Here is an inferior solution to the problem because it
does something needlessly tricky for no particular benefit.
The trick is that it uses the last value assigned to j
, 15,
outside of the loop.
/* Puzzle L02 -- print the integers from 1 to 15, one per line | Bad Solution. */ int main(int argc, char *argv[]) { int j; for (j=1; j<15; j++ ) { printf("%3d\n", j); } printf("%3d\n", j); /* The "trick" */ return 0; }
Although this is an awful way to write the program,
you should understand how it works.
The variable j
is incremented to 15
the last time the loop body is executed.
It keeps this value, even though the loop is finished.