Posttest Logic Controlled loops - Do-while loops


General Information


Basic outline of do-while loops

    do
      single_statement;
    while (comparison evaluates to true);

  
    do
    {
      statement(s);
    }
    while (comparison is true);

NOTE: Be sure to notice the differences and similarities between the while loop construct and the do-while loop construct. Especially the use of the ;


Examples

These do exactly the same thing as the while loop examples.

  count = 0;
  do
  {
    printf("\n%d ", count);
    count = count + 2;
  }
  while (count < 20);

  
  scanf("%d", &count);
  if (count < 20)
  {
    do
    {
      printf("\n%d ", count);
      count = count + 2;
    }
    while (count < 20);
  }
  

  do
  {
    scanf("%d", &value);
    if (value < 0)
      printf("\nError - try again.  Value must be >= 0);
  }
  while (value < 0);

do-while loop to "clean" the input stream

  int iochar;

  ...

  do
  {
    iochar = getchar();
  }
  while (iochar != '\n');

Compressed version

while((iochar = getchar()) != '\n');