4 程序流程结构
C/C++支持基本的三种流程结构:
(1)顺序结构:程序顺序执行,不发生跳转。
(2)选择结构:依据条件是否满足,有选择的执行相应功能。
(3)循环结构:依据条件是否满足,循环多次执行某段代码。
4.2 循环结构
4.2.1 while循环语句
作用:满足循环条件,执行循环语句
语法:while(循环条件){循环语句}
解释:只要循环条件为真,就执行循环语句
#include <iostream>
using namespace std;
int main()
{
//while循环
//打印0~9
int num = 0;
while (num<10)
{
cout << num++ << endl;
}
return 0;
}
循环案例:
#include <iostream>
using namespace std;
int main()
{
//1.系统生成随机数
int num1 = rand() % 100;//生成0~99随机数
//2.玩家进行猜测
int val = 0;
//cout << "玩家猜测的数:" << endl;
//cin >> val;
//3.判断玩家猜测
//猜对:退出游戏
//猜错:提示猜的结果过大或者过小,重新返回第2步
while (1)
{
cout << "请输入你要猜测的数:" << endl;
cin >> val;
if (val > num1)
{
cout << "猜的数过大" << endl;
}
else if (val < num1)
{
cout << "猜的数过小" << endl;
}
else
{
cout << "恭喜你猜对了" << endl;
break;//退出循环
}
}
return 0;
}
4.2.2 do-while循环语句
作用:满足循环条件,执行循环语句
语法:do{循环语句} while(循环条件);
注意:与while的区别在于do…while会先执行一次循环语句,再判断循环条件。
#include <iostream>
using namespace std;
int main()
{
//do-while循环
//输出0~9数字
int num = 0;
do
{
cout << num++ << endl;
} while (num < 10);
return 0;
}
while和do-while的区别是,do-while会先执行一次语句再进行判断,while是先进行判断,再是否执行语句。
循环案例:
#include <iostream>
using namespace std;
int main()
{
//水仙花数
//水仙花数是指一个3为位数,它的每个位上的数字的3次幂之和等于它本身
int num = 100;
while (num <= 999)
{
//获取个位数
int a = num % 10;
//获取十位数
int b = (num/10)%10;
//获取百位数
int c = num / 100;
if ((a*a*a + b*b *b+ c*c *c)==num)
{
cout << "水仙花数为:" << num<<endl;
}
num++;
}
}
4.2.3 for循环语句
作用:满足循环条件,执行循环语句
语法:for(起始表达式;条件表达式;末尾循环体){循环语句}
#include <iostream>
using namespace std;
int main()
{
//for循环
//打印0~9
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
return 0;
}
循环案例:
#include <iostream>
using namespace std;
int main()
{
//for循环:案例
//案例描述:从1开始数到100,如果数字个位含有7,或者数字十位
//含有7,或者该数字是7的倍数,我们打印敲桌子。
for (int i = 0; i < 100; i++)
{
//个位
int a = i % 10;
//十位
int b = i / 10;
if (a == 7 || b == 7 || i % 7 == 0)
{
cout << "敲桌子" <<i<< endl;
}
else
{
cout << i << endl;
}
}
return 0;
}
4.2.4 嵌套循环
作用:在循环体中再嵌套一层循环,解决一些实际问题
#include <iostream>
using namespace std;
int main()
{
//嵌套循环
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
cout << "using*";
}
cout << endl;
}
return 0;
}
循环案例:
#include <iostream>
using namespace std;
int main()
{
//九九乘法表
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
if (j <= i)
{
cout << j << "*" << i << "=" << (i ) * (j) <<" ";
}
}
cout << endl;
}
}