+ 1
When to use while loop and when to use for loop? is their any perfect example to answer my question
1 Answer
+ 3
while loop is generally used when you don't know the number of times the loop should run.
eg:-
while(flag == true)
{
if(someCondition)
flag = false;
}
for loop is used when you know the number of times the loop should run.
eg:-
for(int i = 0; i < array.length; i++)
{
// do something to each element of the array
}
this is how they are generally used, however they can interchange roles with a little work around.