CodesandTutorials
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.  
You are here - Home > Programming > C > Basics

Do While Loop Statement


Description

Do while loop statement is used when user wants to execute the loop block at least once, no matter what initial condition of test expression is. And terminates the loop when test expression is true.

Syntax

do
{
statement;
statement;
}while (test expression is true);

Loop ends with semicolon.

Source code


  • //Using Do While statement
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • int dividend,divisor,quotient,remainder;
  • char ch;
  • clrscr();
  • do
  • {
  • printf("Enter dividend : ");
  • scanf("%d", & dividend);
  • printf("Enter divisor : ");
  • scanf("%d",&divisor);
  • quotient=divident/divisor;
  • remainder=divident%divisor;
  • printf("Quotient is : %d ,",quotient);
  • printf("Remainder is : %d",remainder);
  • printf("\nDo you want to do another calculation? (y/n)");
  • scanf("%c",&ch);
  • }while(ch!='n');
  • getch();
  • }

Program working steps

  • Its a simple division program resulting quotient and remainder.
  • First 4 lines of the program are comments, preprocessor directives and void main() function.
  • 6th and 7th line is the declaration of required variables needed to implement the program.
  • clrscr() function is used to clear the text exists on the console screen.
  • From Do keyword the loop begins, at start programs asks the user to enter dividend and divisor and stores the value to respective variables. Then program calculates quotient using division operator symbol '/' and remainder by using modulus operator symbol '%'.
  • Result calculated are printed using printf statement and the user is prompted to 'Do you want to do another calucation'.
  • If the user enters 'y', then the test expression becomes true and the do while loop body will be repeated from line no.11. And if user enters 'n', the test expression becomes false and the loop will be terrminated.
  • getch() function to avoid flash up and exit off console screen.

Tip Box

Remember

In do while loop, while loop statement ends with a semicolon.


Advertisement





Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved