While statement
executes the statement repeatedly until the expression evaluates to zero.
Grammar
while (expression)
statement
Note
The expression test occurs before each loop execution, so the while loop executes 0 or more times. An expression must be an integral type, a pointer type, or a class type that contains an explicit integer or pointer type conversion.
The while loop can also be aborted when the interrupt, navigation, or regression is executed in the body of the statement. Use the Continue statement to end the current iteration without exiting the while loop. continues to pass the control to the next round of loops while.
The following code uses a while loop to trim a trailing underline from a string:
While_statement.cpp
#include <string.h>
#include <stdio.h>
Char *trim (char *szsource)
{
char *pszeos = 0;
Set Pointer to character before terminating NULL
Pszeos = Szsource + strlen (szsource)-1;
Iterate backwards until non ' _ ' is found while
(Pszeos >=-Szsource) && (*pszeos = ' _ '))
*pszeos -= ' the ';
return szsource;
}
int main ()
{
char szbuf[] = "12345_____";
printf_s ("\nbefore Trim:%s", szbuf);
printf_s ("\nafter Trim:%s\n", Trim (szbuf));
The termination condition is computed at the top of the loop. If there is no trailing underline, the loop does not execute.
Do-while Statement
repeatedly executes the statement until the specified termination condition (expression) evaluates to zero.
Grammar
Do
statement while
(expression);
Note
The test for terminating the condition will be performed after each loop, so the Do-while loop executes one or more times, depending on the value of the terminating expression. The Do-while statement can also be terminated when a break, Goto, or return statement is executed in the body of the statement.
Expression must have an algorithm or pointer type. The execution process looks like this:
Executes the statement body.
Then, compute the expression. If expression is false, the Do-while statement terminates, and control is passed to the next statement in the program. If expression is true (not 0), the process will be repeated starting with the first step.
The following example shows the Do-while statement:
Do_while_statement.cpp
#include <stdio.h>
int main ()
{
int i = 0;
Do
{
printf_s ("\n%d", i++);
} while (I < 3);
}