C Programming While Loop

Last modified by Microchip on 2023/11/09 09:06

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


while (expression) statement

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

While loop schematic


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

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)
While loop