c++ primer 学习之路 (22)第5章 循环和关系表达式 for循环 计算阶乘 for循环访问字符串
5.1 for循环
C++中的for循环可以轻松地完成这种任务。
#include<iostream>
using namespace std;
int main()
{
int i;
for (i = 0; i < 5; i++)
cout << "C++ knows loops.\n";
cout << "c++ knpws when to stop." << endl;
system("pause");
return 0;
}
结果如下:
程序清单5.2通过将表达式i用作测试条件来演示了这一特点。更新部分的i−−与i++相似,只是每使用一次,i值就减1。
#include<iostream>
using namespace std;
int main()
{
cout << "Enter the starting countdown value: ";
int limit;
cin >> limit;
int i;
for (i = limit; i ; i--)
cout << "i = "<<i<< endl;
cout << "Done now that i = " << i<<endl;
system("pause");
return 0;
}
结果如下:
非0转换为true。
for循环是入口条件(entry-condition)循环。这意味着在每轮循环之前,都将计算测试表达式的值,当测试表达式为false时,将不会执行循环体。例如,假设重新运行程序清单5.2中的程序,但将起始值设置为0,则由于测试条件在首次被判定时便为false,循环体将不被执行
计算阶乘的程序:
#include<iostream>
using namespace std;
const int ArSize = 16;
int main()
{
long long factorials[ArSize];
factorials[1] = factorials[0] = 1LL;
for (int i = 2; i < ArSize; i++)
factorials[i] = i*factorials[i - 1];
for (int i = 0; i < ArSize; i++)
cout << i << "! = "<<factorials[i] << endl;
system("pause");
return 0;
}
结果如下:
程序清单5.6让用户能够输入一个字符串,然后按相反的方向逐个字符地显示该字符串
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Enter a word: ";
string word;
cin >> word;
for (int i = word.size() - 1; i >= 0; i--)
cout << word[i];
system("pause");
return 0;
}
结果如下:
程序清单5.11在for循环的测试条件中使用了strcmp( )。该程序显示一个单词,修改其首字母,然后再次显示这个单词,这样循环往复,直到strcmp( )确定该单词与字符串“mate”相同为止。注意,该程序清单包含了文件cstring,因为它提供了strcmp( )的函数原型。
#include<iostream>
#include<string>
using namespace std;
int main()
{
char word[5] = "?ate";
for (char ch = 'a'; strcmp(word, "mate"); ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends,word is " << word << endl;
system("pause");
return 0;
}