break

Sometimes it is necessary to stop the loop’s execution from inside the loop. For example, let’s say you want to step through the positive integers looking for the number x, where x + 90 = x2. Your plan is to step through the integers 0 through 11 and pop out of the loop when you find the solution. Change the code:

#​i​n​c​l​u​d​e​ ​<​s​t​d​i​o​.​h​>​

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​;​
 ​ ​ ​ ​f​o​r​ ​(​i​ ​=​ ​0​;​ ​i​ ​<​ ​1​2​;​ ​i​+​+​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​p​r​i​n​t​f​(​"​C​h​e​c​k​i​n​g​ ​i​ ​=​ ​%​d​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​i​f​ ​(​i​ ​+​ ​9​0​ ​=​=​ ​i​ ​*​ ​i​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​b​r​e​a​k​;​
 ​ ​ ​ ​ ​ ​ ​ ​}​
 ​ ​ ​ ​}​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​T​h​e​ ​a​n​s​w​e​r​ ​i​s​ ​%​d​.​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build and run the program. You should see

C​h​e​c​k​i​n​g​ ​i​ ​=​ ​0​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​1​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​2​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​3​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​4​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​5​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​6​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​7​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​8​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​9​
C​h​e​c​k​i​n​g​ ​i​ ​=​ ​1​0​
T​h​e​ ​a​n​s​w​e​r​ ​i​s​ ​1​0​.​

Notice that when break is called, execution skips directly to the end of the code block.

break
..................Content has been hidden....................

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