While Loop in C with Example
What is while loop?
As the name indicate, while loop works while the condition is hold. ‘While loop’ contains a condition and a body of the loop. Whenever the condition holds, then the body of the loop works.
General form of the while loop:
While (condition)
{
Body of the loop;
}
|
Let us learn more with an example:
- Program to print first 10 numbers using while loop:
#include<stdio.h>
#include <conio.h>
int main()
{
int n=1;
while(n<=10)
{
printf(“%dn”,n);
n = n+1;
}
getch();
}
|
Code Explanation:
int n=1;
=> n declared and its value is 1.
while(n<=10)
This check the value of n is less than or equal to 10, here value of n is 1 [the condition while(1<=10) is correct], so body of while loop works. That is, display the value of n [ print 1 ].
n = n+1;
Here, the value of n is incremented by 1. We already leaned the increment operator earlier. Now the value of n is 2. Note that, we can use n++ instead of n = n+1.
Now again check this condition: while(n<=10)
Here the value of n is 2, that is also hold the while loop condition (less than or equal to 10). So again print the value of n, ie 2.
This process continues.A
If the value of n become 10,
While (n<=10) condition will hold and print the number 10 and n incremented to 11. Now again check the condition n<=10, but here the value of n is 11, so this condition does not hold and compiler execute next statement after the loop(out of loop).
Here we printed numbers from 1 to 10 successfully.
Sample output:
If we want to print numbers up to 50, then what will be the while condition?
while (n<=10)
- If we want to print numbers from 20 to 60, then what changes will occur?
Here n should be initialized to 20 and condition check up to 60. n = 20; while(n<=60)
Another program:
- Program to print even number in between 100 and 150
#include<stdio.h>
#include <conio.h>
int main()
{
int n=100;
while(n<=150)
{
printf(“%dn”,n);
n = n+2;
}
getch();
}
|
Here n is declared as 100. Then ‘while loop’ check the value of n is less than or equal to 150. Here n is 100 and is less than 150. so printf displays the value of n, is 100.
n = n+2; n is incremented by 2. In here, incrementing by 2 skips the odd number 101.
Again check the condition, here the value of n is 102 and is less than 150. So again display the value of n. This process continues until its value becomes greater than 150.
Sample output:
- To display odd number in between 100 and 150, what changes should do?
Only one change, declare n as 101. ie, int n = 101;
Be First to Comment