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



do...while

The do..while loop has the form:

do
{
  do something
}
while (condition);

Notice that the condition is at the end of this loop. This means that a do..while loop will always be executed at least once, before the test is made to determine whether it should continue. This is the chief difference between while and do...while.

The following program accepts a line of input from the user. If the line contains a string of characters delimited with double quotation marks, such as "Hello!", the program prints the string, with quotation marks. For example, if the user types in the following string:

I walked into a red sandstone building. "Oof!" [Careful, Nick!]
...then the program will print the following string:
"Oof!"

If the line contains only one double quotation mark, then the program will display an error, and if it contains no double quotation marks, the program will print nothing.

Notice that the do...while loop in main waits to detect a linefeed character (\n), while the one in get_substring looks for a double quotation mark ("), but checks for a linefeed in the loop body, or main code block of the loop, so that it can exit the loop if the user entered a linefeed prematurely (before the second ").

This is one of the more complex examples we have examined so far, and you might find it useful to trace the code, or follow through it step by step.

#include <stdio.h>

int main();
void get_substring();


int main()
{
  char ch;

  printf ("Enter a string with a quoted substring:\n\n");

  do
  {
    ch = getchar();
    if (ch == '"')
    {
      putchar(ch);
      get_substring();
    }
  }
  while (ch != '\n');

  return 0;
}


void get_substring()
{
  char ch;

  do
  {
    ch = getchar();
    putchar(ch);

    if (ch == '\n')
    {
      printf ("\nString was not closed ");
      printf ("before end of line.\n");
      break;
    }
  }
  while (ch != '"');

  printf ("\n\n");
}