0
What is do while loop. Give an example.
5 Answers
+ 8
do
{
// something
}
while ( // condition is true );
The above code will at least run once.
+ 8
A do....while loop is a control flow structure used to loop at least once or through a given number of iterations provided the condition is True.
Unlike other loops, the do...while loop MUST print something regardless of whether it satisfies the condition or not.
THE do...while LOOP IS TERMINATED WITH A SEMICOLON AFTER THE CONDITION (If you are using C, C++, Java or JavaScript).
For example;
If 25 is assigned to the counter, the do...while might not be helpful if the condition is (counter < 20) as it will allow 25 to print before testing the condition.
#include <iostream>
using namespace std;
int main() {
int counter = 25;
do{
//Statement to be executed ( print counter)
cout<<counter<<endl;
counter++;
}
while (counter < 20);
return 0;
}
Output:
25
https://code.sololearn.com/c9GCoLP5Q7Q7/?ref=app
+ 6
cin>>i;
do
{
cout <<i;
i--;
}
while (i>1);
Input: 3
Output:321
Input:0
Output:0
Loop runs once no matter the condition.
0
In normal while, you check the condition first. If true, loop, else, leave. In do... while, you first loop, then check the condition. If true, loop, else, leave. The difference is you can fail the condition before looping even once in normal while.