目录
1.1 while循环语句
1.2 do…while循环语句
1.3 for循环语句
1.4 嵌套循环
作用:满足循环条件后,执行循环语句。
语法:
while(循环条件)
{
循环语句
}
在循环条件结果为真的情况下,执行循环语句,否则跳出循环。
代码示例:
我们以打印0~9为例,进行打印这十个数字,我们可以使用“++”,重复进行代码的加一操作,不过这样的操作,代码重复太多,并且如果遇到较大数值的打印,很难办到。如下代码一。
代码一:
#include
using namespace std;
#include
int main()
{
//打印0~9这10个数字
int num = 0;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
num++;
cout << num << endl;
system("pause");
return 0;
}
运行结果:
为此我们可以采用while进行执行,如下代码二。
代码二:
#include
using namespace std;
#include
int main()
{
//打印0~9这10个数字
int num = 0;
while (num < 10)//条件语句尽量避免死循环,否则将一直打印无法跳出循环
{
cout << num << endl;
num++;
}
system("pause");
return 0;
}
while循环小游戏:while循环练习小游戏(猜数字)_时光の尘的博客-CSDN博客
作用:满足循环条件后,执行循环语句
语法:
do
{
循环语句
}while(循环条件)
其相较于while循环语句,do…while循环语句会先执行一次循环语句,在进行循环条件的判断。
代码示例:
#include
using namespace std;
#include
int main()
{
int num = 0;
do
{
cout << num << endl;
num++;
}
while (num < 10);
//可以将while()内的条件改为num,以此来验证do…while是否先执行一次循环语句
//由于num初始值为0,0又代表假
//若不进行循环语句,则是while(0);即跳出循环
//若进行魂环语句,则会是while(num),其中num不为0,即为真,则将一直循环,无法跳出
/*
int num = 0;
do
{
cout << num << endl;
num++;
}
while (num);
*/
system("pause");
return 0;
}
do…while循环练习:do…while循环语句练习(水仙花数)_时光の尘的博客-CSDN博客
作用:满足循环条件后,执行循环语句
语法:
for(起始表达式;条件表达式;末尾循环体)
{
循环语句
}
代码示例:
#include
using namespace std;
int main()
{
//从数字0打印到数字9
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
//for循环内的语句可以进行拆分如下
/*
int i=0;
for (; ; )
{
if(i>=10)
{
break;
}
cout << i << endl;
i++;
}
*/
system("pause");
return 0;
}
for循环语句练习:for循环练习(敲七游戏)_时光の尘的博客-CSDN博客
作用:在循环中,在嵌套一层循环,进行一些问题的解决,如下图
如果想要打印这张图片,笨拙的方法,代码过于重复,如下
代码示例:
#include
using namespace std;
int main()
{
//利用嵌套循环实现星图
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
system("pause");
return 0;
}
而使用嵌套循环能大大减少代码的重复,如下
代码示例:
#include
using namespace std;
int main()
{
//利用嵌套循环实现星图
//外层循环执行以此,内层循环执行一周
//外层
for (int a = 0; a < 10; a++)
{
//内层
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
}
system("pause");
return 0;
}
嵌套循环练习:C++嵌套循环练习(乘法口诀表)_时光の尘的博客-CSDN博客