THE WHILE STATEMENT
THE WHILE STATEMENT
The basic format of the while statement is shown below:
while(test condition)
{
body of the loop
}
The while is an entry-controlled loop statement. The test-condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again.
This process of repeated execution of the body continues until the test condition finally becomes false and the control is tranferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop.
The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice to use braces even if the body has only one statement.
A simple count from 1 to 100
/* A program that displays the numbers between 1 and 100.*/
#include <stdio.h>/* A program that displays the numbers between 1 and 100.*/
int main (void)
{
int n;
n = 1; /* loop initialization */
/* the loop */
while (n <= 100) /* loop condition */
{
printf
("%d ", n); /* loop body */n = n + 1; /* loop update */
}
return (0);
}
Comments
Post a Comment