Showing posts with label do while in c. Show all posts
Showing posts with label do while in c. Show all posts

Thursday 17 October 2013

Do While In C++

Do While C:


In this C tutorial for beginners, we are going to discuss the third repetition structure known as do…while loop in c. In for loop, initially the loop condition is checked and then the statement is executed according to the loop condition. But if you want to execute the statement initially(first) and then check the loop condition then we use do…while loop.

Syntax:

do
       statement;
while (expression);



Do while loop in C++



Statement can be either a simple or compound statement. If it is a compound, enclose it between braces. In C++, do and while are reserved keywords.

Mechanism:

The statement executes first and then the expression is evaluated. If the expression is true then statement executes again else the loop will terminate.
A popular use of c do…while loop is that it can be used for input validation. Suppose that a user prompts to enter a test score which must be greater or equal to zero and less than fifty. SO, entries other than that should be invalid. For this we use do…while loop in c.

e.g:

int score;
do
{
    cout << “Enter a score between 0 and 50\n”;
    cin>>score;
    cout<<endl;
}
while (score < 0 || score > 50);

Final words:

In this c tutorial for beginners we discussed do while loop in detail. This is an important structure frequently used in C++. 
You can study and easily understand it here.