《C++PrimerPlus》第5章 循环和关系表达式

5.1 for循环

递增/递减运算符和指针

#include <iostream>

int main(){
    using namespace std;

    double arr[5] = { 21.1,32.8,23.4,45.2,37.4 };
    double *pt = arr;

    //打印数组的第一个元素
    cout << "*pt = " << *pt << endl; 
    //从右到左运算,指针跨过一个元素再取值,此时pt指向arr[1]
    cout << "*++pt = " << *++pt << endl; 
    //取值之后再加1,先++在cout,此时arr[1]=33.8
    cout << "++*pt = " << ++*pt << endl; 
    //取值之后再加1,先cout再++,显示33.8,而此时arr[1]=34.8
    cout << "(*pt)++ = " << (*pt)++ << endl; 
    //此时arr[1]=34.8
    cout << "*pt = " << *pt << endl;
    //++后缀优先级比*高
    //指针后移再加1,但是先cout再++,显示34.8,此时指针指向arr[2]
    cout << "*pt++ = " << *pt++ << endl;
    //此时指针指向arr[2]
    cout << "*pt = " << *pt << endl;

    return 0;
}

5.2 While循环

5.3 do while循环

使用do while

#include <iostream>

int main(){
    using namespace std;

    cout << "Guess my love numbers in the range 1~10: ";
    int n;
    do{
        cin >> n;
    } 
    while (n != 7);

    cout << "Yes, 7 is my favorite." << endl;
    return 0;
}

5.4 基于范围的for循环(C++11)

5.5 循环和文本输入

使用cin.get()的循环文本输入

#include <iostream>

int main(){
    using namespace std;
    char ch;
    int count = 0;

    cout << "Enter characters, enter # to quit: " << endl;
    cin.get(ch);

    while (cin.fail() == false){
        cout << ch;
        ++count;
        cin.get(ch);
    }

    cout << endl;
    cout << count << " characters read" << endl;
    return 0;
}

5.6 嵌套循环和二维数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值