C - do while Statement

Introduction

In do while loop, the test for whether the loop should continue is at the end of the loop.

So the loop statement or statement block always executes at least once.

The general representation of the do-while loop is:

do
{
  /* Statements for the loop body */
}
while(expression);

The following code uses do-while loop to reverse the digits of a positive number:

Demo

#include <stdio.h>
int main(void)
{
  unsigned int number = 0;                 // The number to be reversed
  unsigned int rebmun = 0;                 // The reversed number
  unsigned int temp = 0;                   // Working storage

                       // Read in the value to be reversed
  printf("\nEnter a positive integer: ");
  scanf(" %u", &number);

  temp = number;                           // Copy to working storage

                       // Reverse the number stored in temp
  do/*from   w w w .  j  a v a 2 s .  c o  m*/
  {
    rebmun = 10 * rebmun + temp % 10;        // Add rightmost digit of temp to rebmun
    temp = temp / 10;                        // and remove it from temp
  } while (temp);                           // Continue as long as temp is not 0
  printf("\nThe number %u reversed is  %u rebmun ehT\n", number, rebmun);
  return 0;
}

Result

how It Works

The reversal of the digits is done in the do-while loop:

do
{
      rebmun = 10*rebmun + temp % 10;        // Add rightmost digit of temp to rebmun
      temp = temp/10;                        // and remove it from temp
} while(temp);                           // Continue as long as temp is not 0

You get the rightmost decimal digit using the modulus operator, %, to obtain the remainder after dividing by 10.

Related Topics