
C Programming While Loop
Table of Contents
Loops are used in programming to repeat certain blocks of code. In the chapter you while will learn to create loops in C programming.
A loop is used to repeat a specific block of code until an end condition is reached. There are three types of loops in C programming:
1. For Loop
2. While Loop
3. Do while Loop
Syntax of while loop:
while (testExpression)
{
// This code will execute
}
How does the while loop work?
- while the loop first evaluates test Expression.
- If the value of test Expression is true the while the code inside the loop is executed. test Expression is re-evaluated. This process continues until the value of test example is false(0).
- The while loop terminates when the value of test Expression is false.
Example 1: While loop
// C program to output integer from 1 to 5
#include
#include
int main()
{
int i;
clrscr();
i=1;
while(i<=5)
{
printf("\n%d",i);
i++;
}
getch();
}

Output
1
2
3
4
5
Example 2: While loop
// Factorial (Factorial) evaluation program
//factorial n for positive numbers n! = = 1*2*3...n
#include
int main()
{
int integerNumber;
long long factorial;
printf("Enter an integer number: ");
scanf("%d",&integerNumber);
factorial = 1;
// The while loop ends if the integer is less than or equal to 0
while (integerNumber > 0)
{
factorial *= integerNumber; // factorial = factorial*integerNumber;
--integerNumber;
}
printf("Factorial= %lld", factorial);
return 0;
}
Output
Enter an integer number: 6
Factorial = 720
When the value of test Expression is True and when it is discussed in the Relational and Logical Operator page.