Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

among for,while,do-while loop which is better in what situation

+1 vote
asked Aug 12, 2020 by Monira Mostafiz (130 points)

1 Answer

0 votes
answered Aug 15, 2020 by Peter Minarik (86,040 points)
edited Aug 15, 2020 by Peter Minarik

There's no better or best

They do basically the same thing: repeat to do the same instruction until the exit condition happens.

for ([initialisation]; [condition]; [post execution instruction])
{
    [loop instructions]
}
while ([condition])
{
    [loop instructions]
}

do
{
    [loop instructions]
} while ([condition]);

So the for offers [initialization], that is run only once, before the loop starts and [post-loop instructions], that is run after every time the body of the loop is executed (except when one leaves the loop before [condition] turns false, e.g. by a break or other means).

Of course, this could be expressed with a while loop as well:

[initialization]
while ([condition])
{
    [loop instructions]
    [post execution instruction]
}

The do-while is special in a way, that the [condition] is at the end of the loop, so the body always runs at least once, while with for and while, if the [condition] is evaluated false, the body may not run a single time.

A do-while could be expressed as a "regular while loop" as well:

[loop instructions]
while ([condition])
{
    [loop instructions]
}

So, as you see, for, while, do-while can be used interchangeably (while some extra work), so which one to pick is mostly a matter of taste.

Of course, if you have an [initialization] and a [post execution instruction], then it makes sense to choose the for loop, but it's not compulsory.

commented Aug 28, 2020 by himanshu jain (140 points)
1.) When we don't the number of  "iteration", we use while loop.
but using while loop we have to keep in mind the flow means increment or decrement.
2.) For loop is very common and useful because it allows us to do all the 3 things at one line
"Initialization", "condition", "flow". which is most useful.
3.) do - while -> when our s/w or program wants at least one iteration of a block.
for example when we play any game:-   We play first and then they ask "Do you want to play again" or "Quit". this is the power of do while.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...