设为首页 加入收藏

TOP

1.4 Flow of Control (2)
2013-10-07 16:15:05 来源: 作者: 【 】 浏览:96
Tags:1.4 Flow Control

In this program, the while statement is

  1. // keep executing the while as long as val is less than or equal to 10   
  2. while (val <= 10) {   
  3. sum += val; // assigns sum + val to sum   
  4. ++val; // add 1 to val   
  5. }  

The condition uses the less-than-or-equal operator (the <= operator) to compare the current value of val and 10. As long as val is less than or equal to 10, the condition is true. If the condition is true, we execute the body of the while. In this case, that body is a block with two statements:

  1. {   
  2. sum += val; // assigns sum + val to sum   
  3. ++val; // add 1 to val   
  4. }  

A block is a sequence of zero or more statements enclosed by curly braces. A block is a statement and may be used wherever a statement is required. The first statement in this block uses the compound assignment operator (the += operator). This operator adds its right-hand operand to its left-hand operand and stores the result in the left-hand operand. It has essentially the same effect as writing an addition and an assignment:

  1. sum = sum + val; // assign sum + val to sum  

Thus, the first statement in the block adds the value of val to the current value of sum and stores the result back into sum.

The next statement

  1. ++val; // add 1 to val  

uses the prefix increment operator (the ++ operator). The increment operator adds 1 to its operand. Writing ++val is the same as writing val = val + 1.

After executing the while body, the loop eva luates the condition again. If the (now incremented) value of val is still less than or equal to 10, then the body of the while is executed again. The loop continues, testing the condition and executing the body, until val is no longer less than or equal to 10.

Once val is greater than 10, the programfalls out of the while loop and continues execution with the statement following the while. In this case, that statement prints our output, followed by the return, which completes our main program.
 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇1.3 AWord about Comments (2) 下一篇1.4 Flow of Control (4)

评论

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

·数据库:推荐几款 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)