# BE A CODER (C/CPP track) ## videos <iframe width="560" height="315" src="https://www.youtube.com/embed/msiXme3fDwk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <iframe width="560" height="315" src="https://www.youtube.com/embed/PEYN3isSyPo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <iframe width="560" height="315" src="https://www.youtube.com/embed/bY2bTXKnHRs?si=UFmfrXOu1NzIaPOx" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> <iframe width="560" height="315" src="https://www.youtube.com/embed/MNYSSQ88Va0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <iframe width="560" height="315" src="https://www.youtube.com/embed/VOHvdoYsvHw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <iframe width="560" height="315" src="https://www.youtube.com/embed/k9GzHxQTD-g" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> ## prior skill (recommand) - [typing training](https://typethealphabet.app/) complete in 3 secs - [markdown learning](https://markdown.tw/) ## tools, environments ### mobaxterm [download](https://mobaxterm.mobatek.net) your shell tool, what is [shell](https://zh.wikipedia.org/zh-tw/殼層)? ### commands in the shell - ls, touch, cd, cat, mv, rm - vim the editor in CLI(command line interface) what is GUI? - tmux a terminal multiplexer - ~~xdg-open (you can alias to open) `alias open='xdg-open'`~~ use open directly in mobaXterm - gcc, g++ your [GNU](https://zh.m.wikipedia.org/zh-tw/GNU) c/c++ compiler - man, `--help`(`-h`) flag for any command how to use the commands? here is a [cygwin introduction](https://nobodyzxc.github.io/2017/05/30/basic-linux/#more), most of the commands are available in mobaxterm, and the rest ones also have corresponding ones in mobaxterm. and here are some vim intros - [manipulation](https://nobodyzxc.github.io/2017/01/22/vim-0/#more) - [configuration](https://nobodyzxc.github.io/2020/11/18/vim-1/#more) ## what is a program | program | article | | -------- | -------- | | Programming Language | Nature Language | | function | paragraph | | statement; (c/c++) | sentence. | | expression | word | | operand / operator | letter | | order machine | for human mind | ## start from a c/c++ program ```c #include <stdio.h> int main(int argc, char **argv){ puts("hello world"); return 0; } ``` ### [Flow of Control](https://www.cs.fsu.edu/~myers/c++/notes/control1.html) <ul> <li> <b>Sequential</b>: default mode. Sequential execution of code statements (one line after another) -- like following a recipe</li> <li> <b>Selection</b>: used for decisions, branching -- choosing between 2 or more alternative paths. In C++, these are the types of selection statements: <ul> <li><tt>if</tt></li> <li><tt>if/else</tt></li> <li><tt>switch</tt></li> </ul> </li> <li> <b>Repetition</b>: used for looping, i.e. repeating a piece of code multiple times in a row. In C++, there are three types of loops: <ul> <li><tt>while</tt></li> <li><tt>do/while</tt></li> <li><tt>for</tt></li> </ul> </li> </ul> ```clike #include<stdio.h> int main(){ int i = 0; while(i < 10){ if(i < 5) puts("small"); else puts("big"); i += 1; } return 0; } ``` ### Von Neumann Architecture #### [Von Neumann Architecture](https://medium.com/linkit-intecs/computer-architecture-models-d163cfefd9c5) ![](https://i.imgur.com/8Z7BDav.png) #### code is also a kind of data #### storage level - register - memory - external storage (disk, ...) bit > 0 or 1 byte = 8bit = 2^8 states KB = 1024 byte MB = 1024 KB GB = ... TB = ... PB = ... (2^10) ### compiler & interpreter #### compiler context program: you compiler: translator machine: worker you want the worker to do something, but the worker doesn't understand your language, so you make the translator communicate with the worker for you (the translator may write down all your commands and pass it to the worker). > program that convert code from language to language #### interpreter context program: you interpreter: worker that know your language you can communicate with the worker directly, but his working skill is not good as previous one (the one doesn't know your language) > program that execute your code directly ![](https://i.imgur.com/4yOkQiH.png) ![](https://i.imgur.com/JO469dM.png) ![](https://i.imgur.com/UWbVu4P.png) Note: HTML and markdown **are not** programming languages, but you can call them **markup languages**. ## build your program in shell call compiler directly (gcc/g++) makefile alias --- ## part I. basic c ### main function, comment and indent ```c // here is a comment int main(){ /* no execute */ return 0; } ``` ```c int main(){ return 0; } ``` other types of main: ```c int main( void ) int main( int argc, char *argv[] ) int main( int argc, char *argv[], char *envp[] ) ``` and lagacy: void main ### data types, variable, literal, casting and operators #### types - void (imcomplete type, cannot to declare variables) - char (1 byte) - short (2 bytes) - int (4 bytes) - float (4 bytes) - double (8 bytes) *keyword*: `unsigned`, `long` |Type Name | 32–bit Size |64–bit Size| |---|---|---| |short |2 bytes |2 bytes| |int |4 bytes |4 bytes| |long |4 bytes |8 bytes| |long long |8 bytes |8 bytes| [reference](https://docs.oracle.com/cd/E19253-01/817-6223/chp-typeopexpr-2/index.html) #### variable names start with [a-zA-Z] and _ declare a variable with type ```c // type variable; int i; char ch; // you can have a initial value int j = 0; int i; // dumplicate declaration ``` #### scoping - global (can be accessed anywhere) - local - static (would be mentioned in the future) #### literal unsigned: `3u` unsigned long: `314ul` char literal: `'a'` decimal literal: `123` hex literal: `0xff` oct literal: `0o34` string literal: `"abcde"` (array) float literal: `3.14f` double literal: `3.14` long double: `3.14L` #### casting ```c int a = 3; double b = a; // (ok) b = 4.4; ``` implicit: ```c a = b; // a == ? ``` explicit: ```c a = (int)b; ``` #### operators - `=` - `+`, `-`, `*`, `/`, `%` - `==`, `>`, `>=`, `<`, `<=` - `+=`, `-=`, `*=`, `/=`, `%=` - `&&`, `||`, `&`, `|`, `++`, `--` ... - `expr ? expr : expr` (ternary operator) ### function **keyword**: return ```clike int global = 0; // return_type function_name (parameter_type variable...) int f(int a, int b){ return a + b; } void g(int value){ global = value; } int main(void){ g(5) return f(3 + 4 + global); // return the value } ``` ```bash gcc -o func func.c ./func echo $? ``` ### expression (non-void) - literal (1, 2.3, "asdf"), variable (a, i) - combinations of operator and operands (1 + 2, i++, a += 2) - function (non-void) ### I/O ```c #include<stdio.h> int nth; scanf("%d", &nth); // note "&" operator, pass the address printf("hello %dth world\n", nth); ``` introduction: [link](https://openhome.cc/Gossip/CGossip/PrintfScanf.html) ### header files and basic preprocessing ```c #include<stdio.h> ``` ```c #define N 100 ``` ### compilation of multiples file and headers ```c #ifndef _HEADER_H_ #define _HEADER_H_ ... #endif ``` ```c void f(int x, int y); ``` ```bash gcc -c *.c gcc -o main *.o ``` ### control flow **keyword**: break, continue - if, else ```clike if(expr) statement else statement // optional if(expr) statement else if(expr) statement // optional else statement // optional // one-line statement statement // compound statement { statement... } // above as stmt // cases: if(a != b) puts("!=");j else if(a){ puts("a"); } // if no { ... } ? else puts("b"); if(i % 2) puts("a"); puts("b"); // how to modify? int true = 1, false = 0; if(true) puts("hello"); else if(true) puts("world"); if(true) puts("hello"); if(true) puts("world"); if(true) puts("hello"); else puts("hello"); if(false) puts("hello"); else if(false) puts("hello"); if(true) puts("hello"), puts("world"); int i = (1, 2, 3); ``` - while/do-while ```c while(expr) stmt do{ stmt } while(expr); // convert do-while to while stmt while(expr) stmt // cases int i = 0; while(i != 10){ printf("%d\n", i); i += 3; } // result? int j = 0; do{ printf("%d\n", j); j += 3; }while(j < 10); // result? ``` - for ```c for(expr; expr; expr) stmt for(init; cond; next) stmt // convert to while { init; while(cond){ stmt next; } } // cases: // you can ignore any expr in (...) for(;;;) puts("yes"); int i = 3, j = 90; for(i = 0; i < 5; i += 2) puts("test"); // in newer version gcc/g++ you can declare in (...) for(int i = 0; i < 10; i++) printf("hello %d\n", i); for(int i = 0, j = 0; i + j < 10; i += 1, j += 2) printf("i = %d, j = %d\n", i, j); ``` ```clike for(int i = 0; i < 10; i++){ if(i == 4) continue; printf("%d", i); } for(int i = 0; i < 10; i++){ if(i == 4) break; printf("%d", i); } ``` ### statement (void) in most case, code ended with `;` and `}` (keyword structure). `1` => expression `1;` => statement `for(;;;){ ; }` => statement ```c int i = 0; ---------- statement for(i = 0; i < 10; i++){ printf("%d\n", i); } ----- ------ --- ----------------- expr expr expr expr ------------------ statement --------------------------------------------- statement a += 1, a += 1, a += 1; ------ ------ ------ expr expr expr -------------- expr ---------------------- expr ----------------------- statement ``` ### array and string (char array) ![](https://i.imgur.com/zEQTMSX.png) ```c int a1, a2, a3; #define SIZE 5 int a[SIZE]; // a[0], a[1], [2]; for(int i = 0; i < SIZE; i++) a[i] = i, printf("a[%d] = %d", i, a[i]); for(int i = 0; i < sizeof(a) / sizeof(a[0]); i++) printf("a[%d] = %d", i, a[i]); ``` initialize array ```c int a[10] = {0}; // => ? int b[10] = {1, 2, 3}; // => ? ``` ```c // determine the size automatically const int a = 3; a = 5; // error int scores[] = {1, 2, 3}; char str[] = "hello"; int s[2][3] = {{1, 2, 3}, {3, 4, 3}}; // size of? printf("size of scores: %lu\n", sizeof(scores) / sizeof(scores[0])); printf("size of str: %lu\n", sizeof(str) / sizeof(str[0])); // iterate them? // pass to function? int f(int ss[][3]){ // ... } f(s); // you can ignore the first dimension ``` ```c int data[3][3]; void init(int d[][3], int row){ for(int i = 0; i < row; i++) for(int j = 0; j < 3; j++) d[i][j] = 0; } // c99 void init(int row, int col, int d[row][col]){ for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) d[i][j] = 0; } ``` > more ways to pass 2d array: [reference](https://www.geeksforgeeks.org/pass-2d-array-parameter-c/) we will discuss pass array as pointer in the future --- ## exercise implementations: 1. print 9x9 table 2. write a function that return first position of positive value, otherwise return -1. ```c int find_pos(int n, int array[n]); ``` 3. find max/min value in the array. ```c int max(int n, int array[n]); int min(int n, int array[n]); ``` 4. sum all the values in the array. 5. return the average value of the sum. ```c int sum(int n, int array[n]); float avg(int n, int array[n]); // note the type ``` ### practice on UVa you can use the [command line tool](https://github.com/arafat-hasan/uva-tool) ### practice on [codewars](https://www.codewars.com/) [even or odd](https://www.codewars.com/kata/53da3dbb4a5168369a0000fe) [debug the multiply](https://www.codewars.com/kata/50654ddff44f800200000004/train/c) [sum of positive](https://www.codewars.com/kata/5715eaedb436cf5606000381) [return negative](https://www.codewars.com/kata/55685cd7ad70877c23000102) [reverse string](https://www.codewars.com/kata/5168bb5dfe9a00b126000018) - kyu 8 x4 - kyu 7 x3 - kyu 6 x2 - kyu 5 x1 --- ## part II. advanced c ![](https://i.imgur.com/6rbn5wh.png) [data in memory](https://courses.engr.illinois.edu/cs225/sp2022/resources/stack-heap/) ### recap the scope - global - local - **static** ```c int f(){ static int a = 0; // statements return a++; } int main(){ printf("%d\n", f()); } ``` ### advanced data type - struct - enum - union ```c struct Person { char name[10]; int age; }; #include<string.h> int main(){ struct Person a = { "hello", 10 }; printf("%s\n", a.name); a.name = "world"; // wrong strcpy(a.name, "world"); a.age += 3; } ``` > bonus: know the usage of [typedef](https://groangao.pixnet.net/blog/post/24474489) ```c typedef char[10] Name; typedef int Age; typedef struct { Name name; Age age; } Person; int main(){ Person a = { "hello", 3 }; Person people[10]; // ten people return 0; } ``` ```c enum Day { Sunday, // value = 0 Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; //... const int Monday = 1; // if today == Monday int main(){ Day today = Monday; printf("%d\n", today); } ``` ```c union Number { int i; float f; double d; long l; }; int main(){ Number n; n.i = 4; printf("%d\n", n.i); n.d = 3.14; printf("%lfn\n", n.d); printf("%d\n", n.i); } ``` ### pointer ![](https://i.imgur.com/nnvvc1U.png) ```c void f(int array[]){ // same as (int *array) } void g(int array[][3]){ // same as (int (*array)[3]) // != (int *array[3]) } ``` [reference](https://stackoverflow.com/questions/69249996/functions-with-multi-dimensional-arrays-as-formal-parameters ) of convertion from array to pointer when pass to function ```c void modify(int *ptr, int val){ *ptr = val; } int main(){ int val = 2; int *p = &val; int **pp = &p; printf("%d == %d\n", *p, val); modify(p, 3); printf("%d != %d\n", *p, val); return 0; } ``` ```c void f(int *array, int r, int c){ for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++) printf("%d\n", *(array + i * r + j)); } } // pass data[*][*] ? // array of pointer, different from 2d array // you **can not** pass // int array[2][2] for g as g(2, 2, array) // wrong!!!! void g(int r, int c, int *array[]){ for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++) printf("%d\n", *(array[i] + j)); } } int main(){ int a[3][3]; f(a, 3, 3); } // data[*][*] is *data with size ``` ![](https://i.imgur.com/ZyxN4sc.png) ### recursion ```c int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } ``` exercise: implement fib ```c int fib(int n){ // 0 1 1 2 3 5 if .... return ...; else ... return ...; } ``` ### dynamic allocation (malloc/free) allocate on heap ```c int *ptr = (int*)malloc(100 * sizeof(int)); free(ptr); // you need free after malloc ``` ### define data structure ```c #include<stdio.h> #include<stdlib.h> typedef struct Node { int value; struct Node *next; } Node, *Nodeptr; // (.) -> (.) -> (.) -> NULL int main(){ Node *node = (Nodeptr)malloc(sizeof(Node)); (*node).value = 5; // node->value = 5; node->next = node; Nodeptr cur = node; while(cur){ printf("%d", cur->value); // inf cur = cur->next; } return 0; } ``` > bonus: how to allocate 2D array? // node operations ```c // construct a new node Node* newNode(int val, Node* next){ } // append tail to tail of list Node* append(Node *cur, Node *tail){ } // add a new node to list head Node* cons(Node *cur ,Node *next){ } // release the list void *deleteList(){ } ``` --- ## bonus for c ### function pointer refernece: [link](https://chenhh.gitbooks.io/parallel_processing/content/cython/function_pointer.html) ### advanced preprocessing ```c #define add(x, y) ((x) * (y)) // if add(x, y) (x * y) // add(1+2, 3+4) // (1+2) * (3+4) ``` --- ## part III. basic c++ ### type casting ```cpp double d = 3.14; int a = int(d); // like a function auto b = 4; // type inference (cpp) ``` ### polymorphism > function overloading ### namespace ```cpp namespace lib { int x; } lib::x = 3; namespace { int y; } ::y = 4; ``` ```cpp std::cout << "hello world" << std::endl; ``` ```cpp using namespace std; cout << "hello world" << endl; ``` ```c #include<stdio.h> #include<cstdio> ``` ### c++ flavor I/O, string ```cpp #include<iostream> int x, y, z; cin >> x >> y >> z; cout << x << 3.14; std::string str; // why char a[10]; // a = "asdf"; is not ok but // str = "asdf" is ok? // int array[10], *ptr; // array = ptr; // <= not ok? ``` ### object oriented programming ```cpp class Obj { public: // bonus: other types of constructor Obj(int v){ val = v; } // other types of constructor void show(){ std::cout << val << std::endl; } void set(int v){ val = v; } private: int val; protected: // bonus: more about oop, inheritance } // bonus: inheritance int main(){ Obj obj(3); // Obj obj = Obj(3); obj.show(); obj.set(4); obj.show(); return 0; } ``` ### reference ```c void mod(int *var, int val){ *var = val; } void mod(int &var, int val){ var = val; } int main(){ int a = 3; mod(&a, 4); mod(a, 5); int &b = a; b = 7; } ``` ### dynamic allocation (new/delete) ```cpp int main(){ Obj *obj = new Obj(3); delete obj; // delete after every new int *arr = new int[10]; return 0; } ``` ### template (STL) ```cpp template <class T> T add(T a, T b){ return a + b; } int main(){ add(1, 3); add(1.3, 1.5); } ``` ```cpp #include<vector> using namespace std; vector<int> vec; for(int i = 0; i < 10; i++) vec.push_back(i); // pop_back, push_front, pop_front for(auto v: vec) cout << v << " "; ``` - vector - map - set more STL: [link](https://nobodyzxc.github.io/2017/10/05/cpp-stl/#more) ### data structure - linked list ``` . -> . -> . ``` - binary tree ``` . / \ . . / \ / \ . .. . ``` - tree, graph - bfs, dfs ADT - stack - queue - map - set ### algorithm > discussion about complexity > sorting algorithm collection > complexity --- ### other resources [cp1 syllbas](http://newdoc.nccu.edu.tw/teaschm/1041/schmPrv.jsp-yy=104&smt=1&num=703049&gop=00&s=1&tea=114662.htm) [cp2 syllbas](http://newdoc.nccu.edu.tw/teaschm/1032/schmPrv.jsp-yy=103&smt=2&num=703050&gop=00&s=1&tea=114662.htm) [my college lesson material](https://drive.google.com/file/d/1B3rCJE9kE9u07CzkUqF1plXP6WRtcysh/view?usp=sharing)