练习1.12:下面for循环完成了什么功能?sum的终值是多少?
int sum = 0;
for(int i = -100 ; i <= 100 ; ++i)
sum += i;
循环完成的功能是从-100到100整数相加的和,sum的终值是0
练习1.13:使用for循环重做1.4.1节中的所有练习(第11页)
1.4.1节中的所有练习:
练习1.9:编写程序,使用while循环将50到100的整数相加。
我们用for。
#include<iostream>
using namespace std;
int main()
{
int sum = 0;
for (int i = 50; i <= 100; ++i)
sum += i;
cout << sum << endl;
}
练习1.10:除了++运算符将运算对象的值增加1之外,还有一个递减运算符(-)实现将值减少1。编写程序,使用递减运算符在循环中按递减顺序打印出10到0之间的整数。
#include<iostream>
using namespace std;
int main()
{
for (int i = 10; i >= 1; --i)
cout << i << endl;
}
练习1.11 编写程序,提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数。
#include<iostream>
using namespace std;
int main()
{
cout << "请输入两个整数:";
int a, b;
cin >> a >> b;
if (a > b)
{
for (; b <= a; b++)
{
cout << b<<endl;
}
return 0;
}
if (b > a)
{
for (; a <= b; a++)
{
cout << a<<endl;
}
return 0;
}
}
练习1.14 对比for循环和while循环,两种形式的优缺点各是什么?
参考pezy:
- Advantage of
for
and disadvantage ofwhile
:- Locality, the variable in the scope of the loop.
- Pattern happens so often: using a variable in a condition and incrementing that variable in the body.
- Advantage of
while
and disadvantage offor
:- Clear when there is only one static condition.
- Readable when the global variables incremented in the body.
简单来说,for的优点是:变量能在范围内循环。循环模式经常能够刷新,一个变量一个循环条件。
while的优点是:当只有一个静态条件时,这个条件比较清晰。当全局变量在递增时,可读性比较强。