A do-while loop is best suited to loops that must execute at least once:
srand(( unsigned)time(NULL));
int i;
do {
// pick a random number between 1 and 10
i = 1 + (int) (10.0*(rand()/(RAND_MAX+1.0)));
std::cout << i << std::endl;
} while( i!=10 );
In this example, the loop executes at least once and prints a random number. While the random number is less than 10, the loop reiterates, selecting another random number until the number 10 is selected.
The exact same effect can be achieved with for and while loops but the code is much less readable as a result:
srand(( unsigned)time(NULL));
int i=0;
while( i!=10 )
{
// pick a random number between 1 and 10
i = 1 + (int) (10.0*(rand()/(RAND_MAX+1.0)));
std::cout << i << std::endl;
}
In the above example, we must initialise i before entering the loop for the first time.
srand(( unsigned)time(NULL));
for(;;)
{
// pick a random number between 1 and 10
int i = 1 + (int) (10.0*(rand()/(RAND_MAX+1.0)));
std::cout << i << std::endl;
if( i==10 )
break;
}
In the above example we use an infinite loop and instantiate i within the loop. We can also replace for(;;) with while(1) to achieve the same result.
Ultimately the do-while loop makes the most sense in this case. The infinite loop versions would only make sense if you wanted i to fall from scope at the end of the loop (which can't be done with a do-while loop since the conditional expression is outside of the loop). But the while loop makes the least sense because i must be initialised before entering the loop for the first time.
kk
Example: int main (void) { LOOP: goto LOOP; }
In C++, a for loop is structured as follows: for( int index = 0; index < 10; ++i ) { //do something }
"do statement while (...);" is a loop which does at least one iteration even if the condition after while is false. When, for instance, "while(...) statement" does not iterate at all if the condition after while is false.
No, why did you think so?
A do-while loop checks its termination condition before each iteration, including the first; a do-until checks after each iteration, so that the first iteration occurs before the first check. The C language uses the word "while" for both types of loop, using the placement of the condition to control its timing:C do-while:while (condition) { /* condition checked before first loop iteration */... loop contents}C do-until:do {... loop contents} while (condition); /* condition not checked until after first loop iteration */
Input a variable.
In C a structure within a structure is called nested. For example, you can embed a while loop in another while loop or for loop in a for loop or an if statement in another if statement.
Yes, you can use for-loop in a C program compiled by Turbo C.
It is unnecessary to use a for loop to convert meters to centimeters. Just multiply by 0.01.
+ is an example, one of many, of a binary operator in C or C++ a = b + c; // for usage example
for (int x = 0; x < 5; x++){cout