"For" vs. "While"

Can someone please explain simply the difference between using "for" and "while" loops?

Thanks!

-Incline
Investigate this thread

http://www.cplusplus.com/forum/general/107828/
In general, for loops can be converted to an equivalent while loop like so:
1
2
3
for(init; cond; incr) {
    statements;
}

is
1
2
3
4
5
init;
while(cond) {
    statements;
    incr;
}

The advantage of while loops is that the init, cond, and incr portion are together so it is easier to see that, say, the loop is checking each number in a list, or something. Additionally, it keeps any variables declared in init in the scope of the for loop, unlike my while example which would have them be at the outer scope unless you added additional brackets.
they can both accomplish the same thing. The only thing that's different about them is syntax. Some times it's more convenient to use a while, and other times it's more convenient to use a for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for( initialization;  condition;  increment )
{
    body;
}

//
// is the same as:
//

initialization;
while( condition )
{
    body;
    increment;
}


There's a subtle difference here with the continue; statement, but whatever.



Anyway All this really means is:

- while is generally used when you want to loop an unknown number of times... or when the number of times can vary due to external (user) input

- for is generally used when you know the number of iterations up front


EDIT: I so got ninja'd
Last edited on
Haha, thank you all.

@Disch

What the heck is ninja'd?
Last edited on
You get ninja'd when someone sneaks in a reply before you finished typing yours.
Topic archived. No new replies allowed.