/    /  While Loop

Loops in C

 

C has three loop statements:

  • while
  • for
  • do-while

while and for are pre-test loops, do-while may be a post-test loop. All three loops continue when the condition is true and terminates when it is false.

 

While Loop

 

The while loop is a pre-test loop. It tests the condition before every iteration of the loop.

 

While Loop

Syntax:

 

while (condition)
{
statements(s);
}

 

Example Program:

 

To print first ‘n’ natural numbers.

 

#include<stdio.h>
void main()
{
int i=1,n; 
printf("Enter limit\n"); 
scanf("%d",&n); 
while (i<=n)
{
printf("%d\t", i); 
i++;
}
printf("end of the program");
}

Output:

 

while loop