C++ Primer Plus学习随记(五)

5.1 for循环

// forloop.cpp -- introducing the for loop
#include <iostream>
int main()
{
    using namespace std;
    int i; // create a counter
//   initialize; test ; update
    for (i = 0; i < 5; i++)
        cout << "C++ knows loops.\n";
    cout << "C++ knows when to stop.\n";
    return 0;
}

5.1.1 for循环的组成部分

1.设置初始值。

2.执行测试,看看循环是否应当继续进行。

3.执行循环操作。

4.更新用于测试的值。

for (initialization; test-expression; update-expression)
 body

C++循环允许:

for (for-init-statement condition; expression)
 statement

5.1.9 组合赋值运算符

5.1.12 关系表达式

5.2 while循环

while (test-condition)
 body

5.2.1 for与while

for (init-expression; test-expression; update-expression)
{
    statement(s)
}
init-expression;
while (test-expression)
{
    statement(s)
    update-expression;
}
while (test-expression)
 body
for ( ;test-expression;)
 body
for ( ; ; )
    body

在设计循环时,请记住下面几条指导原则。

  • 指定循环终止的条件。
  • 在首次测试之前初始化条件。
  • 在条件被再次测试之前更新条件。

5.3 do while循环

do
    body
while (test-expression);

首先执行循环体,然后再判定测试表达式,决定是否应继续执行循环。false,循环终止;true,进入新一轮的执行和测试。

5.4 基于范围的for循环

double prices[5] = {4.99, 10.99, 6.87, 7.99, 8.49};
for (double x : prices)
    cout << x << std::endl;

5.5.5  另一个cin.get()版本

5.6 嵌套循环和二维数组

int maxtemps[4][5];

maxtemps包含4个元素的数组,其中每个元素都是一个由5个整数组成的数组。

for (int row = 0; row < 4; row++)
{
      for (int col = 0; col < 5; ++col)
           cout << maxtemps[row][col] << "\t";
      cout << endl;
}

5.6.1 初始化二维数组

int maxtemps[4][5] = // 2-D array
{
    {96, 100, 87, 101, 105}, // values for maxtemps[0]
    {96, 98, 91, 107, 104},  // values for maxtemps[1]
    {97, 101, 93, 108, 107}, // values for maxtemps[2]
    {98, 103, 95, 109, 108}  // values for maxtemps[3]
};

5.6.2 使用二维数组

const string cities[Cities] = // array of 5 strings
{
    "Gribble City",
    "Gribbletown",
    "New Gribble",
    "San Gribble",
    "Gribble Vista"
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值