Page 67 - Modular_V2.0_C++_Flikpbook
P. 67

DIFFERENCE BETWEEN WHILE AND DO-WHILE LOOPS

                 The following are the major differences between while and do-while loops:

                 1.  Pre-Test vs Post-Test:
                         The while loop is a pre-test (or top-test) loop, meaning the condition is checked first
                         before entering the loop body.

                         The do-while loop is a post-test (or bottom-test) loop, meaning the loop body executes
                         first, and then the condition is checked.
                 2.  Minimum Iterations:

                         In a while loop, the minimum number of iterations is zero because the condition is
                         tested before executing the loop body.
                         In a do-while loop, the minimum number of iterations is one, as the loop body executes
                         at least once, even if the condition is false.

                 3.  Interchangeability:
                        while and for loops are interchangeable in most situations.
                        do-while loops, however, cannot always be replaced by a for loop, as they guarantee at
                         least one execution of the loop body.

                    JUMP STATEMENTS

                 Jump statements help to control the flow of a program by making it jump to a different part of
                 the code. These statements allow the program to exit loops, skip iterations, or jump to a specific

                 location in the code. C++ offers four jump statements — break, continue, return and goto —
                 which are used within the loop.
                 The break Statement

                 The break statement is used to exit a loop immediately and transfer control to the statement
                 after the loop. It halts the execution of the loop when a specific condition is met. A single break

                 statement  only  exits one  loop  at  a  time. If used  inside a  nested  loop,  it  will break  only  the
                 innermost loop where it appears. The syntax of the break statement is shown below:
                      while(condition)

                      {
                           if(conditional_expression)
                           {
                                break;
                           }

                      }









                                                                                                                  65
                                                                                                         Loops
   62   63   64   65   66   67   68   69   70   71   72