+ 4
What's the difference between " while " and " for " ?
Hey What's the difference between " while " and " for " ? I mean we can have: while( x < 10 ) { cin>>y; x++ } Also we can have: for(x = 1;x <= 10;x++) cin>>y And both of them do the same thing:/ So whats the difference between them ?
11 Answers
+ 7
"for" creates a new variable and iterates it while "while" examines a condition...
+ 7
Increment in "for" can be omitted...
+ 6
You didn't initialize "i" inside "for" loop (prepend a "var").
+ 4
it is easier to forget the counter incrementation from the while loop ( and get an infinite loop! ) so for simple counter loop, 'for' is easier to read and maintain ( i think)
+ 4
while loop is more flexible . allows for conditions not linked to a counter increment
eg testing of a user entry, or result of a function call or some event happening...
+ 3
And this one is some mistake I ever found
But this is in javascript not c++ becus I never test it
FOR code:
var a = 1;
for(i=0;i<9;i++){
a++;//varaible "a" was not increase to me so I must ++a
}
WHILE code:
var a = 1;
while(1){//I dont interest in while loop so I dont know how to use it much
a++;//variable "a" was increased up that is different for me
}
+ 3
every 'for' loop can be defined as a 'while' loop
however its usually much easier to see pretty quickly how many iterations a 'for' loop will make (or at least know the range - for example starts at x and ends in y)
"while' loop is usually used for more complicated loops where u dont simply increment an index (or multiply etc) but check if u reached the end of the file or the result of some function is as u want it to be
+ 2
......
But for me not what the heck?!
+ 2
Ok I test it again without prepared with "var" and a was increased....
It's my past bug,maybe
+ 2
'for' loop is generally used when you know the number of iterations beforehand. e.g. to traverse an array of 10 elements you can use for loop and increment the counter from 0 to 9(or 1 to 10 in 1 based indexing).
On the other hand 'while' is used when you have an idea about the range of values on which to iterate, but don't know the exact number of iterations taking place.
e.g. in a BFS
while(!queue_q.empty())
{
// remove element(s)
// add element(s)
}
Here we don't know exactly how many times the loop will run.
In some specific areas like multiprocessing(e.g. in OpenMP), it is necessary to specify the number of iterations. Hence only 'for' loop in used.
However many a times both are inter-convertible.
0
both looping works just the same.
for loop is easy for debugging and counting the number of iterations, while loop is handy for sentinel loops