0
What is the difference beetween for and while loops
2 Answers
+ 6
Differences:
for loop:
for(variable; condition; itteration)
while loop:
while(condition).
for loop usually depends on a variables itteration, while loop depends only on a condition.
When to use these?
For loop:
I always know how many times I'm going to loop. (As @Joshua said)
While loop:
I don't know how many times I'm going to loop.
Why these rules?
Here's a while loop turned into a for loop:
int i = 0;
while(i < 10){
// do stuff
i++;
}
So what's the difference from that to this?:
for(int i = 0; i < 10; i++)
{
// do stuff
}
I'm glad you asked.
Notice in the while loop the variables scope is actually dependent on the function, rather than the loop. So the variable for incrementation is actually a local variable. While the for loop variable is destroyed after the use of the loop. This could cause extra memory usage since the lifetime of the variable for the while loop is extended, yet you would only be using that variable for the loop anyway.
+ 1
i think for is usually used when you know exactly how much times you are doing the loop