What is do while loop. Give an example. | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

What is do while loop. Give an example.

11th Apr 2017, 2:44 AM
Tehreem
4 Antworten
+ 8
do { // something } while ( // condition is true ); The above code will at least run once.
11th Apr 2017, 6:20 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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
11th Apr 2017, 8:12 AM
Tusiime Innocent Boub
Tusiime Innocent Boub - avatar
+ 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.
11th Apr 2017, 2:58 AM
Pixie
Pixie - avatar
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.
11th Apr 2017, 3:49 AM
Denis Felipe
Denis Felipe - avatar