While and Do while conversation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

While and Do while conversation

How can I convert While to Do while and vice versa ?

7th Mar 2018, 8:19 PM
thbty
3 Answers
+ 8
@thbty, conversion between the two loops is possible, however, you need to understand the difference, as @Ace and @Lewis said, a do..while loop executes the instructions in its loop body before checking the loop condition. Contrary, a while loop checks the loop condition prior to executing instructions in its loop body, so you need to assess which of those loops best fits the requirement. Syntactically; do { // loop body } while(condition); Loop body is executed once, then condition is evaluated, the loop continues if condition evaluates to true. Note, mind the semicolon after (condition). ============================== while(condition) { // loop body } Condition is checked first, loop body is executed only IF condition evaluates to true. Hth, cmiiw
7th Mar 2018, 9:41 PM
Ipang
+ 2
Not sure how or why you'd need to do this since a do while loop is the same as a plain while loop other than the fact the body of the loop is executed at least once regardless of weather or not the condition checks out. So that being said I don't believe you can convert them, at least not both ways.
7th Mar 2018, 8:30 PM
Lewis
Lewis - avatar
+ 2
@Ace Yes you're right. That's why I said "at least not both ways" but I worded that incorrectly. I was trying to say that as long as you couldn't guarantee that the condition would cause at least one iteration in both cases then you wouldn't necessarily be able to safely swap them out because 'while' loops execute at minimum zero times whereas 'do while' executes at minimum one iteration regardless of the condition.
7th Mar 2018, 9:44 PM
Lewis
Lewis - avatar