What does the following for loop do? What is the final value of sum?
下列循环做什么?sum 的最终值是多少?
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
求-100到100的和 0
Exercise 1.10:
Write a program that uses a for loop to sum the numbers from 50 to 100. Now rewrite the program using a while.
用 for 循环编程,求从 50 到 100 的所有自然数的和。然后用 while 循环重写该程序。
Exercise 1.11:
Write a program using a while loop to print the numbers from 10 down to 0. Now rewrite the program using a for.
用 while 循环编程,输出 10 到 0 递减的自然数。然后用 for 循环重写该程序。
#include "iostream"
int main() { int sum=0,sal; for (sal = 10; sal >= 0; --sal) { sum += sal; } std::cout <<"10到0的和为" << sum << std::endl; return 0; }
//
#include "stdafx.h" #include "iostream"
int main() { int sum=0,sal=10; while(sal>=0)
{
sum=+sal;
--sal;
} std::cout <<"10到0的和为" << sum << std::endl; return 0; }
Exercise 1.12:
Compare and contrast the loops you wrote in the previous two exercises. Are there advantages or disadvantages to using either form?
对比前面两个习题中所写的循环。两种形式各有何优缺点?
* 一个需求:使用for循环和while循环都可以去实现,那么到底两者之间有什么区别? * 从内存角度考虑: * 局部变量在栈内存中存在,当for循环语句结束,那么变量会及时被gc(垃圾回收器)及时的释放掉,不浪费空间 * 如果使用循环之后还想去访问循环语句中控制那个变量,使用while循环 * 从应用场景角度考虑: * 如果一个需求明确循环的次数,那么使用for循环(开发中使用for循环的几率大于while循环) * 如果一个需求,不知道循环了多少次,使用while循环 * 举例:吃葡萄! * * * */ public class WhileDemo4 { public static void main(String[] args) { //使用for循环 for(int x = 1 ; x <=5 ; x++){ System.out.println("我爱高圆圆"); }
//访问for循环中控制的那个变量x // System.out.println(x);
//使用while循环 int x = 1 ; while(x<=5){ System.out.println("我爱高圆圆"); x ++ ; }
//可以访问变量 System.out.println(x);
} }
Exercise 1.13:
Compilers vary as to how easy it is to understand their diagnostics. Write programs that contain the common errors discussed in the box on 16. Study the messages the compiler generates so that these messages will be familiar when you encounter them while compiling more complex programs.