While loop in C will execute the statement or block of statement till the test condition evaluates to true.
Important points regarding while loop
Test condition in while loop is evaluated before the body of the while loop is executed. And the code in the while body is executed until the test condition evaluates to false.
Prefer usage of while loop over for loop when number of iteration to be performed is not fixed or is unknown.
//code to execute
What is the difference between for loop and while loop?
value of i=1
value of i=2
value of i=3
value of i=4
value of i=5
value of i=6
value of i=7
value of i=8
value of i=9
How above code works?
At first ‘i’ is initialized with value 1.
Then condition i<10 of the while loop is checked. Since 1<10, so control enters the body of while loop and value of I is printed as 1.
Immediate next step is to increment the value of i (i++). This changes the value that ‘I’ variable holds to 2.
Again condition i<10 is validated. 2<10 evaluates to true so gain control enters while body and value of ‘i’ is printed. Again value of ‘i’ is incremented and it holds value 3.
This process continues till value of i reaches to 10. Since 10<10, will evaluate to false so this time control does not get entry within while loop’s body. It goes out of the loop.
This marks the end of while loop.