BP-3-1 Selection Control

Chapter 03 Control Flow

1. Algorithm

Algorithm describes the control of the flow, such as which expression computes first, whether to compute some expressions or repeating computing some expressions several times.

We use statement to describe and implement algorithm.

Sometimes we choose to first draw a flowchart to help us clarify the algorithm before we actually write some code to implement it.

2. Sequential Execution

  • Expression Statement

An expression statement is just an expression with ; behind it, which does the same thing as the expression but is a complete statement.

  • Compound Statement

Compound statement is composed of several statements, with { before them and } behind them, which is also called block.

  • Blank statement

Blank statement is just ;, which does nothing at all. What it only does is that it plays a grammar role or syntax role at a place where it needs nothing but a statement to make it grammatically appropriate.

3. Selection Control

Selection control also called branching control allows us to execute some statements selectively according to some conditional judgments, which is implemented using if-statement or switch-statement.

3.1 If-statement
if (<boolean-expression>) <statement(s)>
if (<boolean-expression>) <statement(s)1> else <statement(s)2>

C++ doesn’t take writing style into consideration when reading your code.

Unlike python, indent makes no sense in C++ other than make your code easier for other coder to understand.

Each else is coupled with its nearest if.

3.2 Switch-statement
switch (<integral-expression>){
    case <integral-constant-expression1>: <statement-sequence1>
    case <integral-constant-expression2>: <statement-sequence2>
    ......
    case <integral-constant-expressionn>: <statement-sequencen>
    [default: <statement-sequencen+1>]
}

Integral constant expressions’ values can’t be the same with each other.

Statement sequence can either be a statement or a block without parentheses, and regularly end with a break statement.

Rules for execution:

  • Evaluate the integral expression to get an integer value.
  • Compare the value with all the following cases one by one until the integral constant expression with the same value.
  • Execute the statement sequence behind it until it reach the end or encounter a break statement.
  • If there’s no corresponding case, execute the statement sequence behind default if there exists one.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值