Do-While Loop inc C Programming (syntax and Example)

DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once.

The structure is
 } while ( condition );

Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is almost the same as a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and then continue to loop while the condition is true".

#include <stdio.h>

int main()
  int x;

  x = 0;
    /* "Hello, world!" is printed at least one time
      even though the condition is false */
      printf( "Hello, world!\n" );
  } while ( x != 0 );
Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition. 


Popular posts from this blog


HSC Exam Time Table 2013 Arts, Commerce, Science

What are cookies and its types? Where are cookies used?