Do while loop | Sololearn: Learn to code for FREE!


Do while loop

I understand how does a do while loop works, it first runs the code once then check the condition. What is the purpose of a 'do while loop' and is there any real life examples? Thank you

12/15/2018 3:18:43 PM

Zahraddeen Mahmud

5 Answers

New Answer


Like Taste has shown, do-while loops are really great when receiving and validating input, and the reason is because when you are accepting input, you are ALWAYS receiving 1 input at the minimum.


Imagine you want to validate user input. If there is no do while loop (like in python where a do while loop doesn't exist), you have to do this (pseudocode): input = getUserInput(); while(input != valid) { input = getUserInput(); } So you have to write the line "input = getUserInput();" twice. With a do while loop, you can simply do: do { input = getUserInput(); } while (input != valid); Now you have to write the line "input = getUserInput()" only once and if the while condition is false (i.e. if the user input is valid), there will be no loop that keeps asking for valid input.


Really simple use of do while do{ cout<<"num :"; cin>>x; }while(x<1); It'll keep asking until the user give positive non zero input


Hlo Zahraddeen Mahmud..if u have studied loops then i'll must say u should also know about what r foreach i have derived foreach loop in c++ using #define preprocessor directive


you could use a do while loop to get password input example in java: String password = "12345678"; do { String input; Scanner sc = new Scanner(; input = sc.nextLine(); sc.close(); } while (input != password); System.out.print("Access granted"); of course you shouldn't use this VERY VERY UNSAFE implementation, but this would be a possibility also never store passwords in plain text