# Computer Programming (I)
NTNU 程式設計(一)
##### [Back to Note Overview](https://reurl.cc/XXeYaE)
###### tags: `NTNU` `CSIE` `必修` `Programming(I)`
###### Author Team:@kizato @sophie8909 @joseph89108 @AWfulsome @HsuanYu @RuiRabbit @KaoZhai @ShihHeng @Eoleedi
### [Moodle](https://moodle.ntnu.edu.tw/course/view.php?id=19520)
### [Class Web](https://sites.google.com/gapps.ntnu.edu.tw/neokent/teaching/2019fall-computer-programming-i)
### [Homework Sample](##Homework)
{%hackmd hackmd-dark-theme %}
## Tips
#### 貼網址時請多加善用 [網址縮小燈](https://reurl.cc/main/en)
#### 不知道顏色的時候 [色碼查詢器](https://www.ifreesite.com/color/)
>**非管理員但願意加入筆記編寫的**
>
>可在此區留言或直接跟Admin們要Write權限
>給帳號(profile裡@的那串)或email皆可
>所有**登入帳號**都可以在留言區發言
>有問題可以直接留言區留
>**修正注意事項**
>麻煩發現**觀念錯誤**的先以~~這種方式~~修改並標上日期提醒其他人
> 錯字類的直接修改即可
---
## 課堂影片紀錄檔
https://reurl.cc/A1gLZp
---
## Integrated Development Environment
* [Visual Studio](https://visualstudio.microsoft.com/downloads/)
* 超級肥 [name=AWfulsome]
* [Code::Blocks](http://www.codeblocks.org/downloads/26)
* 這個還行就是很肥 然後預設介面是白的眼睛好痛[name=sophie]
* [Dev-C++](http://orwelldevcpp.blogspot.com/)
* 這個超難用的啦 還很醜 用它不如用Sublime [name=sophie]
* 以前學校都教這個 [name=HsuanYu]
* 我普遍用這種 [name=KaoZhai]
* 明明就很好用,內建編譯器雖然舊但還夠用 [name=王麒翔]
* [Visual Studio Code](https://code.visualstudio.com/?wt.mc_id=vscom_downloads)
* 這個要自己安裝編譯器還要設置環境很複雜,Linux更複雜。[name=蕭瀜]
* [Eclipse](https://www.eclipse.org/downloads/)
* 我自己印象比較深刻就是它有可以直接視窗化的外掛(windowbuilder)可以用 [name=sophie]
* 另外如果有想打競程的NCPC決賽可以用的IDE只有這個跟Netbeans [name=sophie]
* 有點肥跑得有點慢但Debug模式不錯用 [name=Joseph Tu]
---
## Text Editor
* [SublimeText](https://www.sublimetext.com/3)
* 私心大推:heart: 它介面很好看!![name=sophie]
* 這個介面真的很好看 我沒記錯可以裝像是插件的東西讓你打程式變很快[name=KaoZhai]
* 灰底看了就是很舒服 還可以多行同時編輯 很方便 [name=HsuanYu]
* [Vim](https://www.vim.org/download.php)
* 老牌文字編輯器,腳本寫得好並善用外掛可以變超強,但我腳本寫不好也不會用外掛... [name=AWfulsome]
---
## Linux
### Use Virtual Box
[安裝](https://reurl.cc/jdqj1n)
[調整顯示大小](https://reurl.cc/4gy712)
### Use Dual Systems
[Win10](https://reurl.cc/EK2MRK)
(Mac 沒裝過會怕...還是乖乖用VM就好)
### Terminal
```
ls 展開此目錄下的東西
-a 顯示所有目錄、檔案,包含隱藏的
-l 以列表方式呈現
cd 切換到此目錄(change directory)
cd ~ 返回家目錄
cd .. 返回上一層
cd . 回到這一層
gcc 編譯
-o xxx 將編譯後檔案命名為xxx
-Wall 顯示所有警告
pwd 顯示目前完整路徑
./ 當前位置
~/ 家目錄位置
rm 刪除檔案
-r 遞迴往下刪
-f 強制刪除
mv 移動檔案
mv A.txt B.txt 將A.txt改名B.txt
mkdir 新增目錄
rmdir 刪除目錄
```
更多可看[CTF Note](https://hackmd.io/uF8P3o-RTt68JxkhPuryAQ)
---
## 9/18 First coding class
### Code 【Hello World】
```c=
#include <stdio.h>
int main(){
// Your first code.
printf("Hello World!\n");
return 0;
}
```
### 豆知識
printf 的 "f" 代表 format
gcc 在沒有 include stdio.h 時也可以成功編譯 printf
gcc 是給 C 用的,C++ 要用 g++
---
## 9/20 Makefile
### Make
先建一個檔名為"GNUmakefile"or"Makefile" or "makefile"的檔案
##### 內容:
```make
all:
gcc -o "你的檔名".c -o "filename"
clear:
rm "filename"
```
裡面都可以寫要執行的指令,之後還會有連結檔案。
### 豆知識
RTFM:read the Fucking manual
STFG:search the Fucking google
---
## 9/25 Simple Code
### Code 【Addition】
```cpp=
#include<stdio.h>
//Variable
int main()
{
int a = 2;//賦予a 2的數值
int b = 3;
int sum = 0;
sum = a + b;//先算a+b 之後再賦值給sum
printf("sum = %d\n", sum );
return 0;
}
```
### Other code 【Exponential Function】
```c=
#include <stdio.h>
#include <math.h>
int main ()
{
printf ("7 ^ 3 = %f\n", pow (7.0, 3.0) );
printf ("4.73 ^ 12 = %f\n", pow (4.73, 12.0) );
printf ("32.01 ^ 1.54 = %f\n", pow (32.01, 1.54) );
return 0;
}
```
### Pratice & Answer
請用C寫出 0.5 + 2.7 * 3.2 - 6.8 / 2.4 的答案
```c=
#include <stdio.h>
int main()
{
printf("%f\n", 0.5 + 2.7 * 3.2 - 6.8 / 2.4);
return 0;
}
```
[wiki_Clang](https://zh.wikipedia.org/zh-tw/Clang)
### Print Format
| | 意思 | 宣告 |備註|
| -------- | -------- | -------- |--------|
| %d | 十進位整數 | int |decimal int|
|%i|整數|int|%d and %i are synonymous for output, but are different when used with scanf() for input where using %i will interpret a number as hexadecimal if it's preceded by 0x, and octal if it's preceded by 0|
| %f|浮點數|float|如果寫成 %.xf 會只顯示到小數點下第x位,並四捨五入|
|%u|無號整數|unsigned int|如果題目不會遇到負數 然後最大範圍到2^32^-1的時候可以用|
|%c|字元|char||
|%s|字元陣列|char*||
|%%|列印%|------|
#### %i using sample
```c=
#include <stdio.h>
int main()
{
int a, b, c;
//Enter value of a in decimal format
scanf("%i", &a); // input 12
//Enter value of b in octal format
scanf("%i", &b); // input 012
//Enter value of c in hexadecimal format
scanf("%i", &c); // input 0x12;
printf("a = %i, b = %i, c = %i", a, b, c);
return 0;
}
// output >> a = 12, b = 10, c = 18
```
[wiki](https://en.wikipedia.org/wiki/Printf_format_string)
---
## 9/27 Makefile認真看不會就問
###### (其實真的不懂的話,只要會交作業的make就好了)
### Makefile規則
```
Target : 目標檔案,格式包含 Object 、執行檔、標籤(Label)
Dependency : 產生目標檔案(Target)所需要的檔案
Command : Make 之後執行的命令、每行 Command 需用 Tab 鍵縮排不能用 Space
這是一個文件的依賴關係,target這個目標檔案會依賴於dependency中的文件,其生成規則定義
在command中。如果dependency中如果有一個以上的文件比target文件要新的話,command 所定
義的命令就會被執行。這是Makefile最核心的內容。
```
### 慣用Label
```
all: 置於所有Flag頂端,執行所有編譯(通常為最終目標)
clean: 清除所有編譯過程產生的非執行必要檔
info: 產生info檔案
check 或 test: 確認所有檔案已產生
install: 進行安裝指令(編譯後放入安裝路徑)
uninstall: 刪除install產生的檔案
```
### 預定義變數
```
CC: C語言編譯器, cc
CPP: C語言 / c++編譯器, $(CC) -E
CXX: C++語言編譯器 ,g++
CFLAGS: C語言編譯器的編譯選項
CPPFLAGS: C語言前處理器的編譯選項
CXXFLAGS: C++語言編譯器的編譯選項
INCLUDE: 要包含進的函式庫資料夾路徑
srcdir: 需要 compile 的 source code 資料夾路徑
RM: 刪除檔案程式的名稱, rm f
```
### 偽目標 (.PHONY)
```
.PHONY會將目標檔案射成假目標,使make目錄下沒有目標檔案或目標檔案圍最心時,仍可執行
make <target>。.PHONY寫法也可以讓程式設計師知道哪些工作目標不是針對檔案,增加可讀
性。
Make 預設的假工作目標有all, install, clean, distclean, TAGS, info, check。
```
#### Example 1
```make
clean:
rm *.c temp
.PHONY:clean //假設同資料夾中有叫做clean的檔案 加上.PHONY就可以正常執行clean指令
clean:
rm *.c temp
```
#### Example 2
```make
all : prog1 prog2 prog3
.PHONY : all //定義一個all偽目標 這個all會去叫prog123
prog1 : prog1.o utils.o //叫做prog的target
cc -o prog1 prog1.o utils.o
prog2 : prog2.o
cc -o prog2 prog2.o
prog3 : prog3.o sort.o utils.o
cc -o prog3 prog3.o sort.o utils.o
```
### Variables
1. 宣告時給予初值
2. 使用時在變數名稱前加「$」
ps:最好用小括弧「()」或大括弧「{}」將變數包括起來
3. 使用「$」字元時用「$$」表示
#### Example
```
foo = $(bar) #宣告 foo 的值為 $(bar) , foo=c
bar = c #宣告 bar 的值為 c
x := foo #宣告 x 的值為 foo
y := $(x) bar #宣告 y 的值為 $(x) bar , y=foo bar
x := later #宣告 x 的值為 later
FOO ?= bar #如前面未定義 FOO 之值將其定義為 bar
foo := a.o b.o c.o #宣告foo為 a.o b.o c.o
bar := $(foo:.o=.c) #將 foo 中的 .o 全部替換成 .c
```
### Wildcard
- 輸出資料夾中指定格式的文件名稱,以空白分隔
#### Example
```make
$(wildcard *) //所有檔案
a b c a.c b.c c.o x.exe
$(wildcard *.c) //所有副檔名為c的檔案
a.c b.c
$(wildcard c*) //所有檔名為c的檔案
c c.o
$(wildcard *.*) //所有有附檔名的檔案
a.c b.c c.o x.exe
$(wildcard *.c ./sub/*.c) //同時尋找
```
---
## 10/2 stdint.h
### stdint
```c=
#include <stdint.h>
```
```
int8_t :8-bit signed integer
int16_t :16-bit signed integer
int32_t :32-bit signed integer
int64_t :64-bit signed integer
uint8_t :8-bit unsigned integer
uint16_t :16-bit unsigned integer
uint32_t :32-bit unsigned integer
uint64_t :64-bit unsigned integer
```
### Code
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t a = 2;
int32_t b = 3;
int32_t sum = 0;
printf("Please enter the first integer:\n");
scanf( "%d", &a );//不要問為什麼要& L紀說背起來
printf("Please enter the second integer:\n");
scanf("%d", &b );
sum = a + b ;
printf("%d + %d = %d\n", a, b, sum );
return 0;
}
```
### Practice Code 【Area of Trapezoid】
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t b1;
int32_t b2;
int32_t h;
double area;
printf("Calculate Area of Trapezoid\n");
printf("Please enter b1 & b2:\n");
scanf( "%d %d", &b1 , &b2 );
printf("Please enter h:\n");
scanf("%d", &h );
area = (float)( b1 + b2 ) * h / 2;
printf("Area = %.2f\n",area);//.f設定小數點後第二位
return 0;
}
```
![](https://i.imgur.com/2khyk0m.png)
### 豆知識
```
想要在 linux 上離開程式請用 Ctrl + C
(Windows 上也可用)
結束輸入使用 Ctrl + Z
```
---
## 10/4 IF?
### IF
```c=
if( condition )
{
statements;
}
```
#### tips
只有0才不會做if後面的程式
if只會執行底下的一個指令,要執行多個指令要用{}包起來
### Equality and Relation Operaters
| in math | in C |
|:-------:|:----:|
| < | < |
| > | > |
| ≤ | <= |
| ≥ | >= |
| = | == |
| ≠ | != |
| ∪ | \|\| |
| ∩ | && |
## 10/9 Bool and Switch
### 三元運算子
(條件) ? (若成立則執行) : (不成立則執行)
### 三元運算子範例
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t a = 0;
int32_t b = 0;
printf("Please enter two integers: ");
scanf("%d%d", &a, &b);
printf( a > b ? "a is greater than b\n" :
"a is not greater than b\n");
return 0;
}
```
### Boolean
Only two possible values: ture false
### Bool範例
```c=
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool a = true;
if ( a )
printf( "true\n" );
else
printf( "false\n");
return 0;
}
```
### Switch 範例
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t a = 1;
switch( a )
{
case 1:
printf( "A\n" );
break;
case 11:
printf( "J\n" );
break;
case 12:
printf( "Q\n" );
break;
case 13:
printf( "K\n" );
break;
default:
printf( "%d\n",a );
}//輸出為A
return 0;
}
```
### Practice answer
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t card_number = 0;
int32_t suit = 0, num = 0;
printf( "Please enter a card number (1-54):" );
scanf( "%d", &card_number );
if( card_number < 1 || card_number > 54 )
{
printf( "Wrong Input!\n" );
return 0;
}
suit = ( card_number - 1 ) / 13;
num = ( card_number - 1 ) % 13 + 1;
switch( suit )
{
case 0:
printf( "Spade " );
break;
case 1:
printf( "Heart ");
break;
case 2:
printf( "Diamond ");
break;
case 3:
printf( "Club ");
break;
case 4:
printf( card_number == 53 ? "BJ\n" : "LJ\n" );
break;
default:
printf( "Unknown\n" );
break;
}
if( card_number <= 52)
switch( num )
{
case 1:
printf( "A\n" );
break;
case 11:
printf( "J\n" );
break;
case 12:
printf( "Q\n" );
break;
case 0:
printf( "K\n" );
break;
default:
printf( "%d\n",num );
break;
}
return 0;
}
```
#### tips
bool 的大小為 1 byte
bool 可以設為 true false 以外的東西(-127~127)
---
<!--我一直以為bool是1bit-->
## 10/16 LOOO...OOOP
### while
```c=
while( condition )
{
statements;
}
```
### for
```c=
for( ; condition ; )
{
statements;
}
```
### 豆知識
lower camel case 駝峰命名法
Example:TotalGrade
i++ use the current value first
++i use the value after ++
---
## 10/18 一堆東西要背的Git
### 開始使用 Git
首先開一個資料夾
$ mkdir hello
並進入該資料夾
$ cd hello
建立一個新的 Repository
$ git init
### 基本指令
#### status
顯示目前Git的狀態:$ git status
#### add
使Git來追蹤我們的檔案:$ git add <檔案>
取消目前追蹤檔案版本:$ git rm --cached
#### commit
將此次追蹤的檔案作註解:
$ git commit
$ git commit -m "輸入此次變更記錄“
修改當前commit文字:
$ git commit --amend
#### log
查看commit的歷史紀錄:
$ git log
$ git log --stat
$ git log -p
#### branch
從主要 branch 再開出一條新的 branch 來做,這支新開的 branch 會帶著原本 branch 目前狀態,
當完成所要開發的新功能或是 bug 修正後確認沒問題就再把它合併回主 branch
開新 branch:
$ git branch <名稱>
列出所有branch:
$ git branch
#### checkout
切換至其他branch:
$ git checkout <名稱>
切換至master branch:
$ git checkout master
#### push
將檔案傳輸至伺服器:
$ git remote add origin <目標伺服器>
$ git push –u origin master
#### pull
至伺服器中將檔案下載回本機更新:
$ git pull --rebase
---
## 10/23 Another Loop
### Do While
```c=
do{
statements;
}while( condition );
```
### 菱形
Author:施衡
```c=
#include <stdio.h>
#include <math.h>
int main(){
int space = 0, star = 0, N = 0;
scanf("%d", &N);
for(int i = 0; i < N; i++){
space = abs(i - N / 2); //abs是絕對值
for(int j = 0; j < space; j++)
printf(" ");
star = N - space * 2;
for(int j = 0; j < star; j++)
printf("*");
}
return 0;
}
```
Author:高仔
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t num=0;
printf("Please enter a odd positive number: ");
scanf("%d",&num);
for(int i = 1 ; i <= num ; i += 2)
{
for(int j = 0 ; j < (num - i) / 2 ; j++)
printf(" ");
for(int j = 0 ; j < i ; j++)
printf("*");
printf("\n");
}
for(int i = num - 2 ; i > 0 ; i -= 2)
{
for(int j = 0 ; j < (num - i) / 2 ; j++)
printf(" ");
for(int j = 0 ; j < i ; j++)
printf("*");
printf("\n");
}
return 0;
}
```
---
## 10/25 Function
### Function Definition
```c=
Return_Value_Type Function_Name ( parameter_list )
{
Statements;
}
```
### Example
```c=
#include <stdio.h>
#include <stdint.h>
int32_t maximum( int32_t x, int32_t y, int32_t z ); // Function Prototype
int main()
{
int32_t number1 = 0;
int32_t number2 = 0;
int32_t number3 = 0;
printf( "Please enter three integers: " );
scanf( "%d %d %d", &number1, &number2, &number3 );
printf( "Max Value is %d\n", maximum( number1, number2, number3 ) );
return 0;
}
// Real Function Definition
int32_t maximum( int32_t x, int32_t y, int32_t z )
{
int32_t max = x;
if( y > max )
max = y;
if( z > max )
max = z;
return max;
}
```
### Practice answer
```c=
#include <stdio.h>
#include <math.h>
double distance(int x1, int y1, int x2, int y2)
{
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
int main()
{
int a, b, c, d;
printf("Please input 4 int number: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
printf("%lf\n", distance(a, b, c, d));
return 0;
}
```
#### tips
Never reinventing whe wheel.
Search brfore you develop
---
## 10/30 Function Call and Header File
### Function Example
```c=
#include <stdio.h>
#include <stdint.h>
void add_one( int32_t x );
int main()
{
int32_t number = 10;
add_one( number );
printf( "Number is %d\n", number ); //輸出為10
return 0;
}
void add_one( int32_t x )
{
x += 1; //x只存活於此函式中
return;
}
```
### 自己搞標頭檔
#### define(mymax.h)
```c=
#ifndef MYMAX_H_INCLUDED
#define MYMAX_H_INCLUDED
//#pragma once //這行等於1 2 10行的效力,以後只寫這行就好(ANSI C 不支援)
#include <stdint.h>
int32_t maximum( int32_t x, int32_t y, int32_t z ); // Function Prototype
#endif // MYMAX_H_INCLUDED
```
#### definition(mymax.c)
```c=
#include "mymax.h"
// Real Function Definition
int32_t maximum( int32_t x, int32_t y, int32_t z )
{
int32_t max = x;
if( y > max )
{
max = y;
}
if( z > max )
{
max = z;
}
return max;
}
```
#### main(main.c)
```c=
// Function example
#include <stdio.h>
#include <stdint.h>
#include "mymax.h"
// Main Function
int main()
{
int32_t number1 = 0;
int32_t number2 = 0;
int32_t number3 = 0;
printf( "Please enter three integers: " );
scanf( "%d %d %d", &number1, &number2, &number3 );
printf( "Max Value is %d\n", maximum( number1, number2, number3 ) );
return 0;
}
```
#### how to use
gcc -c main.c
gcc -c mymax.c
gcc main.o mymax.o
#### Static Link
每個程式都有屬於自己的.o可以用(資本主義)
#### Dynamic Link
每個程式共用一個.o(共產主義)
###### tags: [自己找的參考資料](https://blog.gtwang.org/programming/howto-create-library-using-gcc/)
---
## 11/1 Scope and Stattic
### Scope Example
```c=
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int32_t x = 1; // Global Variable
void get_local_variable( void );
void get_global_variable( void );
int main()
{
printf( "x = %d\n", x ); //輸出1
int32_t x = 5; // Local Variable
printf( "x = %d\n", x ); //輸出5
{
int32_t x = 25; // Local Variable
printf( "x = %d\n", x ); //輸出25
}
get_local_variable(); //輸出100
get_global_variable(); //輸出1
return 0;
}
void get_local_variable( void )
{
int32_t x = 100; // Local Variable
printf( "x = %d\n", x );
return;
}
void get_global_variable( void )
{
printf( "x = %d\n", x );
return;
}
```
### Static Example
```c=
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void get_static_variable( void );
int main()
{
for( int32_t i = 0 ; i < 10 ; i++ )
{
get_static_variable(); //會印出1到10
}
return 0;
}
void get_static_variable( void )
{
static int32_t counter = 0; //雖然依樣一開始就給定記憶體,但是只有在此
//函式中可以使用
counter++;
printf( "counter = %d\n" , counter );
return;
}
```
---
## 11/8 L紀開嗆 NO 上課
---
## 11/13 Recurse & Array
### Example of Recurse
```c=
#include <stdio.h>
#include <stdint.h>
uint64_t power(int32_t x, int32_t y);
int main()
{
int32_t n1 = 0, n2 = 0;
printf("Please enter two number: ");
scanf("%d%d", &n1, &n2);
printf("%d ^ %d = %lu\n", n1, n2, power(n1, n2));
return 0;
}
uint64_t power(int32_t x, int32_t y)
{
if(y == 1)
return x;
return x * power(x, y-1); //呼叫自己
}
```
### Array
Array is a way to store lots of data items of "the same type".
#### how to declare an array
```c=
array_type array_name[ array_size ];
array_type array_name[ array_size ] = { one_element,
one_element ...last_element };
array_type array_name[] = { one_element, one_element ...last_element };
array_type array_name[ array_size ] = { all_same_elements };
```
#### Example
```c=
#include <stdio.h>
#include <stdint.h>
#include <math.h>
int main()
{
int32_t score[10], sum = 0, average = 0;
double ans = 0.0;
printf("Please enter 10 stdents score\n");
for(int i = 0 ; i < 10 ; i++)
{
printf("%d: ", i + 1);
scanf("%d",&score[i]);
sum += score[i];
}
average = sum / 10;
sum = 0;
for(int i = 0 ; i < 10 ; i++)
{
sum += (int)pow(score[i] - average, 2);
}
ans = sqrt(sum / 10);
printf("SD of this ten students is %.2lf\n", ans);
return 0;
}
```
#### tips
陣列是從0開始數 -> int32_t num[20] 的最後一項是 num[19]
---
## 11/20 Define and Sort
### define
define is a preporcessor directive, not a C statement.
```c=
#include <stdio.h>
#include <stdint.h>
#define five 5
int main()
{
int32_t a = five;
printf("%d\n", a); //輸出為5
}
```
### Bubble Sort
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t num[10] = {0}, temp = 0;
printf("Please enter 10 numbers: \n");
for(size_t i = 0 ; i < 10 ; i++)
scanf("%d", &num[i]);
for(size_t i = 0 ; i < 10 ; i++)
{
for(size_t j = i ; j < 10 ; j++)
{
if(num[i] > num[j])
{
temp = num[j];
num[j] = num[i];
num[i] = temp;
}
}
}
for(size_t i = 0 ; i < 10 ; i ++)
printf("%d ", num[i]);
printf("\n");
return 0;
}
```
---
## 11/22 Passing Array to Function
### Exmaple
```c=
#include <stdio.h>
#include <stdint.h>
void print_array(int32_t b[], size_t size);
void print_array_2(int32_t b[6]);
int main()
{
int32_t array[5] = {1, 2, 3, 4, 5};
print_array(array, 5); //輸出為: 1 2 3 4 5
print_array_2(array); //輸出為: 1 2 3 4 5 (某亂數)
return 0;
}
void print_array(int32_t b[], size_t size)
{
for(size_t i = 0 ; i < size ; i++)
printf("%d ", b[i]);
printf("\n");
}
void print_array_2(int32_t b[6])
{
for( size_t i = 0 ; i < 6 ; i++ )
printf( "%d ", b[i] );
printf( "\n" );
}
```
#### tips
將陣列傳至函式裡時,不用設定陣列大小。
---
## 11/27 2D Array
### Declare 2D array
```c=
array_type array_name[ array_row_size ][ array_column_size ]
/*
int32_t a[2][3];
imagine like:
a[0][0] a[0][1] a[0][2] a[0][3]
a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]
real in memory:
a[0][0] a[0][1] a[0][2] a[0][3] a[1][0]... a[2][3]
*/
```
#### tips
Passing a 2D array into a funtion, you must set bounds except the first:
funtion( array[][bounds] )
### 數字龍捲風
```c=
//不斷向右看走法
//editor: 高仔
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t n = 0, dir = 0;
printf("Please enter n(odd): ");
scanf("%d", &n);
if(!(n % 2))
{
printf("Wrong input!\n");
return 0;
}
printf("\n");
int32_t num[n][n], x = n / 2, y = n / 2;
printf("Please fill the %d * %d array(>0): \n", n, n);
for(int i = 0 ; i < n ; i++)
{
for(int j = 0 ; j < n ; j++)
{
scanf("%d", &num[i][j]);
if(num[i][j] <= 0)
{
printf("Wrong input!\n");
return 0;
}
}
]
printf("\nPlease chose your start direct(1 = up, 2 = right, 3 = down, 4 = left): ");
scanf("%d", &dir);
if(dir < 0 || dir > 4)
{
printf("Wrong input!\n");
return 0;
}
printf("\n");
for(int i = 1 ; i <= n * n ; i++)
{
if(i % 10 == 1)
printf("The %dst number is %d\n", i, num[x][y]);
else if(i % 10 == 2)
printf("The %dnd number is %d\n", i, num[x][y]);
else if(i % 10 == 3)
printf("The %drd number is %d\n", i, num[x][y]);
else
printf("The %dth number is %d\n", i, num[x][y]);
num[x][y] = -1;
switch(dir)
{
case 1:
x--;
if(num[x][y+1] != -1)
dir = 2;
break;
case 2:
y++;
if(num[x + 1][y] != -1)
dir = 3;
break;
case 3:
x++;
if(num[x][y - 1] != -1)
dir = 4;
break;
case 4:
y--;
if(num[x - 1][y] != -1)
dir = 1;
break;
}
}
printf("\n");
return 0;
}
```
---
## 11/29 Pointer
指標 = 用來儲存記憶體位址的變數
### Declare a Pointer
```c=
int32_t *pointer_name, *another_pointer_name;
int32_t * pointer_name;
int32_t * pointer_name, i_am_not_a_pointer;
```
### Example
```c=
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t a = 7;
printf( "a's value is %d\n", a ); //輸出為7
printf( "a's address is %p\n", &a ); //輸出為a的位址
printf( "\n" );
int32_t *a_ptr = &a;
printf( "a_ptr's value is %p\n", a_ptr ); //輸出為a的位址
printf( "a_ptr's address is %p\n", &a_ptr ); //輸出為a_ptr的位址
printf( "The value in %p is %d\n", a_ptr, *a_ptr ); //輸出為a的位址, a的值
return 0;
}
```
###### tips: 可以用print("%p", &a)來印出a的記憶體位址
---
## 12/4 ->Pointer<-
### Passing Address to Function
```c=
#include <stdint.h>
#include <stdio.h>
#include <math.h>
int main()
{
double score = 60.0;
curve( &score );
printf("score now is %g\n", score); //輸出為77.4597
}
void curve( double *score )
{
*score = sqrt(*score) * 10;
return;
}
```
#### tips
pointer + 1 會相當於 pointer 前進一個元素,如 int32_t *每次就是前進4個 bytes
而用 void *宣告時則是前進1個 byte
---
## 12/11
### Function Pointer
建立函式指標
```c=
void function(int32_t a);//此為函式
int main(){
void (*func)(int32_t);
//void -> (欲指向的函式輸出格式)
//(*func) 函式指標的名稱
//(int32_t) 所指函式的輸入值
func = function
//指定指標所指位址
}
```
在函式裡使用函式指標
```c=
bool acmp(int32_t a, int32_t b){
if(a > b)
return true;
return false;
}
bool dcmp(int32_t a, int32_t b){
if(a < b)
return true;
return false;
}
void bubblesort(int32_t *a, int32_t *e, bool (*cmp)(int32_t a, int32_t b)){
for(int32_t *i = a; i < e; i++){
for(int32_t *j = i; j < e; j++){
if(cmp(*i, *j)){
*i ^= *j;
*j ^= *i;
*i ^= *j;
}
}
}
}
```
### Memory Management
Malloc向電腦要記憶體
```c=
ptr = malloc(bytes);//bytes = 所需要的空間
memset(ptr, content, size)//將ptr ~ ptr+size-1 初始化為content
```
Calloc向電腦要記憶體(自帶初始化為0)
```c=
ptr = calloc(elements, size)//elements = 元素數, size = 元素大小
```
---
## 12/18
### Double Pointer
pointer of pointer, allocate memory in a function, 2D-array
#### Example
```c=
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
void memory_alloc( int32_t **, size_t );
int main()
{
size_t size = 0;
printf("Please enter an array size: ");
scanf( "%lu", &size );
int32_t *ptr = NULL;
memory_alloc( &ptr, size );
for( size_t i = 0 ; i < size ; i++ )
{
printf( "%4d ", *( ptr + i ) );
if( i % 8 == 7 )
{
printf( "\n" );
}
}
printf("\n");
return 0;
}
void memory_alloc( int32_t **ptr, size_t s )
{
*ptr = calloc( sizeof( int32_t ), s ); // Not 1, why?
for( size_t i = 0 ; i < s ; i++ )
{
*( *ptr + i ) = i;
}
return;
}
```
## 12/20
### char
char = int8_t (Ascii code)
---
## Homework
Sample code will release after due.
### hw1
**Due: 2019.10.13 PM 11:59**
* Problem
{%pdf https://drive.google.com/file/d/13zFPYmojN55Cvfxhy6vFlXZDmYFsK17g/preview %}
* [Sample code](https://hackmd.io/@NTNUCSIE112/rJqM8z0OH)
### hw2
**Due: 2019.10.20 PM 11:59**
* Problem
{%pdf https://drive.google.com/file/d/1-9LCXcnFLJDRegsTImdsoCCxqIkyBAVW/preview %}
* [Sample code](https://hackmd.io/@NTNUCSIE112/SyEaTYaKr)
### hw3
**Due: 2019.11.03 PM 11:59**
* Problem
{%pdf https://drive.google.com/file/d/1-9LCXcnFLJDRegsTImdsoCCxqIkyBAVW/preview %}
* [Sample code](https://hackmd.io/@NTNUCSIE112/B1aWdHN9H)
### Midterm Exam
* Problem
{%pdf https://drive.google.com/file/d/11_f_lUthrnPrDIJ7oQKyT9l_ddPKy0ui/preview %}
* [Sample code](https://hackmd.io/@joseph89108/ByfFg_ehB)
### hw04
**Due: 2019.12.01 PM 11:59**
* Problem
{%pdf https://drive.google.com/file/d/1LIQSs2DOVmc2SgMCmM2cy-5lWrCT8SPb/preview %}
* [Sample code](https://hackmd.io/@joseph89108/H1gQfLx3S)
### hw05
**Due: 2019.12.15 PM 11:59**
* Problem
{%pdf https://drive.google.com/file/d/1OsW6WiukyxY4jLmvfDwz8X8LssNlNT6M/preview %}
* [Sample code](https://hackmd.io/@joseph89108/rkXQ9m8RS)
### hw06
**Due: 2020.01.05 PM 11:59**
* Problem
{%pdf https://drive.google.com/file/d/1JpyXOZzqIURI-XZ2Ch8D2uq-AeZz_Fnb/preview %}
* [hw06.zip](https://drive.google.com/file/d/125zLpRIVN2OahyqayVGpAkCXLuCyBpJp/view)
* [Sample code](https://hackmd.io/@joseph89108/rJepBF_eI)
### Final Exam
* Problem
{%pdf https://drive.google.com/file/d/1gzrNqLEYqPc5L9xSyVEpdfi0Ed1uz19E/preview %}
* [final.zip](https://drive.google.com/file/d/1xio2-krLW4eNnBhy2vxmLApkD1fnEvZm/view)
* [Sample code](https://hackmd.io/@joseph89108/SkIELK_x8)
<!--
404圖片
https://img.technews.tw/wp-content/uploads/2017/12/05190138/PIXAR-404-Error.jpg
小恐龍
https://st4.depositphotos.com/4967103/22006/v/1600/depositphotos_220068430-stock-illustration-404-error-found-tee-print.jpg
奇怪的人
https://cdn.discordapp.com/attachments/512005304008048667/637108652762726402/tenor.gif
-->
*[iterate]:迴圈
*[recurse]:遞迴