循环语句

第5章 循环和关系表达式:程序经常需要执行重复性操作,为此 C++提供了3种循环结构:for循环、while循环和do while循环。这些循环必须知道何时终止,C++的关系运算符使程序员能够创建测试 来引导循环。本章还将介绍如何创建逐字符地读取和处理输入的循 环。最后,您将学习如何创建二维数组以及如何使用嵌套循环来处 理它们。

5.1 for循环

Basic Demo

没有大括号,默认后边的一行

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

有大括号

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

Demo

// 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";
    // cin.get();
    return 0;
}
Update counter
  • 可以++,--,注意理论上++i 比 i++速度快

  • 可以倒序

for (int i = word.size() - 1; i >= 0; i--)
        cout << word[i];
  • 可以递增递减指针

int main()
{
    using namespace std;
    
    double arr[5] = {2,4,6,8,10};
    double *p = arr;
    cout << *p++ << *p++ << *p++; // 2 4 6
    double * = arr;
    cout << *++q << *++q << *++q; // 4 6 8
    return 0;
}
// 指针递增,然后取值
*++p;
// 取值然后指针递增
*p++;
// 指针指得地方++
++*p;
// 指针指得地方++
(*p)++;
more expression in one block

逗号运算符

// forstr2.cpp -- reversing an array
#include <iostream>
#include <string>
int main()
{
    using namespace std;
    cout << "Enter a word: ";
    string word;
    cin >> word;

    // physically modify string object
    char temp;
    int i, j;
    for (j = 0, i = word.size() - 1; j < i; --i, ++j)
    {                       // start block
        temp = word[i];
        word[i] = word[j];
        word[j] = temp;
    }                       // end block
    cout << word << "\nDone\n";
    // cin.get();
    // cin.get();
    return 0; 
}

5.2 while 循环

Basic Demo
while (test-condition)
    body
    
while (test-condition) {
    body
}
// while.cpp -- introducing the while loop
#include <iostream>
const int ArSize = 20;
int main()
{
    using namespace std;
    char name[ArSize];

    cout << "Your first name, please: ";
    cin >> name;
    cout << "Here is your name, verticalized and ASCIIized:\n";
    int i = 0;                  // start at beginning of string
    while (name[i] != '\0')     // process to end of string
    {
        cout << name[i] << ": " << int(name[i]) << endl;
        i++;                    // don't forget this step
    }
    // cin.get();
    // cin.get();
    return 0; 
}
waiting Demo (with ctime)
// waiting.cpp -- using clock() in a time-delay loop
#include <iostream>
#include <ctime> // describes clock() function, clock_t type
int main()
{
    using namespace std;
    cout << "Enter the delay time, in seconds: ";
    float secs;
    cin >> secs;
    clock_t delay = secs * ;  // convert to clock ticks
    cout << "starting\a\n";
    clock_t start = clock();
    while (clock() - start < delay )        // wait until time elapses
        ;                                   // note the semicolon
    cout << "done \a\n";
    // cin.get();
    // cin.get();
    return 0; 
}
(base) kimshan@MacBook-Pro output % ./"waiting"
Enter the delay time, in seconds: 10
starting
done 

5.3 do while 循环

Basic Demo
do {
    body
} while (test-condition);

5.4 基于范围的 for 循环

C++11新特性

Basic Demo

遍历数字所有元素,就算没有初始化那也遍历

#include <iostream>
#include <ctime>

int main()
{
    using namespace std;

    int array1[] = {100, 200, 300};
    for (int x : array1)
        cout << x << " \n";

    int array2[4] = {140, 250, 360};
    for (int x : array2)
        cout << x << " \n";

    return 0;
}
(base) kimshan@MacBook-Pro output % ./"test1"
100 
200 
300 
140 
250 
360 
0 

5.5 循环和文本输入

最终完善的代码(利用 EOF)

Mac的 EOF 是 command+D

Windows 的 EOF是 control+Z+enter

// textin4.cpp -- reading chars with cin.get()
#include <iostream>
int main(void)
{
    using namespace std;
    int ch;                         // should be int, not char
    int count = 0;

    while ((ch = cin.get()) != EOF) // test for end-of-file
    {
        cout.put(char(ch));
        ++count;
    }
    cout << endl << count << " characters read\n";
	return 0; 
}
(base) kimshan@MacBook-Pro output % ./"textin4"
Hello World
Hello World
A B CCC ddddd ###jhrfijiwj
A B CCC ddddd ###jhrfijiwj
^D
39 characters read

最后更新于

这有帮助吗?