While Loops:
Here's the syntax:
while (some "condition" is true)
{
do something
update the "condition"
}
For example:
#include <stdio.h>
void main( )
{
int counter, limit;
counter = 0;
limit = 10;
while (counter < limit)
{
printf("Counter = %d\n", counter);
counter++;
}
printf("\nOut of the loop!\n");
}
Here's the output:
UNIX prompt >>a.out
Counter = 0
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5
Counter = 6
Counter = 7
Counter = 8
Counter = 9
Out of the loop!
Here's how the loop executes:
- counter = 0
- limit = 10
- Is counter < limit ?
- Yes, it is!
- Execute the printf statement
- Increment counter by one [counter++ ==> counter = counter + 1]
- Now, counter = 1
- limit = 10
- Is counter < limit ?
- Yes, it is!
- Execute the printf statement
- Increment counter by one
- Now, counter = 2
- limit = 10
- Is counter < limit?
- Yes, it is!
- Execute printf statement
- Increment counter by one
- Now, counter = 3
- limit = 10
- Is counter < limit?
- Yes, it is!
- Execute printf statement
- Increment counter by one
- Now, counter = 4
- limit = 10
- Is counter < limit?
- Yes, it is!
- …
- …
- …
- Now, counter = 9
- limit = 10
- Is counter < limit?
- Yes, it is!
- Execute the printf statement
- Increment counter by one
- Now, counter = 10
- limit = 10
- Is counter < limit?
- No, it is not!!
- Fall out of the loop without executing the printf statement!!
Note:
2 differences between FOR and WHILE loops:
- WHILE loops don't initialize the counter variable; has to be done before the WHILE loop.
- WHILE loops don't increment the counter variable; has to be done within the WHILE loop.