Skip to content

[C] For loop (The For Statement)

In the previous note, I recorded how to program conversion between Celsius and Fahrenheit ([C] Variables and Arithmetic Expressions). In the process, we continuously increase the Fahrenheit temperature through the while loop, and view the converted Celsius temperature result.

If you want the program to execute the same command over and over again, you can also use a for loop to do this.


For loop

We rewrite the Celsius and Fahrenheit temperature conversion program from the previous note:

#include <stdio.h>            


int main() {
    float F, C;
    int lower = 0;
    int upper = 300;
    int step = 20;

    // For-loop
    for (F=0; F<=300; F+=step) {
        C = (5.0 / 9.0) * (F - 32.0);
        printf("%3.0f %6.1f\n", F, C);
    }

    return 0;
}


Output:

  0  -17.8
 20   -6.7
 40    4.4
 60   15.6
 80   26.7
100   37.8
120   48.9
140   60.0
160   71.1
180   82.2
200   93.3
220  104.4
240  115.6
260  126.7
280  137.8
300  148.9

It can be seen that using for loop and while loop can achieve the same effect.

The settings in the for loop are divided into three conditions:

for(INITIAL_VALUE; EXECUTE_CONDITION; UPDATE_VALUE)

INITIAL_VALUE is a initial condition when the for loop starts to execute, here is the case of F=0.

The EXECUTION_CONDITION is F<=300, which means that the loop will be executed until F exceeds 300.

The UPDATE_VALUE is F+=step (F+=20), that is, the value of F is fixedly updated at the end of each loop. If you don’t do this, the loop will run forever.


References


Read More

Leave a Reply