An Exit-Condition Loop: do while

The while loop and the for loop are both entry-condition loops. The test condition is checked before each iteration of the loop, so it is possible for the statements in the loop to never execute. C also has an exit-condition loop in which the condition is checked after each iteration of the loop, guaranteeing that statements are executed at least once. This variety is called a do while loop. Listing 6.13 shows an example.

Listing 6.13 The dowhile.c program.
/* dowhile.c -- exit condition loop */
#include <stdio.h>
int main(void)
{
   char ch;
  do
  {
       scanf("%c", &ch);
       printf("%c", ch);
  } while (ch != '#');
  return 0;
}

The program in Listing 6.13 reads input characters and reprints them until the # character shows ...

Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.