while loop in c
while loop in c, works similar as for loop, but the only difference is initialization is done outside loop and iteration is done inside loop body. It is an entry control loop.
Syntax
initialization;
while(expression)
{
// statements
// iteration
}
initialization | The initial value from where the loop starts. |
condition | It checks the condition is true or false and then executes the statements. |
iteration | It continues the loop, until test condition becomes false. |
Example
#include<stdio.h>
void main()
{
int j = 0; // initialization
while (j < 10) // condition
{
printf("%d ", j);
j++; // iteration
}
}
Explanation
- j=0; is initialization of while loop, it means loop starts from value 0.
- while (j < 10), Here, j < 10 is test condition, which test the value of j is less than 10 on each loop cycle. and execute statements until j value becomes 10 and stops loop execution.
- j++, it is iteration, which increases value of j by 1.