Sunday, April 7, 2024

do-while loop in c++



 do-while Loop in c++:

Circles come into utilization when we really want to execute a block of proclamations more than once. Like while the do-while circle execution is additionally ended based on a test condition. The principal contrast between a do-while circle and some time circle is in the do-while circle the condition is tried toward the finish of the circle body, i.e do-while circle is exit controlled though the other two circles are section controlled circles.
you also study while-loop in c++ by clicking on the following loop:

Note: In the do-while loop, the loop body will execute at least once irrespective of the test condition.
syntax:
do
{
   // loop body

   update_expression;
} 
while (test_expression);
Note: Notice the semi – colon(“;”) in the end of loop.

The different pieces of the do-while circle are:

Test Articulation: 
                           In this articulation, we need to test the condition. On the off chance that the condition assesses to valid, we will execute the body of the circle and go to the update articulation. Any other way, we will exit from the while circle.
Update Articulation:
                           Subsequent to executing the circle body, this articulation increases/decrements the circle variable by some worth.
Body: 
         It is the Assortment of explanations i.e, factors and works, and so forth. The condition isn't fulfilled until the condition is executed naturally after an effective cycle. do-while circle, code can be utilized to print straightforward names, execute complex calculations, or carry out useful tasks.


Example : This program will try to print “Hello World” depending on a few conditions. 

// C++ program to illustrate do-while loop
  
#include <iostream>
using namespace std;
  
int main()
{
    // Initialization expression
    int i = 2;
  
    do {
        // Loop body
        cout << "Hello World\n";
  
        // Update expression
        i++;
  
    }
    // Test expression
    while (i < 1);
  
    return 0;
}
Output: 
Hello World

How does a do-While loop execute? 

1.Control falls into the do-while circle.
2.The assertions inside the body of the circle get executed.
3.Updation happens.
4.The stream leaps to Condition
5.Condition is tried.
6.Assuming the Condition yields valid, go to Stage 
7.Assuming the Condition yields bogus, the stream goes outside the circle
8.The stream returns to Stage 2.
9.The do-while circle has been finished and stream has gone external the circle.

Dry-Run of Example 1: 

1. Program starts.
2. i is initialised to 2.
3. Execution enters the loop
  a) "Hello World" gets printed 1st time.
  b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 2 yields false.
5. The flow goes outside the loop.
next loop:   for loop

 

No comments:

Post a Comment

last post

C language Vs C++ language in 2024

Popular Posts