C++: When to use For Loop & While Loop?
Apr 5, 2012 at 8:12pm UTC
Hi, I have just started implementing loops into my programs. Therefore I am wondering if someone can provide me examples of perfect situations of when to use For Loops and when to use While Loops, thank you.
Apr 5, 2012 at 8:16pm UTC
You use a loop whenever you want to repeat something. for loops when you need to count or keep track of something between iterations, while otherwise.
Apr 5, 2012 at 8:19pm UTC
For example,
while loop:
1 2 3 4 5 6 7 8
size_t strlen( const char *s )
{
size_t len = 0;
while ( *s++ ) len++;
return ( len );
}
for loop:
1 2 3 4
int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for ( int i = 0; i < 10; i++ ) std::cout << a[i] << ' ' ;
std::cout << std::endl;
Very often there is no difference between using while loop or for loop, and even compilers generate the same code for this two kind of loops.
Try to rewrite my example with opposite kind of llop.
Last edited on Apr 5, 2012 at 8:22pm UTC
Topic archived. No new replies allowed.