While Loop in C

While loops are a condition-controlled loop, means they continue repeating the statements, until some condition is met. While loop, first checks the condition, if the condition is true then execute the statements. After statement execution, again it tests the condition, if true, repeat the statements. It repeats until the boolean expression is false, if the condition is false, the while loop is terminated. Statements can be single or multiple lines of code to be repeated.

The Syntax of While Loop in C.

while(condition)
{
	//statements
}
  • Here, the condition can be any boolean expression, which can return true or false.
  • Statements can be single or multiple lines of code to be repeated.
  • It repeats the statement until condition returns true.
  • If the condition is false, while loop is terminated.

Example 1: C Program to print, Coder Mantra, 10 times.

#include<stdio.h>
int main()
{
int n=1;
	while(n<=10)
	{
		printf("\nCoder Mantra");
		n++;
	}
return 0;
}

Example 2: C program to print 1 to 10.

#include<stdio.h>
int main()
{
int n=1;
	while(n<=10)
	{
		printf("%d\t",n);
		n++;
	}
return 0;
}
Sample Output:
1 2 3 4 5 6 7 8 9 10

The above program will print 1 to 10 as output. An initial value of a variable n is 1, Value of n is less than 10, so condition is true, after that it prints the value of n, then increase the value by 1. Every time it checks the condition and repeats the statements until the condition is not false.


Example 3: C example to calculate sum of even numbers only.

#include<stdio.h>
int main()
{
int i=1,s=0,n;
	while(i<=10)
	{
		printf("\nEnter a number");
		scanf("%d",&n);
		if(n%2==0)
		{
			s=s+n;
		}
		i++;
	}
	printf("Sum of Even Numbers : %d",s);
return 0;
}

Above program will accept 10 numbers, and check for even numbers. IF the number is even, then it calculate the sum of that numbers. Hence, we can use, if condition in looping also.