for
Loops¶
for
: Loop Simplification (1)¶
while
loop approach:
Fixed number of runs
Counter is initialized
Termination condition is evaluated
Counter is incremented
This can be done simpler!
for
: Loop Simplification (2)¶
for (initialization; condition; step)
...
initialization is evaluated exactly once - before entering the loop
condition is evaluated everytime before the loop body is entered. false ⟶ loop termination
step is evaluated after the loop body, and before the condition
initialization, condition and step are regular statements
Second Program, revisited¶
#include <stdio.h>
int main(void)
{
int fahr;
for (fahr = 0; fahr <= 300; fahr = fahr+20)
printf("%6d\t%6.2f\n", fahr, 5.0/9 * (fahr - 32));
return 0;
}
Wherever there can be a variable, there can be an expression
A block (
{
and}
) is only necessary when the loop body consists of multiple statements5.0/9 * (fahr - 32)
isfloat
because5.0
is