The do-while loop

None of the cool kids use the do-while loop, but for completeness, here it is. The do-while loop doesn’t check the expression until it has executed the block. Thus, it ensures that the block is always executed at least once. If you rewrote the original exercise to use a do-while loop, it would look like this:

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​i​n​t​ ​i​ ​=​ ​0​;​
 ​ ​ ​ ​d​o​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​p​r​i​n​t​f​(​"​%​d​.​ ​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​i​+​+​;​
 ​ ​ ​ ​}​ ​w​h​i​l​e​ ​(​i​ ​<​ ​1​3​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Notice the trailing semicolon. That’s because unlike the other loops, a do-while loop is actually one long statement:

d​o​ ​{​ ​s​o​m​e​t​h​i​n​g​ ​}​ ​w​h​i​l​e​ ​(​ ​s​o​m​e​t​h​i​n​g​ ​e​l​s​e​ ​s​t​a​y​s​ ​t​r​u​e​ ​)​;​

Here’s a flow-chart of this do-while loop:

Figure 7.5  do-while loop

do-while loop
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset