The Ultimate Guide to Using While Loop in C Programming
While loop in C
In while loop the condition is tested first and then only the statements are executed. While loop in c executes group of statements repeatedly as long as a condition is true.
Syntax: while(condition)
{
statements;
}
Compiler tests the condition first. If condition is true, then the statements in the while loop are executed. The compiler goes back and tests the condition again if the condition is true, then the statements will be executed again. In this way as long as the condition is true the statements are repeatedly executed.
Example: char response = 'y'
while(response == 'y' || response =='y')
{
puts("Hello");
puts("would you like to continue?");
response=getchar();
}
In above example, the first puts() statement inside the while loop wil display ‘Hello’ and next puts() asks the user ‘would you like to continue?’. When the user types y or Y, then getchar() will receive it, and stores in into response. So, as long as the user types y or Y, the while loop will continue to execute.
Program to find the factorial of a given number.
#include<stdio.h>
void main()
{
int i,n;
long int fact=1;
printf("\n Enter a positive number:");
scanf("%d",&n);
i=1;
while(i<=n)
{
fact*=i;
i++;
}
pritnf("\nFactorial of %d is %ld."n,fact);
}
Output:
Enter a positive number: 5
Factorial of 6 is: 720
In above program factorial represents the cumulative products starting from 1 till the number. Factorial of 6 is
6!=1 * 2 * 3 * 4 * 5 * 6=720
If we take i values to increase from 1 to 6 we should multiply its values and store somewhere,say in a variable ‘fact’. so fact=fact*i; Initially we take fact as 1.
Step | fact | i (from 1 to 6) | fact*i |
---|---|---|---|
1 | 1 | 1 | 1 |
2 | 1 | 2 | 2 |
3 | 2 | 3 | 6 |
4 | 6 | 4 | 24 |
5 | 24 | 5 | 120 |
6 | 120 | 6 | 720 |