C++ 101

C++ 基礎

執行方式

編譯與執行(1)

編譯後,執行

            
            g++ main.cpp && ./a.out
            
        

編譯與執行(2)

編譯後,執行並導入測資

            
            g++ main.cpp && ./a.out < d1.txt
            
        

常用名稱

C++

  • bits/stdc++.h: 全標準函式庫
  • namespace: 命名空間。不同的命名空間,可以設定相同的變數或函式名稱
  • iostream: 輸出入函式庫
  • iomanip: 格式設定函式庫
  • string: 字串函式庫
  • cmath: 數學函式庫
  • cin: 從「標準輸入裝置」,例如鍵盤或檔案,取得數據,存入變數
  • cout: 將訊息或數據,送到「標準輸出裝置」顯示,例如螢幕
  • endl: 輸出換行

C語言

  • stdio.h: 輸出入函式庫
  • stdlib.h: 標準函式庫
  • string.h: 字串函式庫
  • math.h: 數學函式庫
  • scanf(): 輸入函式
  • printf(): 輸出函式

通用

  • main(): 主函式。程式執行進入點(Entry Point)
  • return: 回傳
  • \n: 通用換行字元

Output(輸出)

輸出字串

            
            #include <iostream>
            using namespace std;

            int main() {
                cout << "Hello, World!" << endl;
                return 0;
            }
            
        

輸出字串(C)

            
            #include <stdio.h>

            int main() {
                printf("Hello, World!\n");
                return 0;
            }
            
        

輸出整數

            
            #include <iostream>
            using namespace std;

            int main() {
                int a = 7;
                int b = 2;

                cout << a + b << endl;
                return 0;
            }
            
        

輸出整數(C)

            
            #include <stdio.h>

            int main() {
                int a = 7;
                int b = 2;

                printf("%d\n", a + b);
                return 0;
            }
            
        

輸出浮點數(保留小數位數)

            
            #include <iostream>
            #include <iomanip>
            using namespace std;

            int main() {
                double pi = 3.14159;

                cout << fixed << setprecision(4);
                cout << pi << endl;
                return 0;
            }
            
        

輸出浮點數(C)

            
            #include <stdio.h>

            int main() {
                double pi = 3.14159;

                printf("%.4f\n", pi);
                return 0;
            }
            
        

Input(輸入)

整數相加

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                cout << "a: ";
                cin >> a;
                cout << "b: ";
                cin >> b;
                cout << "Sum: " << a+b << endl;
                return 0;
            }
            
        

整數相加(C)

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                printf("a: ");
                scanf("%d", &a);
                printf("b: ");
                scanf("%d", &b);
                printf("Sum: %d\n", a+b);
                return 0;
            }
            
        

整數相加解題

讀取解題測資,不設任何輸入提示訊息

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                cin >> a >> b;
                cout << "Sum: " << a+b << endl;
                return 0;
            }
            
        

整數相加解題(C)

讀取解題測資,不設任何輸入提示訊息

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                scanf("%d %d", &a, &b);
                printf("Sum: %d\n", a+b);
                return 0;
            }
            
        

浮點數相乘(圓周長)

            
            #include <iostream>
            #include <iomanip>
            using namespace std;

            int main() {
                double pi = 3.14159;
                double r;

                cout << "Radius: ";
                cin >> r;
                cout << fixed << setprecision(2);
                cout << "Perimeter: " << 2*r*pi << endl;
                return 0;
            }
            
        

浮點數相乘解題(圓周長)

讀取解題測資,不設任何輸入提示訊息

            
            #include <iostream>
            #include <iomanip>
            using namespace std;

            int main() {
                double pi = 3.14159;
                double r;

                cin >> r;
                cout << fixed << setprecision(2);
                cout << "Perimeter: " << 2*r*pi << endl;
                return 0;
            }
            
        

浮點數相乘(C)

            
            #include <iostream>
            using namespace std;

            int main() {
                double pi = 3.14159;
                double r;

                printf("Radius: ");
                scanf("%lf", &r);
                printf("Perimeter: %.2f\n", 2*r*pi);
                return 0;
            }
            
        

字元與整數(等級與分數)

字串以雙引號 "abcde" 括住,字元以單引號 'a' 括住

            
            #include <iostream>
            #include <cctype>
            using namespace std;

            int main() {
                char grade;
                int score;

                cout << "Grade: ";
                cin >> grade;
                cout << "Score: ";
                cin >> score;
                grade = toupper(grade);
                cout << grade << " " << score << endl;
                return 0;
            }
            
        

字元與整數(C)

字串以雙引號 "abcde" 括住,字元以單引號 'a' 括住

            
            #include <stdio.h>
            #include <ctype.h>

            int main() {
                char grade;
                int score;

                printf("Grade: ");
                scanf("%c", &grade);
                printf("Score: ");
                scanf("%d", &score);
                grade = toupper(grade);
                printf("%c %d\n", grade, score);
                return 0;
            }
            
        

字串與整數(名字與年齡)

  • C++可用字串類別存字串
  • 字串以雙引號 "abcde" 括住,字元以單引號 'a' 括住
            
            #include <iostream>
            using namespace std;

            int main() {
                string name;
                int age;

                cout << "What is your name? ";
                cin >> name;
                cout << "How old are you? ";
                cin >> age;
                cout << "Name: " << name << endl;
                cout << "Age: " << age << endl;
                return 0;
            }
            
        

字串與整數(C)

  • C語言使用字元陣列存字串
  • 字串以雙引號 "abcde" 括住,字元以單引號 'a' 括住
  • 一個字元陣列,可以存多個字元
  • 字元陣列取址不加 & 符號
            
            #include <stdio.h>

            int main() {
                char name[10];
                int age;

                printf("What is your name? ");
                scanf("%s", name);
                printf("How old are you? ");
                scanf("%d", &age);
                printf("Name: %s\n", name);
                printf("Age: %d\n", age);
                return 0;
            }
            
        

Math(計算)

