The While loop
A while loop is an event controlled loop. It is a control flow statement that, allow the code to be executed repeatedly based on a given condition.
To while construct consists of a block of code and a condition. The condition is evaluated and if the condition is true, the code within the block is executed. This repeats until the condition becomes false.
EXAMPLE 1:
/*Simple while loop that prints numbers 10 per line */
#include<stdio.h>
int main(void)
{
//local declarations
int num;
int linecount;
//statements
printf("Enter an integer between 1 and 100:");
scanf("%d",&num); //Initialization
//Test number
if(num>0)
num=100;
lineCount=0;
while(num>0)
{
if(lineCount<10)
lineCount++;
else
{
printf("\n");
lineCount=1;
} //else
printf("%4d", num--); // num-- updates loop
} //while
return 0;
}
OUTPUT:
Enter an integer between 1 and 100: 15
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
EXAMPLE 2:
/* Add a list of integers from the standard input unit */
#include<stdio.h>
int main(void)
{
//local declarations
int x;
int sum=0;
//statements
printf("enter your numbers: <EOF> to stop.\n");
while(scanf("%d",&x)!=EOF)
sum+=x;
printf("\n The total is: %d\n",sum);
return 0;
} //end main
Output:
Enter your number: <EOF> to stop
15
22
3^d
The total is: 40