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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值