Node:while, Next:do...while, Previous:Loops, Up:Loops
while
The simplest of the three is the while
loop. It looks like this:
while (condition) { do something }
The condition (for example, (a > b)
) is evaluated every time the
loop is executed. If the condition is true, then statements in the
curly brackets are executed. If the condition is false, then those
statements are ignored, and the while
loop ends. The program then
executes the next statement in the program.
The condition comes at the start of the loop, so it is tested at the start of every pass, or time through the loop. If the condition is false before the loop has been executed even once, then the statements inside the curly brackets will never be executed. (See do...while, for an example of a loop construction where this is not true.)
The following example prompts the user to type in a line of text, and
then counts all the spaces in the line. The loop terminates when the
user hits the <RET> key and then prints out the number of
spaces. (See getchar, for more information on the
standard library getchar
function.)
#include <stdio.h> int main() { char ch; int count = 0; printf ("Type in a line of text.\n"); while ((ch = getchar()) != '\n') { if (ch == ' ') { count++; } } printf ("Number of spaces = %d.\n\n", count); return 0; }