ITDeveloper : C Programming
C Programming
Step by Step Tutorials
![]() Share with a Friend |
while Loop in C
A pre-tested loop is another name for a while loop. A while loop, in general, enables the execution of a section of code repeatedly in response to a specified boolean condition. It may be seen as an if statement that is repeated. When it is unknown how many iterations there will be ahead of time, the while loop is typically employed.
Syntax of while loop in C language
The syntax of while loop in c language is given below:
while (condition) {
//code to be executed
}
Steps:
- The whileloop evaluates the condition inside the parentheses ().
- If conditionis true, statements inside the body of while loop are executed. Then, condition is evaluated again.
- The process goes on until conditionis evaluated to false.
- If condiitonis false, the loop terminates (ends).
Flowchart of while loop in C
Example of the while loop in C language
// Print numbers from 1 to 10
#include<stdio.h>
int main()
{
int i=1;
while ( i <= 10 )
{
printf( "%d \n" , i);
i++;
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
Here, we have initialized i to 1.
- When i = 1, the condition or test expression i <= 10is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2.
- Now, i = 2, the condition i <= 10is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3.
- This process goes on until ibecomes 11. Then, the condition i <= 10 will be false and the loop terminates.
Program to print table for the given number using while loop in C
#include<stdio.h>
int main()
{
int i=1,number=0,b=9;
printf("Enter a number: ");scanf("%d",&number);
while ( i <= 10 )
{
printf("%d \n",(number*i));
i++;
}
return 0;
}
Output 1:
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Output 2:
Enter a number: 10
10
20
30
40
50
60
70
80
90
100