Question:
In the do-while c++ loop format, do you have to put an increment/decrement operator like you do for the while loop?
?
2015-07-22 16:07:11 UTC
The syntax format for the while loop, in c++, is usually:

while (expression)
{
statements;
increment or decrement operator;
}

For a do-while loop, does the syntax format also carry an increment/decrement operator?
Six answers:
?
2015-07-22 16:30:02 UTC
you do not need either a decrement or increment operator. Just some condition that changes so your loop will end.

Even that is not necessary. i sometimes use a while(true){} loop. You can exit the loop with a break or return statement.
david
2015-07-22 20:15:51 UTC
You pretty much need *something* to change about the condition so you can exit the loop. If the condition never changes, then the loop will never end. But that doesn't mean you need to increment/decrement. You might get user input and loop while the input is not "Quit". You might have a loop that runs until it hits the end of a file, or the end of a database query.



I would say that if you're just incrementing or decrementing every time you loop, you would be better off with a for loop instead of a while or do-while loop.
Rashid
2015-07-23 06:39:44 UTC
It depends for what purpose you are using do-while() loop

- If you are using do-while() for input validation e.g. Enter a number from 1-9

then there is no need for Increment/Decrement operator



- If you are using do-while() for couting or finding even or odd number

then you have to use Increment/Decrement operator
dewcoons
2015-07-22 16:14:15 UTC
Yes. You do have to have a value that changes that is used to determine whether or not the loop repeats. If there was no increment/decrement operator then the loop would continue forever.
Chris
2015-07-22 17:02:13 UTC
roger's answer is good, just adding that the only difference between while and do-while is that the latter always runs at least once, while a while loop can get skipped entirely if the condition starts out evaluating to false.
Dan
2015-07-22 22:08:58 UTC
No. Please read the excellent answers you got from Roger and Chris. Then go out and find whomsoever lied to you and slap that person up side the head repeatedly with a sea bass!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...