上面我们看来函数的一些简单东西,数据类型,函数,以及函数的一些使用方法,这次我们来学习一下c++语法:for循环,do...while,while循环三个c++主要循环算法;
(不包含递归思想,会在之后的小文中学习中讲解)
语法:for循环 for(初始条件;循环终止条件;循环条件){循环体}
下面我们以一个例子来说明:打印n以下的数字
#include<iostream>
using namespace std;
void ShowFor(int n) {
for (int i = 0; i < n; i++) {
cout << "从0到n的循环的结果为: " << i <<endl;
}
cout << endl;
}
void TestFor() {
int menber;
cout << "请输入要打印的值:" << endl;
cin >> menber;
ShowFor(menber);
}
int main() {
TestFor();
return 0;
}
结果如图:
![](https://img-blog.csdnimg.cn/img_convert/7110c75aaa8638e8c47c33711792bf10.png)
这个就是for循环的基本用法,你可以用来遍历一些变量,学号for循环是非常重要的,这里的menber数据类型可以为longlong,当然一般配合顺序结构和选择结构能事半功倍。
案例:
我们接下来做一个能否被整除的案例:100以内的数,我们遍历
#include<iostream>
using namespace std;
void ForFunc() {
for (int i = 0; i < 101; i++) {
cout << i << " ";
}
cout << endl;
}
int main() {
ForFunc();
return 0;
}
![](https://img-blog.csdnimg.cn/img_convert/b9a30a9f07ab971d0f3ab0bf6064d74a.png)
感觉很乱,我们做一个排序换行的操作,每10个换行展示,再把0前置去掉,我们从1开始计数
#include<iostream>
using namespace std;
void ForFunc() {
for (int i = 1; i < 101; i++) {
cout << i << " ";
if (i % 10 == 0) {
cout << endl;
}
}
cout << endl;
}
int main() {
ForFunc();
return 0;
}
![](https://img-blog.csdnimg.cn/img_convert/f493f6f39b8f2c852090b90429db45a7.png)
学会排兵布阵,对后面杨辉三角比较友好,以及打印一些图形
在此基础上,我们筛选一下,能被2整除的数,如果能被2整除我们进行输出,因此,我们要修改的是第一个for循环里的输出条件
#include<iostream>
using namespace std;
void ForFunc() {
for (int i = 1; i < 101; i++) {
/* cout << i << " ";*/
if (i % 2 == 0) {
cout << i << " ";
}
if (i % 10 == 0) {
cout << endl;
}
}
cout << endl;
}
int main() {
ForFunc();
return 0;
}
![](https://img-blog.csdnimg.cn/img_convert/97e4345e57ed56839a9bc10bcf043be2.png)
我们已经进行输出了,但是还不够,我们再筛选一下能否被5整除的,这里需要用到c++运算符:&&且运算,请看代码:
#include<iostream>
using namespace std;
void ForFunc() {
for (int i = 1; i < 101; i++) {
/* cout << i << " ";*/
if (i % 2 == 0&&i%5==0) {
cout << i << " ";
}
if (i % 10 == 0) {
cout << endl;
}
}
cout << endl;
}
int main() {
ForFunc();
return 0;
}
![](https://img-blog.csdnimg.cn/img_convert/8cc7092ffc920d7904cb71c6428505b1.png)
这就简单完成一个筛选,但是这种筛选一般不太适用,因为这是随心的,考试也不会看这些,后面会设计到类和对象,STL容器,我们之后再说。For是最主要的循环语句,学好for循环很有必要。当然你可大胆去尝试一些东西,莫非就是报错而已,注意初始条件。
While语法
同样的案例,我们做简单的实现
#include<iostream>
using namespace std;
//这里的是稍微修改
//while的语法 while(判断条件是否继续){函数体}
void ShowWhile(int n) {
int i = 0;
while (i < n) {
cout << "从0到n的循环的结果为: " << i << endl;
i++;
}
}
void TestWhile() {
int menber;
cout << "请输入要打印的值:" << endl;
cin >> menber;
ShowWhile(menber);
}
int main() {
TestWhile();
return 0;
}
这里我们同样的道理
![](https://img-blog.csdnimg.cn/img_convert/42f6820270f2bad52d7cfa3c5d4cf6d2.png)
do...while先做了i++才开始执行循环。
文章比较入门,有错乱的地方请大家批评指针,下一章是c++数组
包括字符数组和数字数组,加指针