一、do while
1、表达式:
do
{循环语句}
while
{循环条件}
2、do while 与while的区别
do while 先执行循环语句,再执行循环条件。while先执行循环条件,再执行循环。
3、实例熟悉与对比
#include<iostream>
using namespace std;
int main()
{
int num = 0;
do
{
cout << num << endl;
num++;
} while (num );
system("pause");
return 0;
}
因为先执行循环语句,所以上面代码陷入死循环
#include<iostream>
using namespace std;
int main()
{
int num = 0;
while(num)
{
cout << num << endl;
num++;
}
system("pause");
return 0;
}
而同样的代码,while语句则不会输出 。
4、案例:水仙花数:三位数,每个位上的数字的三次幂之和等于这个数本身。利用do while 语句求出三位数中的水仙花数。
思路:找到所有三位数;在三位数中筛选出水仙花数:如何筛选,先得到个位、十位、百位,然后判断;输出。
#include<iostream>
using namespace std;
int main()
{
int num = 100;
int a, b, c;
do
{
a = num % 10;//得到三位数的个位
b = num / 10 % 10;//得到三位数的十位
c = num / 100;//得到三位数的百位
if (a* a* a + b * b * b + c * c * c == num)
{
cout << num << endl;
}
num++;
} while (num < 1000);
}
但是为什么num++写入if语句中为什么一直在编译,没有输出
二、for 循环语句
1、表达式:for(起始表达式;条件表达式;末尾循环体)
2、实例:
#include<iostream>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
}
3、敲桌子,1-100,个位数含7,十位数含7或数字是7的倍数,我们打印敲桌子,其它数字直接打印输出
#include<iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 100; i++)
{
if (i % 10 == 7 || i / 10 == 7 || i % 7 == 0)
{
cout << "敲桌子" << endl;
}
else
{
cout << i << endl;
}
}
}
思路:for循环输出所有数字,if语句筛选符合条件(共性)的数字。
三、嵌套循环
1、在屏幕中打印10*10矩阵星图
#include<iostream>
using namespace std;
int main()
{
for (int j = 0; j < 10; j++)
{
for (int i = 0; i < 10; i++)
{
cout << "* ";
}
cout << endl;
}
}
先进行一个循环,找方法,看效果,再在外面进行嵌套。外层执行一次,内层执行一周。
2、打印乘法口诀表
#include<iostream>
using namespace std;
int main()
{
for (int i = 1; i < 10; i++)//行数
{
for (int j = 1; j < 10; j++)//列数
{
if (j <= i)
{
cout << j << "*" << i << "=" << i * j<<"\t";
}
}
cout << endl;
}
}
思路:标序号观察共性。
四、跳转语句
1、break语句
在switch中,退出case分支。
在循环语句中,退出循环。
在嵌套循环语句中,写在内层,退出内层循环。
2、continue语句:在循环语句中,跳出一次循环,进入下一次循环。用于筛选输出。
注意break和continue的区别。:continue不会使循环终止,而break可以
3、goto标记:无条件跳转
#include<iostream>
using namespace std;
int main()
{
cout << "1xxxx" << endl;
cout << "2xxxx" << endl;
goto FLAG;
cout << "3xxxx" << endl;
FLAG:
cout << "4xxxx" << endl;
}
执行124,跳过3。缺点:随意跳转,不利于程序的可读性。