Control Statement_1-程式設計筆記

Shih Jiun Lin Lv4

Chapter 3, Control Statement_1

Control Structure

  • The sequence structure
  • The selection strcture
  • The repetition structure

Selection Statements

  • To choose among courses of action.
  • if: A single-selection statement
  • if...else: A double-selection statement
  • switch: A multiselection statement

Conditional Operators(?:)

  • Closely related to the if..else function.

Ex:

1
2
3
4
5
6
#include <iostream>
int main(){
int x{0}, y{1};
result=x<y?"x<y":"x>y";
std::cout<<result;
}
Accodring to the code, it will cout xy in the command prompt.

  • Another way to declare integers: int x{0} equals to int x=0

Repetition Statements(Looping Statements)

  • while: do the action zero or more times.
  • do...while: do the action at least once.
  • for: do the action zero or more times.

Counter Controlled Repetition

  • Counter variables are normally initialized to zero or one, depending on their use.
  • Remember to initialize the counter varible, or it might contain some garbage variable.

How to change the tpye of a object

1
2
3
4
5
#include <iostream>
int main(){
static_cast<type>(object);
(type)object;
}

setprecision()

1
2
3
4
5
6
#inlcude <iostream>
#include <iomanip>
int main(){
std::cout<<std::setprecision(2)<<floatnum; //start from the first num after fixed point
std::cout<<fixed::std::setprecision(2)<<floatnum; //start from the first num before fixed point
}

Common Keywords in C++ and C

Assignment Operators

Preincrement and Postincrement

  • Preincrement => Increment a by 1, then use the new value of a in the expression in which a resides.
  • Postincrement => Use the current value of a in the expression in which a resides, then increment a by 1.

Ex:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
int main(){
int a=1;
cout<<a<<"\n";
cout<<a++<<"\n";
//do a=a+1 after cout
int b=1;
cout<<b<<"\n";
cout<<++b<<"\n";
//do b=b+1 before cout
}

  • Title: Control Statement_1-程式設計筆記
  • Author: Shih Jiun Lin
  • Created at : 2023-01-17 23:00:50
  • Updated at : 2023-01-24 01:31:39
  • Link: https://shih-jiun-lin.github.io/2023/01/17/Chapter 3, Control Statement_ Part 1/
  • License: This work is licensed under CC BY-NC-SA 4.0.