18. Create Nested Loops

When the body of one loop contains another, the second is said to be nested inside the first. Any of C’s loops may be nested within any other loop. The ANSL C standard specifies that loops may be nested at least 15 levels deep. However, most compilers allow nesting to virtually any level. As a simple example of nested for, this fragment prints the numbers 1 to 10 on the screen ten times,

for (i=0;i<10;i++)
{
  for (j=1;j<11;j++)  /* nested loop */
  printf(“%d”,j);
  printf(“\n”);
}

Examples:

** This program used three for loops to print the alphabet three times, each time printing each latter twice;

#include<stdio.h>
int main(void)
{
  int I,j,k;
  for(i=0;i<3;i++)
    for(j=0;j<26;j++)
      for(k=0;k<2;k++)
      printf(“%c”,’A’+j);
return 0;
}

The statement
Printf(“%c”,’A’+j);
Works because ASCII codes for the letters of the alphabet are strictly ascending-each one is greater than the letter that precedes it.

(Taken from “Teach yourself C”)

1 comment:

free counters