1

C Special Loops


There are two special loops in C:

  • Nested loop – a loop inside of another loop, also called a loop within a loop.
  • The forever loop – a controlled infinite loop

Here is a sample code for the nested loop:

/*
 *
 * nested.c
 * Program to demonstrate the use of nested loops
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int i, j;

 for (i = 1; i <= 5; i = i + 1)
   for (j = 1; j <= 3; j = j + 1)    // nested loop
   printf("Here we are in the inner loop with i = %d and j = %dn", i, j);

 fflush(stdin);
 getchar();
}

Nested loops are often used in the multi-dimensional arrays.

And here is the forever loop:

/*
 *
 * forever.c
 * Program to demonstrate the use of the "forever" loop
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type;
 int album;    // boolean

 for (;;) {    // A for loop that has no arguments will repeat the loop forever
   printf("Album or single (a for album, s for single)? ");
   scanf("%c", &type);
   while (getchar() != 'n' && getchar() != EOF)    // nested loop
     printf("");
   if (type == 'a' || type == 's')
     break;
   printf("Errorn");
 }

 album = type == 'a';

 if (album)
   printf("Albumn");
 else
   printf("Singlen");

 fflush(stdin);
 getchar();
}

The forever loops can only used in the for loops, and it’s similar to the while loop for input validation.

There are no posts related to C Special Loops.

  1. [...] “country-firstNam_lastName-age-thumb.png” as well as some knowledge I got from the C for loop tutorial. Also note that this is the test code, meaning that I haven’t added extensive [...]