Point of Do-while?

Posts 1–10 of 10 · Page 1 of 1
Point of Do-while?
What's the point of [PHP]do
{
//code
}
while(statement);[/PHP]

Wouldn't it just be easier to just use a While or For?
while(xxx), as you may see it starts with a condition... sometimes you don't need the condition right on the start... so..

do {} while will do fine.. and check condition at the end... it's all about choices.. and logic.

example, if you want it to loop by asking a a user input, you will for sure need to ask the input first... like:

Code:
int num;

do
{
    cin >> num;
}
while(num < 0);
Quote Originally Posted by 'Bruno View Post
while(xxx), as you may see it starts with a condition... sometimes you don't need the condition right on the start... so..

do {} while will do fine.. and check condition at the end... it's all about choices.. and logic.

example, if you want it to loop by asking a a user input, you will for sure need to ask the input first... like:

Code:
int num;

do
{
    cin >> num;
}
while(num < 0);
Brilliant explanation.
If you wanted to initialize it, couldnt you just use [php]while(true)[/php]
Quote Originally Posted by Kallisti View Post
If you wanted to initialize it, couldnt you just use [php]while(true)[/php]
Lolwut?

He's saying, if you want to do something that you're going to put in a loop without a condition first, you use the do while. Otherwise the first iteration would depend on the condition, where as do,while doesn't.

[php]
while(1 == 0)//false
{
cout <<"Lulz";
}
[/php]

[php]
do {
cout <<"Lulz";
} while (1 == 0);
[/php]

In the first example, nothing would happen, obviously... 1 doesn't equal to 0. But in the second example, it'll output "Lulz" once then move on.

I think...
If you wanted to do it without testing the condition why not just use like
[php]while(true)
{
cout << "lulz\n";
break;
}[/php]
Quote Originally Posted by Kallisti View Post
If you wanted to do it without testing the condition why not just use like
[php]while(true)
{
cout << "lulz\n";
break;
}[/php]
because that is an infinite loop...
do while is used for a situation where you want to run something at least once.
A perfect example would be looping through processes.
Code:
pseudocode:
Process32First
do
{
    code
} while(Process32Next);
Looks better then

Code:
pseudocode:
x = Process32First
while(x)
{
    Code
    x=Process32Next
}
in my opinion
I used a break toxic........

lock plox
Posts 1–10 of 10 · Page 1 of 1
This thread is closed for replies.

Similar Threads

Tags for this Thread

None

Talk with us