一、for循环的概念
for循环是C++中最基本的循环控制语句之一,通过for循环可以方便的实现对数组、字符串、集合等一系列数据类型进行遍历。 for循环和while循环、do while循环一样,可以实现循环操作。它的语法格式如下:
for (循环变量初始值; 循环条件; 循环变量增量)
{
// 循环体语句
}
其中:
- 循环变量初始值:循环开始时,循环变量的初始值;
- 循环条件:循环执行的条件,如果循环条件成立,则执行循环体语句;
- 循环变量增量:每次执行完循环体语句之后,循环变量的修改方式;
- 循环体语句:循环执行的语句段。
二、for循环语句示例
1. for循环依次输出1~10之间的整数:
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
cout << i << " ";
}
return 0;
}
运行结果如下:
1 2 3 4 5 6 7 8 9 10
2. for循环实现数组遍历:
#include <iostream>
using namespace std;
int main()
{
int nums[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 5; i++)
{
cout << nums[i] << " ";
}
return 0;
}
运行结果如下:
1 2 3 4 5
3. for循环实现字符串遍历:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "hello world";
for (int i = 0; i < str.length(); i++)
{
cout << str[i] << " ";
}
return 0;
}
运行结果如下:
h e l l o w o r l d
三、for循环函数示例
1. for循环计算阶乘:
#include <iostream>
using namespace std;
int main()
{
int num, fac = 1;
cout << "请输入一个正整数:";
cin >> num;
for (int i = 1; i <= num; i++)
{
fac *= i;
}
cout << num << "的阶乘为:" << fac;
return 0;
}
运行结果如下:
请输入一个正整数:5
5的阶乘为:120
2. for循环求素数:
#include <iostream>
using namespace std;
int main()
{
int num, flag;
cout << "请输入一个正整数:";
cin >> num;
for (int i = 2; i <= num; i++)
{
flag = 1;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
flag = 0;
break;
}
}
if (flag)
{
cout << i << " ";
}
}
return 0;
}
运行结果(例如输入50):
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
3. 求斐波那契数列:
#include <iostream>
using namespace std;
int main()
{
int num;
int f0 = 0, f1 = 1, f;
cout << "请输入一个正整数:";
cin >> num;
cout << "斐波那契数列:";
for (int i = 0; i < num; i++)
{
if (i <= 1)
{
f = i;
}
else
{
f = f0 + f1;
f0 = f1;
f1 = f;
}
cout << f << " ";
}
return 0;
}
运行结果(例如输入10):
斐波那契数列:0 1 1 2 3 5 8 13 21 34
四、总结
通过本文,我们可以清楚的了解到for循环在C中的基本语法以及应用场景,包括遍历数组、字符串等数据类型,计算阶乘、求素数、求斐波那契数列等等。 for循环的语法比较简单,但掌握其应用场景和细节,能够提高代码效率,避免出现死循环等逻辑错误,是C程序员必须熟练掌握的基础知识之一。