Simple command of C++ programming while and do while loop statements

  • 2020-05-07 20:08:26
  • OfStack

While statement
repeats the statement until the expression evaluates to zero.
grammar


  while ( expression )
statement

note
expression tests occur before each execution loop; So the while loop executes zero or more times. The expression must be an integer, pointer type, or class type that contains an explicit integer or pointer type conversion.
The while loop can also be aborted when an 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. Continue to pass the control to the next round of loop while.
The following code clipped the trailing underscore from the string using the while loop:


// 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-- = '\0';

 return szSource;
}
int main()
{
 char szbuf[] = "12345_____";

 printf_s("\nBefore trim: %s", szbuf);
 printf_s("\nAfter trim: %s\n", trim(szbuf));
}

Calculate the termination condition at the top of the loop. If there is no trailing underline, the loop does not execute.


do - while statements
executes statement repeatedly until the specified termination condition (expression) evaluates to zero.
grammar


  do
statement
while ( expression ) ;

note
The termination condition will be tested after each execution loop. So the do-while loop will execute one or more times, depending on the value of the termination expression. The do-while statement can also terminate when the break, goto, or return statements are executed in the statement body.
expression must have an algorithm or pointer type. The execution process is as follows:
Execute the body of the statement.
Next, calculate 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 (non-zero), this process is repeated from step 1.
The following example demonstrates 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);
}


Related articles: