设为首页 加入收藏

TOP

1.4 Flow of Control (1)
2013-10-07 16:14:47 来源: 作者: 【 】 浏览:58
Tags:1.4 Flow Control

Statements normally execute sequentially: The first statement in a block is executed first, followed by the second, and so on. Of course, few programs—including the one to solve our bookstore problem—can be written using only sequential execution. Instead, programming languages provide various flow-of-control statements that allow for more complicated execution paths.

1.4.1 The while Statement

A while statement repeatedly executes a section of code so long as a given condition is true. We can use a while to write a program to sum the numbers from 1 through 10 inclusive as follows:

  1. #include <iostream>   
  2. int main()   
  3. {   
  4. int sum = 0, val = 1;   
  5. // keep executing the while as long as val is less than or equal to 10   
  6. while (val <= 10) {   
  7. sum += val; // assigns sum + val to sum   
  8. ++val; // add 1 to val   
  9. }  
  10. std::cout << "Sum of 1 to 10 inclusive is "   
  11. << sum << std::endl;   
  12. return 0;   
  13. }  

When we compile and execute this program, it prints

  1. Sum of 1 to 10 inclusive is 55  

As before, we start by including the iostream header and defining main. Inside main we define two int variables: sum, which will hold our summation, and val, which will represent each of the values from 1 through 10. We give sum an initial value of 0 and start val off with the value 1.


The new part of this program is the while statement. A while has the form

  1. while (condition)   
  2. statement  

A while executes by (alternately) testing the condition and executing the associated statement until the condition is false. A condition is an expression that yields a result that is either true or false. So long as condition is true, statement is executed. After executing statement, condition is tested again. If condition is again true, then statement is again executed. The while continues, alternately testing the condition and executing statement until the condition is false.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.2 A First Look at Input/Outpu.. 下一篇1.4 Flow of Control (7)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·数据库:推荐几款 Re (2025-12-25 12:17:11)
·如何最简单、通俗地 (2025-12-25 12:17:09)
·什么是Redis?为什么 (2025-12-25 12:17:06)
·对于一个想入坑Linux (2025-12-25 11:49:07)
·Linux 怎么读? (2025-12-25 11:49:04)