initialization;
while( test expression )
{
Body of loop
...........
}
while loop is a pretest loop. It uses a test expression to control the loop. The test expression should contain a loop control variable. The initialization of loop control variable should be done before loop starts. Update condition must be included in the body of loop. The loop iterates while the test expression is true and when it becomes false program control passes to the line of code immediately following the loop.
int i=1;
while(i<3)
{
printf("%d", i);
i++;
}
In above code initial value of i is 1. The condition ( i<3) is true, so printf() statement prints 1, integer value of i. After that update condition increases the value of i, so value of i becomes 2. Again condition ( i<3) is true, so printf() statement prints 2 which is integer value of i. After that update condition changes the value of i and the value becomes 3. But the condition (i<3) is false and control passes to the line of code immediately following the loop.
C program to generate Fibonacci series : 0,1,1,2,3,5,8,13,21,34
#include<stdio.h>
int main()
{
int a=0,b=1,c=0;
printf("\n
%d , %d",a,b);
while(c<=21)
{
c=a+b;
printf(",
%d",c);
a=b;
b=c;
}
return 0;
}
0 Comments