算術運算子
  • +: 加法
  • -: 減法
  • *: 乘法
  • /: 浮點數除法,其中一個運算元是浮點數
  • /: 商數除法,兩個運算元都是整數
  • %: 餘數除法

整數加減乘除

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                cout << "a: ";
                cin >> a;
                cout << "b: ";
                cin >> b;
                cout << endl;
                cout << a << " + " << b << " = " << a + b << endl;
                cout << a << " - " << b << " = " << a - b << endl;
                cout << a << " * " << b << " = " << a * b << endl;
                cout << endl;
                cout << a << " / " << b << " = " << (double)a / b << endl;
                cout << a << " / " << b << " = " << a / (double)b << endl;
                cout << a << " / " << b << " = " << a / b << endl;
                cout << a << " % " << b << " = " << a % b << endl;
                return 0;
            }
            
        

整數加減乘除(C)

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                printf("a: ");
                scanf("%d", &a);
                printf("b: ");
                scanf("%d", &b);
                printf("\n");
                printf("%d + %d = %d\n", a, b, a + b);
                printf("%d - %d = %d\n", a, b, a - b);
                printf("%d * %d = %d\n", a, b, a * b);
                printf("\n");
                printf("%d / %d = %f\n", a, b, (double)a / b);
                printf("%d / %d = %f\n", a, b, a / (double)b);
                printf("%d / %d = %d\n", a, b, a / b);
                printf("%d %% %d = %d\n", a, b, a % b);
                return 0;
            }
            
        

絕對值

            
            #include <iostream>
            using namespace std;

            int main() {
                int n;

                cout << "n: ";
                cin >> n;
                cout << "abs(n) = " << abs(n) << endl;
                return 0;
            }
            
        

絕對值(C)

            
            #include <stdio.h>
            #include <stdlib.h>

            int main() {
                int n;

                printf("n: ");
                scanf("%d", &n);
                printf("abs(n) = %d\n", abs(n));
                return 0;
            }
            
        

和差問題(bee1013)

            
            #include <iostream>
            using namespace std;

            int main() {
                int sum = 10;
                int diff = 4;
                int large, small;

                large = (sum + diff) / 2;
                small = (sum - diff) / 2;
                cout << "Large number: " << large << endl;
                cout << "Small number: " << small << endl;
                return 0;
            }
            
        

和差問題(C)

            
            #include <stdio.h>

            int main() {
                int sum = 10;
                int diff = 4;
                int large, small;

                large = (sum + diff) / 2;
                small = (sum - diff) / 2;
                printf("Large number: %d\n", large);
                printf("Small number: %d\n", small);
                return 0;
            }
            
        

平方與平方根(bee1015)

            
            #include <iostream>
            #include <cmath>
            using namespace std;

            int main() {
                int x;

                cout << "x: ";
                cin >> x;
                x = pow(x, 2);
                cout << x << endl;
                x = sqrt(x);
                cout << x << endl;
                return 0;
            }
            
        

平方和平方根(C)

            
            #include <stdio.h>
            #include <math.h>
            using namespace std;

            int main() {
                int x;

                printf("x: ");
                scanf("%d", &x);
                x = pow(x, 2);
                printf("%d\n", x);
                x = sqrt(x);
                printf("%d\n", x);
                return 0;
            }
            
        

個位與十位(bee1018)

            
            #include <iostream>
            using namespace std;

            int main() {
                int n;

                cout << "n: ";
                cin >> n;
                cout << "units digit: " << n % 10 << endl;
                cout << " tens digit: " << n / 10 << endl;
                return 0;
            }
            
        

個位與十位(C)

            
            #include <stdio.h>
            using namespace std;

            int main() {
                int n;

                printf("n: ");
                scanf("%d", &n);
                printf("units digit: %d\n", n % 10);
                printf(" tens digit: %d\n", n / 10);
                return 0;
            }
            
        

位元運算

  • &  (AND)
  • |  (OR)
  • ^  (XOR)
  • << (左移)
  • >> (右移)
            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                cout << "a: ";
                cin >> a;
                cout << "b: ";
                cin >> b;
                cout << (a & b) << endl;
                cout << (a | b) << endl;
                cout << (a ^ b) << endl;
                cout << (a << b) << endl;
                cout << (a >> b) << endl;
                return 0;
            }
            
        

位元運算(C)

            
            #include <stdio.h>
            using namespace std;

            int main() {
                int a, b;

                printf("a: ");
                scanf("%d", &a);
                printf("b: ");
                scanf("%d", &b);
                cout << (a & b) << endl;
                cout << (a | b) << endl;
                cout << (a ^ b) << endl;
                cout << (a << b) << endl;
                cout << (a >> b)<< endl;
                return 0;
            }
            
        

進位制基底與位數範圍

  • 10進位(Dec): 0123456789
  •  2進位(Bin): 01
  •  8進位(Oct): 01234567
  • 16進位(Hex): 0123456789abcdef (a~f 依序表示 10~15)

各種進位值

            
            #include <iostream>
            using namespace std;

            int main() {
                int n = 987;

                cout << "Dec: " << n << endl;
                cout << "Oct: " << oct << n << endl;
                cout << "Hex: " << hex << n << endl;
                cout << showbase;
                cout << "Oct: " << oct << n << endl;
                cout << "Hex: " << hex << n << endl;
                return 0;
            }
            
        

各種進位值(C)

            
            #include <stdio.h>

            int main() {
                int n = 987;

                printf("Dec: %d\n", n);
                printf("Oct: %o\n", n);
                printf("Hex: %x\n", n);
                return 0;
            }
            
        

運算子優先序

#運算子
1 ()
2 +(正號), -(負號), ++(遞增), --(遞減), !(NOT), ~(位元NOT), sizeof(取得記憶體空間大小), (強制轉型)
3 *(乘法), /(除法、商數), %(餘數)
4 +(加法), -(減法)
5 <<(位元左移), >>(位元右移)
6 >(大於), <(小於), >=(大於等於), <=(小於等於)
7 ==(是否相等), !=(是否不相等)
8 &(位元AND)
9 ^(位元XOR)
10 |(位元OR)
11 &&(條件AND)
12 ||(條件OR)
13 =, +=, -=, *=, /=, %=

