Introducing: The for statement (a.k.a. "for loop") * First, here is a while loop again: i = 1; while (i <= 5) { printf("This is line %d\n", i); i = i + 1; } /* end of while loop */ i = 100; * Here is the equivalent for loop: for (i = 1; i <=5; i++) printf("This is line %d\n", i); /* end of for loop */ i = 100; * The output is the same for both loops: This is line 1 This is line 2 This is line 3 This is line 4 This is line 5 How does it work? Much like a while loop. General form: for ( statement; Conrol Expression; statement ) statement; Inside the parentheses after "for" are 3 things, separated by semi-colons: 1) The first thing is a statement that is executed exactly once during the loop, when the CPU first comes to the For Loop. 2) The second thing is the Control Expression. If the Control Expression is true, the statement (or statements) inside the loop is executed. 3) The third thing is a statement that is executed each time the processor reaches the end of the loop, *before* the Control Expression is tested to see if the for loop should continue. ------------------------------------------------------------ Let's look at another example: Goal: produce this table of temperatures: (left column is fahrenheit, right is celsius) 0 -17 20 -6 40 4 60 15 80 26 100 37 Here's the program: #include int main(void) { int fheit, celsius; for (fheit = 0; fheit <= 100; fheit = fheit + 20) { celsius = 5 * (fheit - 32) / 9; printf("%d\t%d\n", fheit, celsius); /* reminder: \t is an escape sequence for a tab */ } return(0); } ------------------------------------------------------------ Review: For Loop * standard way to do something N times: (where N is some integer) for (i = 0; i < N; i++) { ... ... } * An equivalent while loop: i = 0; while (i < N) { ... ... i++ } ------------------------------------------------------------ * * * * *