5.1 for循环
程序清单5.1 forloop.cpp
// forloop.cpp -- introducing the for loop
#include<iostream>
int main()
{
using namespace std;
int i; // create a counter
for (i = 0; i < 5; i++)
cout << "C++ knows loops.\n";
cout << "C++ knows when to stop.\n";
return 0;
}
C++ knows loops.
C++ knows loops.
C++ knows loops.
C++ knows loops.
C++ knows loops.
C++ knows when to stop.
5.1.1 for循环的组成部分
1、设置初始值
2、执行测试,看看循环是否应当继续进行
3、执行循环操作
4、更新用于测试的值
程序清单5.2 num_test.cpp
// num_test.cpp --use numeric test in for loop
#include<iostream>
int main()
{
using namespace std;
cout << "Enter the starting coutdown calue: ";
int limit;
cin >> limit;
int i;
for (i = limit; i; i--) // quits when i is 0
cout << " i = " << i << endl;
cout << "Done now that i = " << i << endl;
return 0;
}
Enter the starting coutdown calue: 4
i = 4
i = 3
i = 2
i = 1
Done now that i = 0
1、表达式和语句
程序清单5.3 express.cpp
// express.cpp -- values of expressions
#include<iostream>
int main()
{
using namespace std;
int x;
cout << "The expression x = 100 has the value ";
cout << (x = 100) << endl;
cout << "Now x = " << x << endl;
cout << "The expression x < 3 has the value ";
cout << (x < 3) << endl;
cout << "The expression x > 3 has the value ";
cout << (x > 3) << endl;
cout.setf(ios_base::boolalpha);
cout << "The expression x < 3 has the value ";
cout << (x < 3) << endl;
cout << "The expression x > 3 has the value ";
cout << (x > 3) << endl;
return 0;
}
The expression x = 100 has the value 100
Now x = 100
The expression x < 3 has the value 0
The expression x > 3 has the value 1
The expression x < 3 has the value false
The expression x > 3 has the value true
5.1.2 回到for循环
程序清单5.4 formore.cpp
// formore.cpp
#include<iostream>
const int ArSize = 16; // example of external declaration
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++)
std::cout << i << ": = " << factorials[i] << std::endl;
return 0;
}
0: = 1
1: = 1
2: = 2
3: = 6
4: = 24
5: = 120
6: = 720
7: = 5040
8: = 40320
9: = 362880
10: = 3628800
11: = 39916800
12: = 479001600
13: = 6227020800
14: = 87178291200
15: = 1307674368000
5.1.3 修改步长
程序清单5.5 bigstep.cpp
// bigstep.cpp --cout as directed
#include<iostream>
int main()
{
using namespace std;
cout << "Enter an integer: ";
int by;
cin >> by;
cout << "Counting by " << by << "s:\n";
for (int i = 0; i < 100; i = i + by)
cout << i << endl;
return 0;
}
Enter an integer: 17
Counting by 17s:
0
17
34
51
68
85
5.1.4 使用for循环访问字符串
程序清单5.6 forstr1.cpp
// forstr1.cpp -- using for with a string
#include<iostream>
#include<string>
int main()
{
using namespace std;
cout << "Enter a word: ";
string word;
cin >> word;
// display letters in reverse order
for (int i = word.size() - 1; i>=0; i--)
cout << word[i];
cout << "\nBye.\n";
return 0;
}
Enter a word: animal
lamina
Bye.
5.1.5 递增运算符(++)和递减运算符(–)
程序清单5.7 plus_one.cpp
// plus_one.cpp -- the increment operator
#include<iostream>
int main()
{
using namespace std;
int a = 20;
int b = 20;
cout << "a = " << a << ": b = " << b << "\n";
cout <<"a++ = " << a++ << ": ++b = " << ++b << endl;
cout << "a = " << a << ": b = " << b << endl;
return 0;
}
a = 20: b = 20
a++ = 20: ++b = 21
a = 21: b = 21
5.1.6 副作用和顺序点
副作用(side effect):在计算表达式时对某些动议(如存储在变量中的值)进行了修改
顺序点(sequence point): 程序执行过程中的一个点
5.1.7 前缀格式和后缀格式
最终效果相同
5.1.8 递增/递减运算符和指针
double arr[5] = {11, 22, 33, 44, 55};
double *pt = arr; //pt points to arr[0], i.e. to 21.1
++pt; //pt points to arr[1], i.e. to 32.8
double x = *++pt; //increment pointer, take the value: i.e., arr[2], or 23.4
++*pt; //increment the pointed to value: i.e., change 22 to 23
x = *pt++; //dereference original location, then increment poiniter
5.1.9 组合赋值运算符
pa += 2; // ok, pa points to the former pa[2]
*(pa + 4) += 7; // ok, pa[4] set to pa[4] + 7
5.1.10 复合语句(语句块)
程序清单 5.8 block.cpp
// block.cpp -- use a block statement
#include<iostream>
int main()
{
using namespace std;
cout << "The Amazing Accounto will sum and average ";
cout << "five numbers for you.\n";
cout << "Please enter five values:\n";
double number;
double sum = 0.0;
for (int i =1; i <= 5; i++)
{
cout << "Value " << i << ": ";
cin >> number;
sum += number;
}
cout << "Five exquisite choice indeed: ";
cout << "They sum to " << sum << endl;
cout << "and average to " << sum / 5 << ".\n";
cout << "The Amazing Accounto bids you adieu:\n";
return 0;
}
The Amazing Accounto will sum and average five numbers for you.
Please enter five values:
Value 1: 1
Value 2: 2
Value 3: 3
Value 4: 4
Value 5: 5
Five exquisite choice indeed: They sum to 15
and average to 3.
The Amazing Accounto bids you adieu:
程序清单5.9 forstr2
// 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";
return 0;
}
Enter a word: bing
gnib
Done
5.1.13 赋值、比较和可能犯的错误
程序清单 5.10 equal.cpp
//equal.cpp --equality vs assignment
#include<iostream>
int main()
{
using namespace std;
int quizscores[10] =
{20, 20, 20, 20, 20, 20, 20, 19, 28, 20};
cout << "Doing it right:\n";
int i;
for (i=0; quizscores[i] == 20; i++)
cout << "quiz " << i << " is a 20\n";
return 0;
}
Doing it right:
quiz 0 is a 20
quiz 1 is a 20
quiz 2 is a 20
quiz 3 is a 20
quiz 4 is a 20
quiz 5 is a 20
quiz 6 is a 20
程序清单 5.11 compstr1.cpp
// compstr1.cpp --comparing strings using arrays
#include<iostream>
#include<cstring> // prototype for strcmp()
int main()
{
using namespace std;
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;
return 0;
}
?ate
aate
bate
cate
date
eate
fate
gate
hate
iate
jate
kate
late
After loop ends, word is mate
5.1.15 比较string类字符串
程序清单 5.12 compstr2.cpp
// compstr2.cpp --comparing strings using arrays
#include<iostream>
#include<string> // string class
int main()
{
using namespace std;
string word = "?ate";
for (char ch = 'a'; word != "mate"; ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends, word is " << word << endl;
return 0;
}
?ate
aate
bate
cate
date
eate
fate
gate
hate
iate
jate
kate
late
After loop ends, word is mate
5.2 while循环
程序清单 5.13 while.cpp
// 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
}
return 0;
}
Your first name, please: bing
Here is your name, verticalized and ASCIIized:
b: 98
i: 105
n: 110
g: 103
5.3 do while循环
程序清单 5.15 dowhile.cpp
// dowhile.cpp -- exit-condition loop
#include<iostream>
int main()
{
using namespace std;
int n;
cout << "Enter numbers in the range 1-10 to find ";
cout << "my favorite number\n";
do
{
cin >> n; // executre body
} while (n!=7); // then test
cout << "Yes, 7 is my favorite.\n";
return 0;
}
Enter numbers in the range 1-10 to find my favorite number
1
2
3
4
5
6
7
Yes, 7 is my favorite.
5.5 循环和文本输入
cin将忽略空格和换行符
程序清单5.16 textin1.cpp
// textin1.cpp --reading chars with a while loop
#include<iostream>
int main()
{
using namespace std;
char ch;
int count = 0; // use basic input
cout << "Enter characters; enter # to quit:\n";
cin >> ch;
while (ch!='#') // test the character
{
cout << ch; // echo the character
++count; // count the chracter
cin >> ch; // get the next character
}
cout << endl << count << " characters read\n";
return 0;
}
Enter characters; enter # to quit:
bing want # to go
bingwant
8 characters read
cin.get(char)会检查每个字符,包括空格、制表符和换行符
程序清单 5.17 textin2.cpp
// textin2.cpp -- using cin.get(char)
#include<iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters: enter # to quit:\n";
cin.get(ch);
while(ch != '#')
{
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " character read\n";
return 0;
}
Enter characters: enter # to quit:
bing want #to go
bing want
10 character read
5.5.4 文件尾条件
程序清单 5.18 textin3.cpp
// textin3.cpp --reading chars to end of file
#include<iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cin.get(ch); // attempt to read a char
while (cin.fail() == false) // test for EOF
{
cout << ch; // echo character
++count;
cin.get(ch); // attempt to read another char
}
cout << endl << count << " characters read\n";
return 0;
}
bing want to go
bing want to go
^Z
16 characters read
5.5.5 另一个cin.get()版本
//textin4.cpp --reading chars with cin..get()
#include<iostream>
int main()
{
using namespace std;
int ch;
int count = 0;
while ((ch = cin.get()) != EOF) // test for end-of-file
{
cout.put(char(ch));
++count;
}
cout << endl << count << " character read\n";
return 0;
}
bing want to go
bing want to go
^Z
16 character read
5.6 嵌套循环和二维数组
// nested.cpp -- nested loops and 2-D array
#include<iostream>
const int Cities = 5;
const int Years = 4;
int main()
{
using namespace std;
const char * cities[Cities] = // array of pointers
{
"Beijing",
"Chengdu",
"Shanghai",
"ShenZhen",
"GuangZhou"
} ;
int maxtemps[Years][Cities] = //2-D array
{
{96, 100, 87, 101, 105},
{96, 98, 91, 107, 104},
{97, 101, 93, 108, 107},
{98, 103, 95, 107, 107}
};
cout << "Maximum temperatures for 2008 - 2011\n\n";
for (int city = 0; city < Cities; ++city)
{
cout << cities[city] << ":\t";
for (int year = 0; year < Years; ++year)
cout << maxtemps[year][city] << "\t";
cout << endl;
}
return 0;
}
Maximum temperatures for 2008 - 2011
Beijing: 96 96 97 98
Chengdu: 100 98 101 103
Shanghai: 87 91 93 95
ShenZhen: 101 107 108 107
GuangZhou: 105 104 107 107