C do while loop

Description

The do...while loop checks the conditional expression only after the repetition part is executed. It is used when you want to execute the loop body at least once.

Syntax for do while loop

The general form of the do...while loop is


do {
   repetition part;
} while (expr);

Example

The following code checks an int value against a predefined value n with do while loop.


#include <stdio.h>
//from  w w  w  .  j a va  2s  .co m
main(){
    int i,n = 5;
    i = 0;

    do{
        printf("the numbers are %d \n",i);
        i = i +1;
    }while( i<n) ;
}

The code above generates the following result.


Reversing the digits with do while loop.


#include <stdio.h>
//from   w ww.  j  a v  a2  s.  c  o  m
int main(void)
{
  int number = 123;
  int rightMostNumber = 0;
  int temp = 0;

  temp = number;

  do
  {
    rightMostNumber = 10*rightMostNumber + temp % 10;
    temp = temp/10;
  } while (temp);

  printf ("\nThe number %d reversed is  %d\n", number, rightMostNumber );
  return 0;
}

The code above generates the following result.


Read number in a range


#include <stdio.h>
/*  ww  w . ja  va2 s  .c o  m*/
int main(){


    printf("Please enter the number to start\n");
    printf("the countdown (1 to 100):");

    int start;
    scanf("%d",&start);
    do {
      printf("%d",start);
    }while(start<1 || start>100);
}

The code above generates the following result.


Nest for loop inside do while loop


#include <stdio.h>
//from   w  ww.  j a va2  s  .c  o m
int main()
{
    int start = 10;
    long delay = 1000;
 
 
    do
    {
        printf(" %d\n",start);
        start--;
        for(delay=0;delay<100000;delay++);   /* delay loop */
    }
    while(start>0);
 
    printf("Zero!\nBlast off!\n");
    return(0);
}

The code above generates the following result.





















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array