Pages

Saturday, May 15, 2021

C style for loop

The syntax of the C-style for loop is taking the following form:

    for ((INITIALIZATION; TEST; STEP))

        do

        [COMMANDS]

    done


The INITIALIZATION part is executed only once when the loop starts. Then, the TEST part is evaluated. If it is false, the loop is terminated. If the TEST is true, commands inside the body of the for loop are executed, and the STEP part is updated.

In the following example code, the loop stars by initializing i = 0, and before each iteration checks if i = 10. If true it prints the current value of i and [increments the variable] i by 1 (i++) otherwise the loop terminates.


    for ((i = 0 ; i <= 1000 ; i++)); do

          echo "Counter: $i"

    done

The loop will iterate 1001 times.

No comments:

Post a Comment