7.4: While or For?
- Page ID
- 35832
So, which do you use, a while()
or a for()
? You can make simple loops with either of them but for()
loops are handy in that the initialization, termination, and increment are all in one spot. With while()
loops, you only specify the termination, so you must remember to write the variable initializations before the loop as well as the increments within the loop. If you forget either of these your loop will behave erratically. It may fail to terminate altogether, resulting in an infinite loop, as shown below.
a=0; while( a<10 ) { printf(“hello\n”); }
This code fragment doesn’t print the word hello ten times, it prints hello forever (or better to say until you forcibly terminate the program)! Although a
was initialized and tested, it was never incremented. You need an a++;
(or similar) within that loop.