1.3.2.2 while loop
The general form of the while loop is:
while (condition)
Statement
A while loop indicates that a statement is executed when the condition is true. The loop is not completed until the condition is false. and continues execution of subsequent statements outside of the loop program.
Example 17:
#include <stdio.h>
Main ()
{
char c;
C= ' "; /* Initialize c*/
while (c!= ' \x0d ')//Enter END loop * *
C=getche (); /* with echo from the keyboard to receive characters * *
}
In the example above, while loop is to check whether C is a carriage return start, because it was initially initialized to empty, so the condition is true, enter the loop waiting for the keyboard input characters; Once entered return, then c= ' \x0d ', the condition is false, the cycle ends.
As with a For loop, the while loop always checks the condition at the head of the loop, which means that the loop may exit without executing anything.
Attention:
1. Empty statements are also allowed within a while loop.
For example:
while ((C=getche ())!= ' \x0d ');
This loop until you type carriage return.
2. Multiple loops can be nested.
3. The statement can be a statement body, which must be enclosed in "{" and "}".
Example 18:
#include <stdio.h>
Main ()
{
Char c, fname[13];
FILE *FP; /* Definition file pointer/*
printf ("File name:"); /* Prompt to enter file name * *
scanf ("%s", fname); /* Wait for the input file name * *
Fp=fopen (fname, "R"); /* Open File Read Only */
while (C=FGETC (FP)!=eof)/* Reads a character and determines whether to end the file.
Putchar (c); /* Show this character when the file is not finished/*
}
1.3.2.3 Do-while Cycle
The general format for Do-while loops is:
Todo
Statement
while (condition);
The difference between this loop and the while loop is that it executes the statement in the loop before it determines whether the condition is true, if it is true, continues the loop, and if it is false, terminates the loop. Therefore, the Do-while loop executes at least one loop statement at a time.
Also, when there are many statements participating in the loop, use "{" and "}" to enclose them.