Node:for, Next:, Previous:do...while, Up:Loops



for

The most complex loop in C is the for loop. The for construct, as it was developed in earlier computer languages such as BASIC and Pascal, was intended to behave in the following way:

For all values of variable from value1 to value2, in steps of value3, repeat the following sequence of commands...

The for loop in C is much more versatile than its counterpart in those earlier languages. The for loop looks like this in C:

for (initialization; condition; increment)
{
  do something;
}

In normal usage, these expressions have the following significance.

For example, the following for loop prints out the integers from 1 to 10:

int my_int;

for (my_int = 1; my_int <= 10; my_int++)
{
  printf ("%d ", my_int);
  printf("\n");
}

The following example prints out all prime numbers between 1 and the macro value MAX_INT. (A prime numbers is a number that cannot be divided by any number except 1 and itself without leaving a remainder.) This program checks whether a number is a prime by dividing it by all smaller integers up to half its size. (See Preprocessor directives, for more information on macros.)

#include <stdio.h>

#define MAX_INT  500
#define TRUE      1
#define FALSE     0

int main ()
{
  int poss_prime;

  for (poss_prime = 2; poss_prime <= MAX_INT; poss_prime++)
  {
    if (prime(poss_prime))
    {
      printf ("%d ", poss_prime);
    }
  }
  printf("\n\n");
  return 0;
}


prime (int poss_prime)       /* check whether poss_prime is prime */
{
  int poss_factor;

  for (poss_factor = 2; poss_factor <= poss_prime/2; poss_factor++)
  {
    if (poss_prime % poss_factor == 0)
    {
      return (FALSE);
    }
  }

  return (TRUE);
}

The program should print the following sequence of integers:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191
193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283
293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401
409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499