4 程序流程结构
C/C++支持基本的三种流程结构:
(1)顺序结构:程序顺序执行,不发生跳转。
(2)选择结构:依据条件是否满足,有选择的执行相应功能。
(3)循环结构:依据条件是否满足,循环多次执行某段代码。
4.3 跳转语句
4.3.1 break语句
作用:用于跳出选择结构或者循环结构
break使用的时机:
(1)出现在switch条件语句中,作用是终止case并跳出switch
(2)出现在循环语句中,作用是跳出当前的循环语句
(3)出现在嵌套循环中,作用是跳出最近的内层循环语句
#include <iostream>
using namespace std;
int main()
{
//break使用时机
//1.出现在switch语句中:退出case分支,并跳出switch
cout << "请选择副本的难度" << endl;
cout << "1、普通难度" << endl;
cout << "2、中等难度" << endl;
cout << "3、困难难度" << endl;
int select = 0;
cin >> select;
switch (select)
{
case 1:
cout << "你选择的是普通难度" << endl;
break;
case 2:
cout << "你选择的是中等难度" << endl;
break;
case 3:
cout << "你选择的是困难难度" << endl;
break;
}
//2.出现在循环语句中:退出循环语句
int i = 0;
for (i; i < 10; i++)
{
if (i == 5)
{
break;//退出循环
}
cout << "i的值为:" << i << endl;
}
//3.出现在嵌套循环语句中:跳出最近的内层循环语句
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j > i)
{
break;
}
else
{
cout << "*" << " ";
}
}
cout << endl;
}
}
4.3.2 continue语句
作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环。
#include <iostream>
using namespace std;
int main()
{
//continue语句
for (int i = 0; i < 100; i++)
{
//如果是奇数输出.偶数不输出
if (i % 2 == 0)
{
continue;
}
else
{
cout << i << endl;
}
}
}
4.3.3 goto语句
作用:可以无条件跳转语句,尽量不要使用,避免程序的紊乱
语法:goto 标记;
解释:如果标记存在,执行到goto语句是,会跳转到标记的位置(标记:)。
#include <iostream>
using namespace std;
int main()
{
//goto语句
cout << "1.****" << endl;
cout << "2.****" << endl;
goto FLAG;
cout << "3.****" << endl;
cout << "4.****" << endl;
cout << "5.****" << endl;
FLAG:
cout << "6.****" << endl;
cout << "7.****" << endl;
}