Answer in brief
The while loop repeats a body while its condition is true. It is an entry-controlled loop because the test comes before the body.
Syntax
while (condition) {
/* repeated statements */
}
Working
- Set the initial values before the loop.
- Test the condition. If false, leave the loop.
- Execute the body when true, then return to the condition.
Example trace
The example starts with i = 1. The test i <= 3 succeeds, so 1 is printed and i becomes 2. The next iterations print 2 and 3. After the third update, i becomes 4. The condition is now false and the loop ends. The update is essential: without it, this example would continue printing 1.
Uses and important points
while is useful when repetition is controlled mainly by a condition, such as reading values until a sentinel is entered. The body can execute zero times. Use braces for multiple statements. An accidental semicolon after the condition creates an empty body. When continue is used, make sure an essential update is not skipped.
Complexity
A loop that performs constant work once for each of n values takes O(n) time. This example prints exactly three values, so the displayed run has fixed work. Generalising its limit to n gives O(n) time and O(1) auxiliary space because only a counter is needed.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int i = 1;
while (i <= 3) {
printf("%d\n", i);
++i;
}
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
1
2
3