For loops for fun and profit

For loops aren’t rocket science by any stretch of the imagination, but perhaps some wayfaring programmer will find the following enlightening.

What appears to be at first basic and fundamental can belie the incredible flexibility offered. Below are a few examples related to that most common of control structures, the for loop.

These examples apply to most variations of C and C-based languages as well as Java.

Infinite loop:

    // Works a treat for main event loops.

Statement scoped control variable:

for(int i = 1; i = 10; i++)
    // i is valid within the loop only.

Control variable incremented within body:

int i;

for(i=1; i = 10;)

Body-less loop for arithmetic:

int i, sum = 0;

for (i = 1; i = 10; sum += i++);