This is the explanation i gave when i was asked how to identify the scenario suited for these 3 flow statement:
I think I’ll use the flow statement that best fit the context of my problem. If i need a finite loop, my first choice would be the for loop. Actually, if you are not aware of this, the for and while loop are interchangeable. Take a look a look at the syntax here:
for (int i = 0; i < 20; i++) {
}
int i = 0;
while (i <20){
i++;
}
So I could also use while loop for a finite loop as well. I need to initialize a counter variable before the while loop, perform whatever i need and at the end i increment/decrement the counter. So using while is not straightforward. for loop prettier way of looping :). I have lesser codes to maintain. An example of a scenario to use for loop is i want to print out a list of names of classmates that is stored in a String array.
I think from the syntax, you should be able to differentiate while and do-while. while test condition upfront. do-while test at the end. So the statements in while block may not be executed. do-while will be executed at least once.while loop is suitable when I cannot predict the number times to execute the block or i don’t want to execute the statements at all e.g. i retrieved name records from a table in the database. I don’t know how many records i have retrieved. So I iterate the loop e.g. print out the names, as long as there is next record. And if there are no names retrieved from the database, the while block will not be executed at all.
do-while is most suitable when I want to test a condition after running the first iteration of the loop.e.g I need to restrict user to enter a number between 1 to 10 in the input dialog box. Anything outside this range, my program will keep prompting an error message and then prompt an input dialog box again.