while statement in c language

Preview
You must first complete for statement in c language | Nesting of for in c language before viewing this Lesson

while statement in c language

While statement is an entry controlled iterative statement. The syntax of while statement is:

Initialize;
while(Condition)
{
Statements;
Update;
}

while is a keyword to start while statement.

Initialize:  In this part, we assign some value to the control variable which controls number of times the loop should execute.

Example

counter=1;

Condition: It is a relational or logical expression to verify whether the for statement should continue or not.

Example

counter<=5;

Update: Increasing or decreasing the value of control variable comes under this part.

Example

counter++

Statements are set of instructions which will repeatedly execute as long as condition evaluates to true.



Program
#include<stdio.h>
int main()
{
int counter;
counter=1;
while(counter<=5)
{
printf(“\n%d”,counter);
counter++;
}
return(0);
}
Output
1
2
3
4
5

Description of Program

Initially variable counter is assigned value 1.

Value of counter is tested against 5.  If  value of counter is less than five, printf(“\n%d”,counter) gets executed. 

After this statement, update statement counter++ increments value of counter by 1  to make it 2.

Condition counter<=5 is tested again. If condition is true, printf(“\n%d”,i) is executed again.

Update statement will work again. 

This process repeats as long as condition remains true.

RELATED PROGRAMS

Best Books of Computer Science





 

Lesson tags: program of while statement in c, while statement in c
Back to: C Programming Language