C++

Example Of A C++ Do-While Loop

When a block of statements needs to be repeated until the specified loop condition returns false, a loop is employed, as was covered in the last tutorial on the while loop. We’ll see the do-while loop in this tutorial. While loop and do-while loop are similar, there is a distinction between them: In a while loop, the statements inside the body of the loop are run first, and only then is the condition evaluated. In a while loop, on the other hand, the statements inside the body of the loop are executed first, and only then is the condition evaluated.

Do-while loop syntax

do
{
   statement(s);
} while(condition);

How does the while loop operate?

The statements inside the loop are first executed, after which the condition is evaluated. If the condition evaluates to true, the control then goes to the “do” statement, where it is repeated until the condition evaluates to false. Control shifts to the next statement in the program after do-while once condition returns false.

do-while loop example in C++

#include <iostream>
using namespace std;
int main(){
   int num=1;
   do{
      cout<<"Value of num: "<<num<<endl;
      num++;
   }while(num<=6);
   return 0;
}

Output:

Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
Value of num: 6

Example: Using a do-while loop to display array components

An integer array with four members is present here. We are utilizing a do-while loop to display its components.

#include <iostream>
using namespace std;
int main(){
   int arr[]={21,99,15,109};
   /* Array index starts with 0, which
    * means the first element of array
    * is at index 0, arr[0]
    */
   int i=0;
   do{
      cout<<arr[i]<<endl;
      i++;
   }while(i<4);
   return 0;
}

Output:

21
99
15
109

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button