WHILE LOOP
The syntax of the while loop is:
- while (test expression)
- The while loop evaluates the test expression inside the parenthesis ().
- If the test expression is true, statements inside the body of while loop are executed. Then, the test expression is evaluated again.
- The process goes on until the test expression is evaluated to false.
- If the test expression is false, the loop terminates (ends).
- When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2.
- Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3.
- This process goes on until i becomes 6. When i is 6, the test expression i <= 5 will be false and the loop terminates.
{
// statements inside the body of the loop
}
How while loop works??
Example :
#include <stdio.h>
void main()
{
int i = 1;
while (i <= 5)
{
printf(" %d ", i);
++i;
}
}
Output : 1 2 3 4 5
Now Let's iterate above example
- Here, we have initialized i to 1.
Comments