+ 2

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

15th Dec 2018, 3:18 PM
Zahraddeen Mahmud
Zahraddeen Mahmud - avatar
5 Antworten
+ 2
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.
15th Dec 2018, 4:32 PM
Zeke Williams
Zeke Williams - avatar
+ 5
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.
15th Dec 2018, 4:34 PM
Anna
Anna - avatar
+ 2
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
15th Dec 2018, 3:26 PM
Taste
Taste - avatar
+ 2
Hlo Zahraddeen Mahmud..if u have studied loops then i'll must say u should also know about what r foreach loops..so i have derived foreach loop in c++ using #define preprocessor directive https://code.sololearn.com/cl5dRAoh6kaa/?ref=app
6th May 2019, 4:16 PM
Mohan
Mohan - avatar
0
you could use a do while loop to get password input example in java: String password = "12345678"; do { String input; Scanner sc = new Scanner(System.in); 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
16th Dec 2018, 3:29 PM
Azad Ad
Azad Ad - avatar