While vs. For vs. Do/While

Hi All,

I was wondering what the specific circumstances one would use for, while, and do/while loops? I'm reading my text and they seem to do the same thing, just in different ways. Thanks!
i think it's a question of taste ....... although there is little difference between while and do while .... " while " checks the condition and then enters in body of cycle but " do while " does body of cycle and then checks condition
boston wrote:
they seem to do the same thing
They do.
1
2
3
4
for( int i = 0; i < 10; i++ ) { ...; }
//is the same as
int i = 0;
while( i < 10 ) { ...; i++; }
1
2
3
4
do { ...; } while( b );
//is the same as
...;
while( b ) { ...; }
Scope may differ...
Last edited on
(generally)
Use a while loop to run until a condition is met
1
2
3
4
while(dontQuit)
{

}

Use a for loop to iterate over container of some description
1
2
3
4
for (int i = 0; i < someAmount; ++i)
{

}

Use a do while loop if you want the code to run at least once

Are there times when one of them would be better suited for a task than the others?
they do the same thing but there is one BIG difference from side of usability .... in for cycle you do i++ and don't care for changing argument then ........ but in while or do while you must change " i " in the body of cycle .... but very often you forget about it and your cycle will be endless .... it is uncomfortable .... if you must change your " i " only by adding 1, i recommend you to use for cycle
Hi
I agree with @LBEaston.
Use a 'for' loop when you want to read/modify every item in the array/container.
If you're planning to break out of the loop early, for example once you've found something, it might be better to use a 'do...while' or a 'while'.
That way you're minimizing use of the 'break' statement which is generally considered good style. For example see section '4.24 Flow Control Structures' of the JSF C++ coding standards.

Also if you're keeping track of two indices, I think a '(do...)while' loop is much more readable, as in this string-reversal code:
1
2
3
4
5
6
7
8
9
10
11
12
13
const char* s1 = "Here is a string...";
char s2[ strlen(s1) + 1 ];

int from = strlen(s1) - 1;
int to   = 0;

do
{
    s2[to] = s1[from];
    ++to;
    --from;
} while ( from >= 0 );
s2[to] = '\0';
Last edited on
Mathhead200's answer contains an error:

while (b) { ... }

is NOT the same as

do { ... } while (b)

because the latter will ensure execution of the body at least once, which is contrary to the former's behavior.

To see this in practice, run this:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
 
using namespace std;
 
int main()
{
    int i = 10;
    while (i < 10) { cout << "While loop execution." << endl; }
    do { cout << "Do loop execution." << endl; } while (i < 10);
    return 0;
}

Output:
Do loop execution.
Use a for lopp when an index is involved / increment required (iterators) like the for(int i = 0; i < x; ++i)

Use while(expr) { } when there's no increment necessary

Use do { } while(expr); if the above statement is true plus what webJose (at least once)

Generally use that construct that's the most handsome / least error prone which is mostly the for loop
Awesome, thanks everyone!
keineahnung wrote:
That way you're minimizing use of the 'break' statement which is generally considered good style
It is? I use break and return all the time in loops. I think it make code more readable.
Example:
1
2
3
4
5
6
7
//linear search
template <typename T>
int find( T *arr, T &trg, int size, int index = 0) {	//We need an array, target, size, and possibly a starting point
	for( ; index < size; index++ )			//Loop trough each index in [index, size)
		if( arr[index] == trg )			//Check if the target is in the array at this index
			return index;			//If it is, we're done! Return the current index
}


webJose wrote:
Mathhead200's answer contains an error:

while (b) { ... }

is NOT the same as

do { ... } while (b)
That's not what I said. Why did you chop up my code block, it was 4 lines long. What I said was:
Mathhead200 wrote:
1
2
3
4
do { ...; } while( b );
//is the same as
...;
while( b ) { ...; }
Scope may differ...
I was inferring that all of the "...;" were the same statement (or block of statements.) Sorry if I was unclear.
LOL! My bad entirely. I didn't even pay attention to those little tiny dots. So I stand corrected.
@Mathhead200
keineahnung wrote:
That way you're minimizing use of the 'break' statement which is generally considered good style
It is?


www2.research.att.com/~bs/JSF-AV-rules.pdf
AV Rule 191 (MISRA Rule 58)
The break statement shall not be used (except to terminate the cases of a switch statement).
Exception: The break statement may be used to “break” out of a single loop provided the
alternative would obscure or otherwise significantly complicate the control logic.


No offense, @Mathhead200, but these guys put fighter jets in the sky (and keep them up there ;). If they say you should go careful with break, I'm inclined to take note.
keineahnung wrote:
"The break statement may be used to "break" out of a single loop provided the
alternative would obscure or otherwise significantly complicate the control logic."
- www2.research.att.com/~bs/JSF-AV-rules.pdf
Kinda' what I meant...

Standards within a group of programmers are very important. Enforcing them on other just because you want them to write code like you, eh... I stand by my "clean" use of break and return.
Topic archived. No new replies allowed.