Review
第一階段複習
Jason
Content
- Type, Variable, and Operator
- Flow Control
- Array & C-Style String
- Pointer
- Function
上週作業講解
void solve(char message[]) { srand(time(NULL)); encrypt(message, t - (rand() % 1000)); cout << message; }
Can we assume the time() will return the same value?
Then we can get the same random values from rand()
Type, Variable, and Operator
Type 變數型別
int, char, long long, float, ...
Variable 變數
type variableName (= initialValue); int test = 10; char c = 'a'; long long l = 2147483648; c = 'k';
Type, Variable, and Operator
Operator 運算子
int a; cin >> a; // read integer from stdin cout << a + 50 << endl; // output result to stdout a += 10; a -= 20; a /= 5; a *= 10;
Quick Question: How many operators in above?
Flow Control
Conditions (條件判斷)
bool cond1 = {...}; bool cond2 = {...}; if(cond1) { // cond1 = true if (cond2){ // cond2 = true } else { // cond2 = false } } else if(cond2) { // cond1 = true & cond2 = false } else { // cond1 = false & cond2 = false }
Can be Nested / Conditions are evaluated as boolean
Flow Control
Loops
int i = 0; while(i < 10){ cout << i << endl; i++; } for(int i = 0; i < 10; i++){ cout << i << endl; } for(int i = 0; i < 10; i++){ for(int j = 0; j < i; j++) cout << "*"; cout << endl; }
Quick Question: Can all for-loop be translated to while-loop
Quick Question: Can all while-loop be translated to for-loop
Array & C-Style String
Array: Multiple items of same type
int arr1[10] = {1,2,3,4}; int arr2[] = {3,4,5,6,7}; char arr3[] = "Hello?"; double arr4[105]; for(int i = 0; i < 105; i++) cin >> arr4[i]; int arr2D[10][20]; for(int i = 0; i < 10; i++) for(int j = 0; j < 20; j++) arr2D[i][j] = i * j;
How many indices allocated in above code?
Array & C-Style String
C-Style String: Basically char array ended with '\0'
char s1[] = "Hello?"; char s2[10]; strcpy(s2, s1); cout << s2 << endl; cout << strlen(s2) << endl; // print ascii value for each char in s2 for(int i = 0; s2[i]; i++) cout << (int)s2[i] << endl; // concat two string char sa[] = "???"; strcat(s2, sa); cout << s2 << endl;
The size of s1 array is?
Pointer
Variable that points to variable address
int a = 10; int *ptr = &a; cout << ptr << " " << *ptr << endl; *ptr = 20; cout << ptr << " " << *ptr << " " << a << endl; int b = 20; ptr = &b; *ptr = 30; cout << a << " " << b << " " << *ptr << " " << ptr << endl; int arr[10] = {1,2,3,4,5,6,7,8,9,10}; cout << *(arr+5) << " " << arr[5] << endl;
What will be the output?
Function
A way to modularize procedures
// passing parameters by value / address / reference int addA(int a, int *arr, int n){ for(int i = 0; i < n; i++) arr[i] += a; } // swap(&a, &b); void swap2(int *a, int *b){ int tmp = *a; *a = *b; *b = *a; } // swap(a, b); void swap1(int &a, int &b){ int tmp = a; a = b; b = a; }
Return type / Parameter type / Passing by value, address or reference
Review
By jason-plainlog
Review
- 206