Difference between While loop and For loop. Where we need to use While/For?
Please explain with example
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Santhosh Kumar JayaramanRank #563 · 4.3K reputationPosted Oct 9, 2012, 1:53 AM EDT
only difference is before using variable in while loop condtion, you need to declare it before but with for its not required. You can declare in for loop also.
While( int i=1>0)
{
}
The above is not possible. We have to declare i earlier and should assign some value
int i=2;
while(i<5)
{
}
but for (int i=1;i>0;i++)
{
}
This is allowed
R ACHUTHA181 reputationPosted Oct 9, 2012, 1:54 AM EDT
In a while loop if continue is used before the increment of a variable is done it converts into a infinite loop.
i=1;
while(i<10)
{
/* do stuff */
if(i==6);
continue;
i++;
}
The above piece of code will turn into an infinite loop.
for(i=1;i<10;i++)
{
/* do stuff */
if(i==6);
continue;
}
In the above for loop the value of will be incremented once it attains the value 6.
Therefore it will not turn into a infinite loop.
VulpesRank #55 · 29.2K reputationPosted Oct 9, 2012, 2:02 AM EDT
So it's just a matter of which is the more convenient (or even personal taste) for a given scenario.
Prashantkumar D7 reputationPosted Oct 9, 2012, 3:27 AM EDT
Prashantkumar D7 reputationPosted Oct 9, 2012, 3:27 AM EDT
Prashantkumar D7 reputationPosted Oct 9, 2012, 3:28 AM EDT