Variable(變數)

變數最大值

            
            #include <iostream>
            #include <climits>
            #include <cfloat>
            using namespace std;

            int main() {
                char   i1 = CHAR_MAX;
                short  i2 = SHRT_MAX;
                int    i4 = INT_MAX;
                long   i8 = LONG_MAX;
                float  f4 = FLT_MAX;
                double f8 = DBL_MAX;

                cout << "  char : " << (int)i1 << endl;
                cout << " short : " << i2 << endl;
                cout << "   int : " << i4 << endl;
                cout << "  long : " << i8 << endl;
                cout << " float : " << f4 << endl;
                cout << "double : " << f8 << endl;
                return 0;
            }
            
        

INT整數上下限

            
            #include <iostream>
            #include <cmath>
            #include <climits>
            using namespace std;

            int main() {
                int bytes = sizeof(int);
                int bits = bytes * 8;

                cout << bytes << " bytes" << endl;
                cout << bits << " bits" << endl;
                cout << INT_MIN << " ~ " << INT_MAX << endl;
                cout << -(int)(pow(2, bits)) << " ~ " << INT_MAX << endl;
                cout << INT_MIN << " ~ " << (int)(pow(2, bits))-1 << endl;
                return 0;
            }
            
        

各種整數型別(整數範圍)

Type Size Range
char (CHAR) 1 byte -128 ~ 127
short (SHRT) 2 bytes -32768 ~ 32767
int (INT) 4 bytes -2147483648 ~ 2147483647
long (LONG) 8 bytes -9223372036854775808 ~ 9223372036854775807
unsigned char (UCHAR) 1 byte 0 ~ 255
unsigned short (USHRT) 2 bytes 0 ~ 65535
unsigned int (UINT) 4 bytes 0 ~ 4294967295
unsigned long (ULONG) 8 bytes 0 ~ 18446744073709551615

整數字元互轉

凱撒加解密字母

            
            #include <iostream>
            using namespace std;

            int main() {
                int i = 65;
                char c = 'A';

                cout << i << endl;
                cout << c << endl;
                cout << (char)i << endl;
                cout << (char)(i+1) << endl;
                cout << (int)c << endl;
                cout << (int)(c+1) << endl;
                return 0;
            }
            
        

整數字元互轉(C)

            
            #include <stdio.h>

            int main() {
                int i = 65;
                char c = 'A';

                printf("%d\n", i);
                printf("%c\n", c);
                printf("%c\n", (char)i);
                printf("%c\n", (char)(i+1));
                printf("%d\n", (int)c);
                printf("%d\n", (int)(c+1));
                return 0;
            }
            
        

兩數對調(交換)

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b, t;

                cout << "Enter 2 numbers: ";
                cin >> a >> b;
                t = a;
                a = b;
                b = t;
                cout << a << ' ' << b << endl;
                return 0;
            }
            
        

兩數對調(C)

            
            #include <stdio.h>

            int main() {
                int a, b, t;

                printf("Enter 2 numbers: ");
                scanf("%d %d", &a, &b);
                t = a;
                a = b;
                b = t;
                printf("%d %d\n", a, b);
                return 0;
            }
            
        

兩數相除

            
            #include <iostream>
            #include <iomanip>
            using namespace std;

            int main() {
                int    dividend = 19;
                int    divisor1 = 3;
                double divisor2 = 6.0;
                double answer;

                answer = dividend / divisor1;
                cout << "answer1: " << answer << endl;

                answer = dividend / divisor2;
                cout << "answer2: " << answer << endl;

                answer = (double)dividend / divisor1;
                cout << "answer3: " << answer << endl;

                return 0;
            }
            
        

兩數相除(C)

            
            #include <stdio.h>

            int main() {
                int    dividend = 19;
                int    divisor1 = 3;
                double divisor2 = 6.0;
                double answer;

                answer = dividend / divisor1;
                printf("answer1: %f\n", answer);

                answer = dividend / divisor2;
                printf("answer2: %f\n", answer);

                answer = (double)dividend / divisor1;
                printf("answer3: %f\n", answer);

                return 0;
            }
            
        

變數值與位址

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b, c;

                cout << "Enter 3 numbers: ";
                cin >> a >> b >> c;
                cout << a << ' ' << &a << endl;
                cout << b << ' ' << &b << endl;
                cout << c << ' ' << &c << endl;
                return 0;
            }
            
        

變數值與位址(C)

            
            #include <stdio.h>
            using namespace std;

            int main() {
                int a, b, c;

                printf("Enter 3 numbers: ");
                scanf("%d %d %d", &a, &b, &c);
                printf("%d %p\n", a, &a);
                printf("%d %p\n", b, &b);
                printf("%d %p\n", c, &c);
                return 0;
            }
            
        

變數命名法(Camel Case)

兩個以上單字,第一個單字全小寫,第二個以上單字首字母大寫

            
            #include <iostream>
            using namespace std;

            int main() {
                string yourName;
                string yourBestFriend;

                cout << "What is your name? ";
                cin >> yourName;
                cout << "Who is your best friend? ";
                cin >> yourBestFriend;
                cout << yourName << " & " << yourBestFriend << endl;
                return 0;
            }
            
        

變數命名法(C)

            
            #include <stdio.h>

            int main() {
                char yourName[10];
                char yourBestFriend[10];

                printf("What is your name? ");
                scanf("%s", yourName);
                printf("Who is your best friend? ");
                scanf("%s", yourBestFriend);
                printf("%s & %s\n", yourName, yourBestFriend);
                return 0;
            }
            
        

Selection(選擇) - 選擇式(分支或選擇結構)

