While and Do while conversation | Sololearn: Learn to code for FREE!

0

While and Do while conversation

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

3/7/2018 8:19:21 PM

thbty

4 Answers

New Answer

+9

@Lewis that is not entirely correct. If you can guarantee that the loop will execute at least once, you can easily convert a while to do-while. While loops can run 0 times, do-while runs at least once.

+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

+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.

+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.