Code About Us Tutorial


  Statements & Expression
    The while Statement
    The do ... while Statement
    The for Statement
    The break Statement
    The continue Statement
    The goto Statement
    The switch Statement
    Keywords
    Scope Resolution (::)
    Arithmatic Operators


   
 

Home > Statements & Expression > The do ... while Statement

November 27, 2009 11:58 am

   

The do ... while Statement

The Next statement we are going to focus on will be the do...while statement. The do...while statement is almost the same as the while statement. Its syntax is:

do statement while (condition);

The only difference is that the do...while statement executes the statement first and then evaluates the condition. These two steps are repeated until the condition evaluates to zero (false). A do...while loop will always loop at least once, regardless of the value of the condition, because the statement executes before the condition is evaluated the first time. I'll rewrite the above code but use the do...while instead of the while statement.

 
 
#include <iostream.h>
void main()
{
	int n;
	
	do 
	{
		cout <<"Enter a number to be cubed, terminate with 0: ";
		cin >> n;
		cout << n <<" cubed is: " << n*n*n << "n";
	} while( n > 0 );
	
}

This programs output is the exact same as the while statement. The only difference is that this program will always iterate at least once through the code before checking the condition.Please Rate this Code:


    Comments for: The do ... while Statement
Annonymouse User says:
what came first the do or the while. (may be more of a history question but a response would still be appreciated)

ben [frenchtoast2@home.com] Posted: 2 times. says:
you can use the pow(n,3) function, as opposed to your poor choice of n*n*n.

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
Yeah, But this is just an example.

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
I would say the while came first because the do is simply a pre-execution loop!




Add Comment:
Name:
Email:


 «3» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.