比較運算子

  • ==: 是否相等
  • !=: 是否不相等
  •  >: 大於
  • >=: 大於等於
  •  <: 小於
  • <=: 小於等於
  • 4種 if 區段結構

    • (1) if
    • (2) if-else
    • (3) if-else if... (可以有多個 else if,都必須接條件式)
    • (4) if-else if...else

    if條件式

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    string weather;
    
                    cout << "Beebo: Let's hang out." << endl;
                    cout << "How is the weather? ";
                    cin >> weather;
    
                    if (weather == "sunny") {
                        cout << "Sure. Why not?" << endl;
                    }
                    return 0;
                }
                
            

    if條件式(C)

                
                #include <stdio.h>
                #include <string.h>
    
                int main() {
                    char weather[10];
    
                    printf("Beebo: Let's hang out.\n");
                    printf("How is the weather? ");
                    scanf("%s", weather);
    
                    if (strcmp(weather, "sunny") == 0) {
                        printf("Sure. Why not?\n");
                    }
                    return 0;
                }
                
            

    if-else條件否則式

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    string weather;
    
                    cout << "Beebo: Let's hang out." << endl;
                    cout << "How is the weather? ";
                    cin >> weather;
    
                    if (weather == "sunny") {
                        cout << "Sure. Why not?" << endl;
                    }
                    else {
                        cout << "I want to stay home." << endl;
                    }
                    return 0;
                }
                
            

    if-else條件否則式(C)

                
                #include <stdio.h>
                #include <string.h>
    
                int main() {
                    char weather[10];
    
                    printf("Beebo: Let's hang out.\n");
                    printf("How is the weather? ");
                    scanf("%s", weather);
    
                    if (strcmp(weather, "sunny") == 0) {
                        printf("Sure. Why not?\n");
                    }
                    else {
                        printf("I want to stay home.\n");
                    }
                    return 0;
                }
                
            

    三數最大值

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int a, b, c;
                    int max;
    
                    cout << "Enter 3 numbers: ";
                    cin >> a >> b >> c;
                    max = a;
                    if (max < b) {
                        max = b;
                    }
                    if (max < c) {
                        max = c;
                    }
                    cout << max << endl;
                    return 0;
                }
                
            

    三數最大值(C)

                
                #include <stdio.h>
    
                int main() {
                    int a, b, c;
                    int max;
    
                    printf("Enter 3 numbers: ");
                    scanf("%d %d %d", &a, &b, &c);
                    max = a;
                    if (max < b) {
                        max = b;
                    }
                    if (max < c) {
                        max = c;
                    }
                    printf("%d\n", max);
                    return 0;
                }
                
            

    三元運算子

    條件式 ? 條件成立的運算式 : 不成立的運算式

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int a, b, c;
                    int max;
    
                    cout << "Enter 3 numbers: ";
                    cin >> a >> b >> c;
                    max = (a > b) ? a : b;
                    max = (max > c) ? max : c;
                    cout << max << endl;
                    return 0;
                }
                
            

    三元運算子(C)

    條件式 ? 條件成立的運算式 : 不成立的運算式

                
                #include <stdio.h>
    
                int main() {
                    int a, b, c;
                    int max;
    
                    printf("Enter 3 numbers: ");
                    scanf("%d %d %d", &a, &b, &c);
                    max = (a > b) ? a : b;
                    max = (max > c) ? max : c;
                    printf("%d\n", max);
                    return 0;
                }
                
            

    條件與範圍(成績平均績點)

    移除多餘條件

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int score;
    
                    cout << "Your score: ";
                    cin >> score;
    
                    if (score >= 80) {
                        cout << "A, GPA is 4";
                    }
                    else if (score < 80 && score >= 70) {
                        cout << "B, GPA is 3";
                    }
                    else if (score < 70 && score >= 60) {
                        cout << "C, GPA is 2";
                    }
                    else if (score < 60 && score >= 50) {
                        cout << "D, GPA is 1";
                    }
                    else {
                        cout << "F, GPA is 0";
                    }
                    cout << endl;
                    return 0;
                }
                
            

    條件與範圍(C)

                
                #include <stdio.h>
    
                int main() {
                    int score;
    
                    printf("Your score: ");
                    scanf("%d", &score);
    
                    if (score >= 80) {
                        printf("A, GPA is 4\n");
                    }
                    else if (score < 80 && score >= 70) {
                        printf("B, GPA is 3\n");
                    }
                    else if (score < 70 && score >= 60) {
                        printf("C, GPA is 2\n");
                    }
                    else if (score < 60 && score >= 50) {
                        printf("D, GPA is 1\n");
                    }
                    else {
                        printf("F, GPA is 0\n");
                    }
                    return 0;
                }
                
            

    讀取一行問題

    • 輸入單字後,立即按 [Enter]
    • 輸入單字,接著空白,再按 [Enter]
                
                #include <iostream>
                using namespace std;
    
                int main() {
                    string word;
                    string line;
    
                    cin >> word;
                    cout << word << endl;
                    // cin.ignore();
                    // cin.ignore(256, '\n');
                    getline(cin, line);
                    cout << line << endl;
    
                    return 0;
                }
                
            

    購買票券

    • toupper(): 將字元轉成大寫
    • tolower(): 將字元轉成小寫
                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int price;
                    int tickets;
                    char creditCard;
                    int total;
                    int isCard;
    
                    cout << "Price? ";
                    cin >> price;
                    cout << "Tickets? ";
                    cin >> tickets;
                    cout << "Credit Card? (Y/n): ";
                    cin >> creditCard;
    
                    creditCard = toupper(creditCard);
                    isCard = (creditCard == 'Y');
                    total = isCard ? price*tickets*0.9 : price*tickets;
                    cout << "Total: $" << total << endl;
                    return 0;
                }
                
            

    購買票券(C)

                
                #include <stdio.h>
                #include <ctype.h>
    
                int main() {
                    int price;
                    int tickets;
                    char creditCard;
                    int total;
                    int isCard;
    
                    printf("Price? ");
                    scanf("%d", &price);
                    printf("Tickets? ");
                    scanf("%d", &tickets);
                    printf("Credit Card? (Y/n): ");
                    scanf(" %c", &creditCard);
    
                    creditCard = toupper(creditCard);
                    isCard = (creditCard == 'Y');
                    total = isCard ? price*tickets*0.9 : price*tickets;
                    printf("Total: $%d\n", total);
                    return 0;
                }
                
            

    兩層巢狀選擇(動物連連看)

    先判斷 small 再判斷 furry

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    bool isFurry = true;
                    bool isSmall = true;
    
                    if (isFurry) {
                        if (isSmall)
                            cout << "Cat";
                        else
                            cout << "Bear";
                    }
                    else {
                        if (isSmall)
                            cout << "Gecko";
                        else
                            cout << "Crocodile";
                    }
                    cout << endl;
                    return 0;
                }
                
            

    兩層巢狀選擇(C)

                
                #include <stdio.h>
                #include <stdbool.h>
    
                int main() {
                    bool isFurry = true;
                    bool isSmall = true;
    
                    if (isFurry) {
                        if (isSmall)
                            printf("Cat\n");
                        else
                            printf("Bear\n");
                    }
                    else {
                        if (isSmall)
                            printf("Gecko\n");
                        else
                            printf("Crocodile\n");
                    }
                    return 0;
                }
                
            

    三層巢狀選擇(三個孩子)

    • toupper(): 字母字元轉大寫
    • tolower(): 字母字元轉小寫
    • 增加第三個孩子的性別判斷
    • 在 Son 及 Daughter 後面,箭頭後方設定英文名字
    • 英文名字不可重複命名
                
                #include <iostream>
                using namespace std;
    
                int main() {
                    char firstBorn;
                    char secondBorn;
                    char thirdBorn;
    
                    cin >> firstBorn >> secondBorn >> thirdBorn;
                    firstBorn  = toupper(firstBorn);
                    secondBorn = toupper(secondBorn);
                    thirdBorn  = toupper(thirdBorn);
    
                    if (firstBorn == 'M') {
                        cout << "1st child: Son -> Aaron" << endl;
                        if (secondBorn == 'M')
                            cout << "2nd child: Son" << endl;
                        else
                            cout << "2nd child: Daughter" << endl;
                    }
                    else {
                        cout << "1st child: Daughter -> Bella" << endl;
                        if (secondBorn == 'M')
                            cout << "2nd child: Son" << endl;
                        else
                            cout << "2nd child: Daughter" << endl;
                    }
                    return 0;
                }
                
            

    switch結構(五則運算)

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int x, y;
                    char op;
    
                    cout << "x: ";
                    cin >> x;
                    cout << "y: ";
                    cin >> y;
                    cout << "Choose an operation (+ - * / %): ";
                    cin >> op;
    
                    switch(op) {
                        case '+': cout << x + y << endl;
                                  break;
                        case '-': cout << x - y << endl;
                                  break;
                        case '*': cout << x * y << endl;
                                  break;
                        case '/': cout << x / y << endl;
                                  break;
                        case '%': cout << x % y << endl;
                                  break;
                        default: cout << "Wrong operation!" << endl;
                    }
                    return 0;
                }
                
            

    switch結構(C)

                
                #include <stdio.h>
    
                int main() {
                    int x, y;
                    char op;
    
                    printf("x: ");
                    scanf("%d", &x);
                    printf("y: ");
                    scanf("%d", &y);
                    printf("Choose an operation (+ - * / %%): ");
                    scanf(" %c", &op);
    
                    switch(op) {
                        case '+': printf("%d\n", x + y);
                                  break;
                        case '-': printf("%d\n", x - y);
                                  break;
                        case '*': printf("%d\n", x * y);
                                  break;
                        case '/': printf("%d\n", x / y);
                                  break;
                        case '%': printf("%d\n", x % y);
                                  break;
                        default: printf("Wrong operation!\n");
                    }
                    return 0;
                }
                
            

    分階傳訊

    讀取一行字串

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    string msg;
                    int level;
    
                    cout << "Message: ";
                    getline(cin, msg);
                    cout << "Level (1 to 9): ";
                    cin >> level;
    
                    switch(level) {
                        case 1: cout << "Send \"" << msg << "\" to level 1\n";
                        case 2: cout << "Send \"" << msg << "\" to level 2\n";
                        case 3: cout << "Send \"" << msg << "\" to level 3\n";
                        case 4: cout << "Send \"" << msg << "\" to level 4\n";
                        case 5: cout << "Send \"" << msg << "\" to level 5\n";
                        case 6: cout << "Send \"" << msg << "\" to level 6\n";
                        case 7: cout << "Send \"" << msg << "\" to level 7\n";
                        case 8: cout << "Send \"" << msg << "\" to level 8\n";
                        case 9: cout << "Send \"" << msg << "\" to level 9\n"; break;
                        default: cout << "Wrong level!\n";
                    }
                    return 0;
                }
                
            

    分階傳訊(C)

                
                #include <stdio.h>
    
                int main() {
                    char msg[100];
                    int level;
    
                    printf("Message: ");
                    scanf("%[^\n]", msg);
                    printf("Level (1 to 9): ");
                    scanf("%d", &level);
    
                    switch(level) {
                        case 1: printf("Send \"%s\" to level %d\n", msg, 1);
                        case 2: printf("Send \"%s\" to level %d\n", msg, 2);
                        case 3: printf("Send \"%s\" to level %d\n", msg, 3);
                        case 4: printf("Send \"%s\" to level %d\n", msg, 4);
                        case 5: printf("Send \"%s\" to level %d\n", msg, 5);
                        case 6: printf("Send \"%s\" to level %d\n", msg, 6);
                        case 7: printf("Send \"%s\" to level %d\n", msg, 7);
                        case 8: printf("Send \"%s\" to level %d\n", msg, 8);
                        case 9: printf("Send \"%s\" to level %d\n", msg, 9); break;
                        default: printf("Wrong level!\n");
                    }
                    return 0;
                }
                
            

    成績與評語

    使用 switch-case 語法改寫

                
                #include <iostream>
                #include <cctype>
                using namespace std;
    
                int main() {
                    char grade;
    
                    cout << "Grade: ";
                    cin >> grade;
                    grade = toupper(grade);
                    if (grade == 'A') {
                        cout << "Excellent!";
                    }
                    else if (grade == 'B') {
                        cout << "Good!";
                    }
                    else if (grade == 'C' || grade == 'D') {
                        cout << "Poor!";
                    }
                    else if (grade == 'F') {
                        cout << "Egregious!";
                    }
                    else {
                        cout << "Invalid grade!";
                    }
                    cout << endl;
                    return 0;
                }
                
            

    Repetition(重複) - for loop迴圈式(迴圈或重複結構)

    for迴圈流程

    for (1.迴圈變數預設初值; 2.迴圈可執行條件; 4.迴圈變數遞增遞減) {
        3.迴圈功能程式
    }
    1->2->3->4->2->3->4...直到 2 的條件不成立
    註: 1 只執行一次

    迴圈輸出整數

    等差數列、等比數列

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int i;
    
                    for (i = 0; i < 10; i += 1) {
                        cout << i << endl;
                    }
                    return 0;
                }
                
            

    迴圈輸出星號

    連續依序輸出三種符號,例如 @#$@#$...

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int i;
    
                    for (i = 0; i < 10; i += 1) {
                        cout << '*';
                    }
                    cout << endl;
                    return 0;
                }
                
            

    數的兩倍

    • ++: 整數變數遞增,每次 +1
    • --: 整數變數遞減,每次 -1
                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int i;
    
                    for (i = 1; i < 10; i++) {
                        cout << "i: " << i << endl;
                        i = i * 2;
                        cout << "Double of i: " << i << endl;
                    }
                    return 0;
                }
                
            

    大寫小寫

    凱撒加解密單句

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    char upper = 'A';
                    char lower = 'a';
                    int i;
    
                    for (i = 0; i < 26; i += 1) {
                        cout << (char)(upper+i) << ' ';
                    }
                    cout << endl;
    
                    for (i = 0; i < 26; i += 1) {
                        cout << (char)(lower+i) << ' ';
                    }
                    cout << endl;
                    return 0;
                }
                
            

    整數倒數

    等差數列、等比數列

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n = 0;
                    int i = 0;
    
                    cout << "n: ";
                    cin >> n;
                    for (i = n; i >= 1; i -= 1) {
                        cout << i << endl;
                    }
                    return 0;
                }
                
            

    巢狀for迴圈(四季與月份)

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int q, m;
    
                    for (q = 1; q <= 4; q++) {
                        cout << "Q: " << q << endl;
                        for (m = 1; m <= 3; m++) {
                            cout << "    M: " << m + (q-1) * 3 << endl;
                        }
                    }
                    return 0;
                }
                
            

    九九乘法表

                
                #include <iostream>
                #include <iomanip>
                using namespace std;
    
                int main() {
                    int i, j;
    
                    for (i = 1; i <= 9; i++) {
                        for (j = 1; j <= 9; j++) {
                            cout << setw(4) << i*j;
                        }
                        cout << endl;
                    }
                    return 0;
                }
                
            

    數列三角

    各式數列三角

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n = 0;
                    int i = 0, j = 0;
    
                    cout << "n: ";
                    cin >> n;
                    for (i = 1; i <= n; i++) {
                        for (j = 1; j <= i; j++) {
                            cout << j << ' ';
                        }
                        cout << endl;
                    }
                    return 0;
                }
                
            

    星號三角

    正左直角、倒左直角、正右直角、倒右直角、金字塔形、奇數菱形、三角沙漏

                
                /*
    
                # 正左直角
                i *
                1 1 *
                2 2 **
                3 3 ***
                4 4 ****
                5 5 *****
    
                # 倒左直角
                i *
                1 5 *****
                2 4 ****
                3 3 ***
                4 2 **
                5 1 *
    
                # 正右直角
                i . *
                1 4 1     *
                2 3 2    **
                3 2 3   ***
                4 1 4  ****
                5 0 5 *****
    
                # 倒右直角
                i . *
                1 0 5 *****
                2 1 4  ****
                3 2 3   ***
                4 3 2    **
                5 4 1     *
    
                # 金字塔形
                i . *
                1 4 1     *
                2 3 3    ***
                3 2 5   *****
                4 1 7  *******
                5 0 9 *********
    
                # 奇數菱形
                i . *
                1 2 1   *
                2 1 3  ***
                3 0 5 *****
                4 1 3  ***
                5 2 1   *
    
                # 三角沙漏
                i . *
                1 0 5 *****
                2 1 3  ***
                3 2 1   *
                4 1 3  ***
                5 0 5 *****
    
                */
    
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n = 0;
                    int i = 0, j = 0;
    
                    cout << "n: ";
                    cin >> n;
                    for (i = 1; i <= n; i++) {
                        for (j = 1; j <= i; j++) {
                            cout << '*';
                        }
                        cout << endl;
                    }
                    return 0;
                }
                
            

    二維轉一維

  • ri (row index): 列索引編號
  • ci (col index): 欄索引編號
  • col 原字 column
  •             
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n;
                    int ri, ci, i;
    
                    cout << "2D index -> 1D index" << endl;
                    cout << "n: ";
                    cin >> n;
                    for (ri = 0; ri < n; ri++) {
                        for (ci = 0; ci < n; ci++) {
                            i = ri * n + ci;
                            cout << "ri: " << ri << ' '
                                 << "ci: " << ci << " -> "
                                 << "i: " << i << endl;
                        }
                    }
                    return 0;
                }
                
            

    一維轉二維

                
                #include <iostream>
                #include <cmath>
                using namespace std;
    
                int main() {
                    int n, m;
                    int ri, ci, i;
    
                    cout << "2D index <- 1D index" << endl;
                    cout << "n: ";
                    cin >> n;
                    m = (int)sqrt(n);
                    cout << "m: " << m << '\n';
                    for (i = 0; i < n; i++) {
                        ri = i / m;
                        ci = i % m;
                        cout << "ri: " << ri << ' '
                             << "ci: " << ci << " <- "
                             << "i: " << i << endl;
                    }
                    return 0;
                }
                
            

    返回與離開

  • continue: 在「這層迴圈」中,忽略之後的程式,返回 for 結構句,再執行一次迴圈
  • break: 立刻離開「這層迴圈
  • n=20, t=3
  • n=20, t=5
  • n=20, t=7
  •             
                #include <iostream>
                using namespace std;
    
                int main() {
                    int i, n, t, c;
    
                    cout << "n: ";
                    cin >> n;
                    cout << "t: ";
                    cin >> t;
    
                    c = 0;
                    for (i = t; i < n; i++) {
                        if (i % t == 0 || i % t == t - 1)
                            continue;
                        cout << i << endl;
                        c += 1;
                        if (c == 5) {
                            break;
                        }
                    }
                    return 0;
                }
                
            

    Repetition(重複) - while loop迴圈式(迴圈或重複結構)

    整數累加

  • bool 原字 boolean
  • 台式中譯: 布林變數
  • 陸式中譯: 布爾變數
  •             
                #include <iostream>
                using namespace std;
    
                int main() {
                    bool isPlus = true;
                    int total = 0;
    
                    while (isPlus) {
                        total += 1;
                        cout << total << endl;
                        if (total == 10) {
                            isPlus = false;
                        }
                    }
                    return 0;
                }
                
            

    無條件進迴圈

  • continue: 在「這層迴圈」中,忽略之後的程式,返回 while 結構句,再執行一次迴圈
  • break: 立刻離開「這層迴圈
  • continue 和 break 指令,都適用於 for 迴圈
  •             
                #include <iostream>
                using namespace std;
    
                int main() {
                    int total = 0;
    
                    while (true) {
                        total++;
                        if (total % 2 == 1) {
                            continue;
                        }
                        cout << total << endl;
                        if (total == 10) {
                            break;
                        }
                    }
                    return 0;
                }
                
            

    非零即真

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n = 10;
    
                    while (n) {
                        cout << n << endl;
                        n = n - 1;
                    }
                    return 0;
                }
    
                
            

    任意數合計

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int total = 0;
                    int count = 0;
                    int x;
    
                    while (true) {
                        cin >> x;
                        if (x == -1)
                            break;
                        total += x;
                        count += 1;
                    }
                    cout << "Total: " << total << endl;
                    cout << "Count: " << count << endl;
                    return 0;
                }
                
            

    限定等差數列

    • step 1: 1 2 3 4 5 6 7 8 9 10
    • step 2: 2 4 6 8 10
    • step 3: 3 6 9
    • step 4: 4 8
                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int i, step;
                    int limit = 10;
    
                    cout << "step: ";
                    cin >> step;
    
                    i = step;
                    while (true) {
                        cout << i << " ";
                        i += step;
                        if (i == limit) {
                            break;
                        }
                    }
                    cout << endl;
    
                    return 0;
                }
                
            

    兩種迴圈比較

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n = 10;
                    int i;
    
                    cout << "for loop: " << endl;
                    for (i = 0; i < n; i += 1) {
                        cout << i << endl;
                    }
    
                    cout << "while loop: " << endl;
                    i = 0;
                    while (i < n) {
                        cout << i << endl;
                        i += 1;
                    }
    
                    return 0;
                }
                
            

    迴圈選取圖形

    依選項輸出圖形

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    char op;
                    int n, i;
    
                    while (true) {
                        cout << "1.正左直角 2.倒左直角" << endl;
                        cout << "3.正右直角 4.倒右直角" << endl;
                        cout << "5.金字塔形 6.奇數菱形" << endl;
                        cout << "7.三角沙漏 q.離開迴圈" << endl;
                        cout << "> ";
    
                        cin >> op;
                        if (op == 'q')
                            break;
    
                        cout << "n: ";
                        cin >> n;
    
                        if (true) {
                            for (i = 0; i < n; i++) {
                                cout << i << endl;
                            }
                        }
                        else if (true) {
                            for (i = 0; i < n; i++) {
                                cout << i << endl;
                            }
                        }
                    }
    
                    return 0;
                }
                
            

    進位轉換

    10進位轉 2/8/10/16 進位

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n;
                    string strHex = "0123456789abcdef";
    
                    cout << strHex << endl;
                    cout << "N: ";
                    cin >> n;
                    while (true) {
                        break;
                    }
    
                    cout << "Bin: " << endl;
                    cout << "Oct: " << endl;
                    cout << "Dec: " << endl;
                    cout << "Hex: " << endl;
    
                    return 0;
                }
                
            

    梅花座

                
                /*
    
                [輸入與輸出]
                n: 5
                -o-o-
                x-x-x
                -o-o-
                x-x-x
                -o-o-
    
                n: 6
                -o-o-o
                x-x-x-
                -o-o-o
                x-x-x-
                -o-o-o
                x-x-x-
    
                */
    
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n, i, j;
    
                    cout << "n: ";
                    cin >> n;
                    for (i = 0; i < n; i++) {
                        for (j = 0; j < n; j++) {
                            cout << "-";
                        }
                        cout << endl;
                    }
                    return 0;
                }
                
            

    質數判斷

    • 輸出 a 到 b 之間的所有質數,一列十數
    • 第一版:第一層使用 for 迴圈
    • 第二版:第一層使用 while 迴圈
                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int a, b, i;
    
                    cout << "a: ";
                    cin >> a;
                    cout << "b: ";
                    cin >> b;
    
                    for (i = a; i <= b; i++) {
                        cout << i << endl;
                    }
                    return 0;
                }
                
            

    一維陣列

    整數陣列預設

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int arrX[5] = {0};
                    int arrY[5];
                    int i;
    
                    for (i = 0; i < 5; i++) {
                        cout << arrX[i] << endl;
                    }
                    for (i = 0; i < 5; i++) {
                        cout << arrY[i] << endl;
                    }
                    return 0;
                }
                
            

    整數陣列索引

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int arrX[5] = {1, 2, 3, 4, 5};
                    int i;
    
                    for (i = 0; i < 10; i++) {
                        cout << arrX[i] << endl;
                    }
                    return 0;
                }
                
            

    陣列空間位址

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int arrX[10] = {0};
                    int i;
    
                    for (i = 0; i < 10; i++) {
                        cout << &arrX[i] << endl;
                    }
                    return 0;
                }
                
            

    搜尋指定數值

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int keys[] = {9, 8, 7, 5, 2, 0};
                    int key;
                    int i = 0;
                    bool isFound = false;
                    int N = sizeof(keys) / sizeof(int);
    
                    cout << "Array size: " << N << endl;
                    cout << "key: ";
                    cin >> key;
                    for (i = 0; i < N && !isFound; i++) {
                        if (key == keys[i]) {
                            cout << "index: " << i << endl;
                            isFound = true;
                        }
                    }
                    if (!isFound) {
                        cout << -1 << endl;
                    }
                    return 0;
                }
                
            

    一維亂數(模擬骰子)

    統計各點數次數

                
                #include <iostream>
                #include <iomanip>
                using namespace std;
                const int F = 6;
                const int N = 30;
    
                int main() {
                    int dice[F] = {1, 2, 3, 4, 5, 6};
                    int rnum;
                    int i;
    
                    // fixed random seed
                    // srand(1);
    
                    // time(0): seconds from 1970-01-01 00:00:00 to now
                    srand(time(0));
    
                    for (i = 1; i <= N; i++) {
                        rnum = rand() % F;
                        cout << setw(3) << dice[rnum];
                        if (i % 10 == 0) {
                            cout << endl;
                        }
                    }
                    return 0;
                }
                
            

    一維陣列彙總

    合計數、平均值、最大數、最小數

                
                #include <iostream>
                #include <cstdlib>
                using namespace std;
                const int N = 10;
    
                int main() {
                    int numbers[N] = {0};
                    int i;
    
                    // fixed random seed
                    srand(1);
    
                    for (i = 0; i < N; i++) {
                        numbers[i] = rand() % 100;
                    }
    
                    for (i = 0; i < N; i++) {
                        cout << numbers[i] << " ";
                    }
                    cout << endl;
                    return 0;
                }
                
            

    整數升冪排序一版

                
                #include <iostream>
                #include <algorithm>
                using namespace std;
    
                int main() {
                    int numbers[] = {5, 39, 4, 23, 9, 16, 8, 47, 7, 41};
                    int i;
    
                    sort(numbers, numbers+10);
                    cout << "Ascending order:" << endl;
                    for (i = 0; i < 10; i++) {
                        cout << numbers[i] << ' ';
                    }
                    cout << endl;
                    return 0;
                }
                
            

    整數升冪排序二版

                
                #include <iostream>
                #include <algorithm>
                using namespace std;
    
                int main() {
                    int numbers[] = {5, 39, 4, 23, 9, 16, 8, 47, 7, 41};
                    int i;
    
                    // begin() & end()
                    sort(begin(numbers), end(numbers));
                    cout << "Ascending order:" << endl;
                    for (i = 0; i < 10; i++) {
                        cout << numbers[i] << ' ';
                    }
                    cout << endl;
                    return 0;
                }
                
            

    整數降冪排序

                
                #include <iostream>
                #include <algorithm>
                using namespace std;
    
                int main() {
                    int numbers[] = {5, 39, 4, 23, 9, 16, 8, 47, 7, 41};
                    int i;
    
                    sort(begin(numbers), end(numbers), greater<int>());
                    cout << "Descending order:" << endl;
                    for (i = 0; i < 10; i++) {
                        cout << numbers[i] << ' ';
                    }
                    cout << endl;
                    return 0;
                }
                
            

    字串字元排序

                
                #include <iostream>
                #include <algorithm>
                using namespace std;
    
                int main() {
                    char word[] = "something";
                    int N = sizeof(word) / sizeof(char);
                    int i;
    
                    cout << "Size: " << N << endl;
                    // '\0': NUL
                    cout << "int of '\\0': " << int(word[N-1]) << endl;
                    cout << endl;
    
                    sort(begin(word), end(word)-1);
                    cout << "Ascending order:" << endl;
                    for (i = 0; i < 10; i++) {
                        cout << word[i] << ' ';
                    }
                    cout << endl;
    
                    sort(begin(word), end(word)-1, greater<char>());
                    cout << "Descending order:" << endl;
                    for (i = 0; i < 10; i++) {
                        cout << word[i] << ' ';
                    }
                    cout << endl;
                    return 0;
                }
                
            

    基本排序法

    氣泡排序、選擇排序、插入排序

                
                #include <iostream>
                #include <cstdlib>
                using namespace std;
                const int N = 10;
    
                int main() {
                    int numbers[N] = {0};
                    int i;
    
                    // fixed random seed
                    srand(5);
    
                    for (i = 0; i < N; i++) {
                        numbers[i] = rand() % 50;
                    }
    
                    for (i = 0; i < N; i++) {
                        cout << numbers[i] << " ";
                    }
                    cout << endl;
                    return 0;
                }
                
            

    計算眾數

    眾數可能不止一個

                
                #include <iostream>
                #include <iomanip>
                using namespace std;
                const int N = 30;
    
                int main() {
                    int numbers[N] = {0};
                    int i, j;
    
                    // seed: 1607154996
                    // seed: 1607155295
                    // long seed = time(0);
                    long seed = 1607154996;
                    cout << "seed: " << seed << endl;
                    srand(seed);
    
                    for (i = 0; i < N; i++) {
                        numbers[i] = rand() % 100 + 1;
                        cout << setw(4) << numbers[i];
                        if ((i+1) % 10 == 0) {
                            cout << endl;
                        }
                    }
                    return 0;
                }