Academic Program

while Loop

While Loop

while loop statement in C programming language repeatedly executes a target statement as long as a given condition is true.

Syntax

while (expression) statement

If expression is true, statement will be executed and then expression will be re-evaluated to determine whether or not to execute statement again. It is possible that statement will never execute if expression is false when it is first evaluated

whileloop.png

Example

1
2
3
4
5
6
int i = 0;  //loop counter initialized outside of loop
 
while (i < 5) // condition checked at start of loop iterations
{
    printf("Loop iteration %d\n", i++); //(i++) Loop counter incremented manually inside loop
}

The expected output for this loop is:

Loop iteration 0
Loop iteration 1
Loop iteration 2
Loop iteration 3
Loop iteration 4

Unlike a for loop, the expression must always be there. while loops are used more often than for loops when implementing an infinite loop, though it is only a matter of personal choice.

Infinite Loops


while loop with expression=1 can execute indefinitely (can leave loop via break statement)
InfiniteWhileLoop.png