循环控制分成两种,一种是中断循环break,一种是进入下一次循环continue
一、break
break语法:
![](https://img-blog.csdnimg.cn/img_convert/d055165d49cea57a2b3be44d28f30447.png)
1、代码实现:循环数1-20的偶数,在输出第一个偶数时退出循环。
Java写法:
![](https://img-blog.csdnimg.cn/img_convert/31ead7bbe8618e2c8f1737e632bc3de2.png)
![](https://img-blog.csdnimg.cn/img_convert/dc8bcf54efebb109cfa308e7410de37c.png)
Python写法:
![](https://img-blog.csdnimg.cn/img_convert/a74909c7cdd1052e9122eb36dba8fde8.png)
2、使用break跳出外层循环
break语句只会使程序跳出当前包含他的循环,当存在循环嵌套的情况下,除了当前包含他的循环,其他循环继续执行。
![](https://img-blog.csdnimg.cn/img_convert/4857fa796d01895b6024dffe068f044e.png)
以上图为例,先是i=1,j依次输出1、2、3然后中断当前j的循环,但是外层i的循环并未中断,所以继续i=2,j依次输出1、2、3。修改上图代码如下:
![](https://img-blog.csdnimg.cn/img_convert/6150f2be90417f6b70f54332e8426541.png)
由控制台输出结果可知,当j==4时,外层i的循环已中断。9
二、continue
continue语法:
![](https://img-blog.csdnimg.cn/img_convert/66a542038ca517e6cf4658300d56dd00.png)
1、代码实现:输出1-1000的奇数
不使用continue:
![](https://img-blog.csdnimg.cn/img_convert/72af8ae2a48d0cd8ef68038a1191c62d.png)
使用continue:
![](https://img-blog.csdnimg.cn/img_convert/c3fab6aaeb4ceed396236d25d2fd2c9e.png)