Control Statement_2-程式設計筆記

Shih Jiun Lin Lv4

Chapter 4, Control Statement_2

do...while

1
2
3
do{

}while;(condition)
  • do...while always check the continuation after the code inside the {} has been excecuted. Therefore, it will execute at least one time.

switch case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
switch(expression){
case constant1:
//execute while expression is constant1;
break;
case constant2:
//execute while expression is constant2;
break;
case 'F':
case 'f':
//execute while expression is F or f;
break;
.
.
.
case 3+2:
//not allowed
case 1+4:
//not allowed

default:
...
//code to be executed if expression doesn't
// match any constant

}
  • Perform many different actions based on the value of expression.

setw()

  • setw() => print spaces to make it tidy.

EOF

  • EOF => End of file by entering ctrl+z.
    1
    2
    3
    4
    cin>>sth;
    while(cin.get()!=EOF){
    ...
    }

cin.get() vs cin>>

  • cin.get() -> only read one character.
  • cin -> depends on >>.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    #include <iostream>
    int main(){
    int grade, aC{0}, bC{0}, cC{0};
    while((grade=std::cin.get())!=EOF){
    switch(grade){
    case 'a':
    aC++;
    break;
    case 'b':
    bC++;
    break;
    case 'c':
    cC++;
    break;
    case '\n':
    case '\t':
    case ' ':
    break;
    }
    }
    std::cout<<aC<<' '<<bC<<' '<<cC;
    }

C++ Modified Data Types

Continue vs Break

  • Continue -> Only skip a specific process.
  • Break -> Skip the whole process.

Boolalpha

1
2
3
4
std::cout<<true<<"\n";
std::cout<<std::boolalpha;
std::cout<<true<<"\n";
//The result will be 1 and true.

Operator's Precedence

  • The right side of the && will only be considered if the left side is true.
  • The && operator has a higher precedence than ||.
  • Any nonezero value is interpreted as ture. Which means if(a=5){...} will be true.
  • Title: Control Statement_2-程式設計筆記
  • Author: Shih Jiun Lin
  • Created at : 2023-01-17 23:00:50
  • Updated at : 2023-01-24 01:31:50
  • Link: https://shih-jiun-lin.github.io/2023/01/17/Chapter 4, Control Statement_ Part 2/
  • License: This work is licensed under CC BY-NC-SA 4.0.