While loops are a
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
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.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
Shubhranshu Shekhar is a coding instructor, mentor, and founder of VSIT Delhi with 20+ years of teaching experience (since 2004). He has guided many students who are now working in multinational companies and specializes in Full Stack Development, Python, Digital Marketing, and Data Analytics.