while statement in c language
It is an entry controlled looping statement. It is basically used when we may not be aware of how many times the loop will execute. In while statement, initialization, condition and updation are performed in different lines. The syntax of while statement is:
while is a keyword which specifies that while statement has started.
Initialization is the way to store some initial value in the control variable. Control variable is the variable which is used to control how many times loop should execute.
Control variable can of any data type like int, float, char etc. In this part, control variable is initialized with some value using assignment operator.
It is basically used to specify the value from which the loop should start. In this part, we can also initialize more than one variable depending upon the requirement.
If more than one variable have to be initialized, they should be separated by commas.
If condition is true, the loop will execute. The loop will continuously execute as long as condition is true.
Loop will terminate when the Condition becomes false.
In condition part, usually control variable is tested to check whether the loop should continue or not.
If condition is initially false, the loop will not execute even once. Multiple conditions can appear in this part but they should be combined with the help of logical operators.
Updation is the way to increment or decrement the value of a control variable.
Updation can be done by using increment/decrement operator, shorthand operators or arithmetic operators.
If there are more than one updation statements, they should be separated by commas.
is the set of instructions which are part of loop and which will execute as a part of for statement. Statement block can contain one or more statements. These instructions will repeatedly execute as long as condition is true.
Statement-X may be set of one or more statements which will be executed after completion of for statement.
While statement can be explained through the following flowchart:
|Program to demonstrate the use of while statement.|
Description of Above Program
In the above program, initially variable i has been assigned value 1.
Value of variable i is compared with 5 to check whether it is less than 5 or not.
If it is less than five, next statement i.e printf(“\n%d”,i); would be executed displaying value of i which is initially 1.
After executing this statement, control would go to updation statement i.e. i++ which would increment the value of i by 1. i now becomes 2.
Again condition i<=5 would be tested. If it is true, printf(“\n%d”,i);would be executed. Again updation will be performed followed by condition.
This process is continuously repeated as long as condition is true.