C - for Loop Control Options

Introduction

You can increment or decrement the loop counter by any amount. Here's an example of how you can do this:

long sum = 0L;
for(int n = 1 ; n < 20 ; n += 2)
  sum += n;
printf("Sum is %ld", sum);

The preceding loop sums all the odd integers from 1 to 20.

The third control expression increments the loop variable n by 2 on each iteration.

To sum every seventh integer from 1 to 1,000:

for(int n = 1 ; n < 1000 ; n = n + 7)
  sum += n;

You could rewrite the loop in the first code fragment, summing the odd numbers from 1 to 20 like this:

This time you update two values in the third statement.

for(int n = 1 ; n<20 ; sum += n, n += 2)
  ;

The third control expression consists of two expressions separated by a comma. 

Floating-Point Loop Control Variables

The loop control variable can be a floating-point variable. Here's a loop to sum the fractions from 1/1 to 1/10:

double sum = 0.0;
for(double x = 1.0 ; x < 11 ; x += 1.0)
  sum += 1.0/x;

Fractional values often don't have an exact representation in floating-point form:

for(double x = 0.0 ; x != 2.0 ; x+= 0.2)      // Indefinite loop!!!
  printf("\nx = %.2lf",x);

Related Topic