- The loop body in the while loop executes as long as the test expression is true.
- It is also an entry controlled loop.
Syntax
while (Test Expression){
loop-body ;
Updation expression;
}
Description
- The working of while loop is the same as that of for loop.
- Here initialization expression will be placed before the while statement.
- Then evaluate test expression.
- If it is true loop body and updating expression are executes.
- This process will continue until the test expression becomes false.
- Here the updating expression is placed within the body of the loop.
Example
PROGRAM TO DISPLAY NUMBERS FROM 1 TO 10 USING WHILE LOOP
#include
main()
{
int i;
i=0;
while(i<10){
printf("%d",i);
i+=1;
}
}
Output: 0 1 2 3 4 6 7 8 9
Working of program
- in the main function, the execution of the program starts
- First executes initialization expression,ie set i=0.
- Then evaluates condition expression i<10.ie 0<10 ,it is true, so jump to the body of the loop.
- in the body of the loop, it has given to print value of i.ie current value of i is 0, so print 0.
- next evaluate condition expession.here increment the value of i.ie i=i+1,ie i=0+1=1.
- Again evaluates condition expression i<10.ie 1<10 and loop body works.
- repeat steps 3,4,5,6 until the condition becomes false.
- when i=10, the condition expression will not satisfy. ie 10<10 is false.so exit from the loop.
Sample Programs
- C program to print numbers up to a given limit.
- C program to print even numbers up to a given limit.
- C program to print odd numbers up to a given limit.
- C program to find the sum of even numbers and sum of odd numbers up to a given limit.
- C program to print factorial of a number.
- C program to print the Fibonacci series up to a limit.
- C program to check whether a number is prime or not.
- C program to check whether a number is a palindrome or not.
- C program to find the sum of natural numbers up to a limit.