I'm still quite a noob, and I've been reading a bit on learncpp.com and just completed a semester of C++ in college and I'm a bit confused about the specific advantages of a for loop over a while loop.
I understand what you have 3 parameters in the head of a loop, and so far the structure that we've been using has been something like this.
for (int i=0; i<=25; i++){
//for statements
}
Whereas I can do the exact same thing with a while loop with an initial statement:
int i=0
while (i<=25){
//statements
i++;
}
For some reason my brain really enjoys thinking in terms of while rather than for, is there really any large advantage for for's? If so can you show an example??
I only use while loops when i have conditions like:
1 2 3 4 5
bool condition = false;
while(!condition)
{
}
since you can't use boolean conditions in a for loop like this.
so while or do while has an advantage over for when it comes to other conditions than integers.
In "for loop",eventhough your conditions were met it will still do the loop. While in "while loop",once it became false i t will stop the loop,try binary search to see what i mean.
For loops are great when you need to iterate a certain number of times.
While loops are great when you need to loop until a certain condition becomes false.
In "for loop",eventhough your conditions were met it will still do the loop. While in "while loop",once it became false i t will stop the loop,
This is not correct. Once the condition in a for loop becomes false, the loop will stop.
I like to compare them by readability, and when it comes to usage of "for" vs "while", like many others i use while-loops for simpler stuff, and for-loops for the little more complex stuff. Sometimes a for-loop can make a complex loop much easier to read, in comparison to a while loop.
As Dufresene has already pointed at, while and for loops are virtually identical in their operations. Logically, a while loop may be more appropriate over a for loop, however. For instance, lets say you are looping user input and are looping until char continue = 'n', you could write it in two ways
for(;continue != 'n';)
or
while(continue != 'n')
From a readability stand point, I'd prefer the while loop, but again they both will work just fine.