C++

C++ 入門

程式基本概念

編譯與執行(1)

編譯後立即執行

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

編譯與執行(2)

編譯後,執行並導入測資

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

  • bits/stdc++.h: 全標準函式庫
  • namespace: 命名空間。不同的命名空間,可以設定相同的變數或函式名稱
  • main(): 主函式。程式執行進入點(Entry Point)
  • return: 回傳
  • iostream: 輸出入函式庫
  • cin: 從「標準輸入裝置」,例如鍵盤或檔案,取得數據,存入變數
  • cout: 將訊息或數據,送到「標準輸出裝置」顯示,例如螢幕
  • stdio.h: C語言輸出入函式庫
  • scanf(): C語言輸入函式
  • printf(): C語言輸出函式
  • endl: 輸出換行
  • \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;
                }
                
            

    各種進位值

    進位制基底與位數範圍
    • 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 << uppercase;
                    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);
                    printf("Hex: %X\n", n);
                    return 0;
                }
                
            

    Input(輸入)

    名字與年齡

    string: 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語言以字元陣列儲存字串

                
                #include <stdio.h>
    
                int main() {
                    char name[30];
                    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 << "Sum: " << a + b << endl;
                    return 0;
                }
                
            

    兩數相加(C)

                
                #include <stdio.h>
    
                int main() {
                    int a, b;
                    int x;
    
                    printf("a: ");
                    scanf("%d", &a);
                    printf("b: ");
                    scanf("%d", &b);
                    x = a + b;
                    printf("Sum: %d\n", x);
                    return 0;
                }
                
            

    和差問題

                
                #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;
                }
                
            

    三數相乘

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int a, b, c;
                    int x;
    
                    cin >> a >> b >> c;
                    x = a * b * c;
                    cout << "Product: " << x << endl;
                    return 0;
                }
                
            

    三數相乘(C)

                
                #include <stdio.h>
    
                int main() {
                    int a, b, c;
                    int x;
    
                    scanf("%d %d %d", &a, &b, &c);
                    x = a * b * c;
                    printf("Product: %d\n", x);
                    return 0;
                }
                
            

    加減乘除運算

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int a, b;
    
                    cout << "a: ";
                    cin >> a;
                    cout << "b: ";
                    cin >> b;
                    // + (加法)
                    cout << a << " + " << b << " = " << a + b << endl;
                    // - (減法)
                    cout << a << " - " << b << " = " << a - b << endl;
                    // * (乘法)
                    cout << a << " * " << b << " = " << a * b << endl;
                    // / (分數除法) 其中之一為浮點數,結果為浮點數
                    cout << a << " / " << b << " = " << (double)a / b << endl;
                    // / (商數除法) 兩整數相除結果為商數
                    cout << a << " / " << b << " = " << a / b << endl;
                    // % (餘數除法)
                    cout << a << " % " << b << " = " << a % b << endl;
                    return 0;
                }
                
            

    個位與十位

                
                #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;
                }
                
            

    圓周率

                
                #include <iostream>
                #include <cmath>
                #include <iomanip>
                using namespace std;
    
                int main() {
                    double pi = M_PI;
    
                    cout << pi << endl;
                    cout << fixed;
                    cout << setprecision(2) << pi << endl;
                    cout << setprecision(4) << pi << endl;
                    cout << setprecision(8) << pi << endl;
                    return 0;
                }
                
            

    圓周率(C)

                
                #include <stdio.h>
                #include <math.h>
    
                int main() {
                    double pi = M_PI;
    
                    printf("%f\n", pi);
                    printf("%.2f\n", pi);
                    printf("%.4f\n", pi);
                    printf("%.8f\n", pi);
                    return 0;
                }
                
            

    浮點數精度

                
                #include <iostream>
                #include <cmath>
                #include <iomanip>
                using namespace std;
    
                int main() {
                    double a = 12.40;
                    double b = 12.50;
                    double c = 12.55;
                    double d = 12.60;
    
                    cout << setprecision(32);
                    cout << a << endl;
                    cout << b << endl;
                    cout << c << endl;
                    cout << d << endl;
                    cout << endl;
                    cout << round(a) << endl;
                    cout << round(b) << endl;
                    cout << round(c) << endl;
                    cout << round(d) << endl;
                    return 0;
                }
                
            

    位元運算

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int a, b;
    
                    cout << "a: ";
                    cin >> a;
                    cout << "b: ";
                    cin >> b;
                    // ~ (NOT)
                    cout << ~a << endl;
                    cout << ~b << endl;
                    // & (AND)
                    cout << (a & b) << endl;
                    // | (OR)
                    cout << (a | b) << endl;
                    // ^ (XOR)
                    cout << (a ^ b) << endl;
                    // << (左移)
                    cout << (a << b) << endl;
                    // >> (右移)
                    cout << (a >> b)<< endl;
                    return 0;
                }
                
            

    位元運算(C)

                
                #include <stdio.h>
    
                int main() {
                    int a, b;
    
                    printf("a: ");
                    scanf("%d", &a);
                    printf("b: ");
                    scanf("%d", &b);
                    // ~ (NOT)
                    printf("%d\n", ~a);
                    printf("%d\n", ~b);
                    // & (AND)
                    printf("%d\n", a & b);
                    // | (OR)
                    printf("%d\n", a | b);
                    // ^ (XOR)
                    printf("%d\n", a ^ b);
                    // << (左移)
                    printf("%d\n", a << b);
                    // >> (右移)
                    printf("%d\n", a >> b);
                    return 0;
                }
                
            

    運算子優先序

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

    Variable(變數)

    資料型別長度(C)

                
                #include <stdio.h>
                #include <stdint.h>
    
                int main() {
                    printf("         char   : %ld byte(s)\n", sizeof(char));
                    printf("         short  : %ld byte(s)\n", sizeof(short));
                    printf("         int    : %ld byte(s)\n", sizeof(int));
                    printf("         long   : %ld byte(s)\n", sizeof(long));
                    printf("unsigned short  : %ld byte(s)\n", sizeof(unsigned short));
                    printf("unsigned int    : %ld byte(s)\n", sizeof(unsigned int));
                    printf("unsigned long   : %ld byte(s)\n", sizeof(unsigned long));
                    printf("         float  : %ld byte(s)\n", sizeof(float));
                    printf("         double : %ld byte(s)\n", sizeof(double));
                    printf("\n");
                    printf("         size_t : %ld byte(s)\n", sizeof(size_t));
                    printf("         int8_t : %ld byte(s)\n", sizeof(int8_t));
                    printf("         int16_t: %ld byte(s)\n", sizeof(int16_t));
                    printf("         int32_t: %ld byte(s)\n", sizeof(int32_t));
                    printf("         int64_t: %ld byte(s)\n", sizeof(int64_t));
                    printf("         uint8_t: %ld byte(s)\n", sizeof(uint8_t));
                    printf("        uint16_t: %ld byte(s)\n", sizeof(uint16_t));
                    printf("        uint32_t: %ld byte(s)\n", sizeof(uint32_t));
                    printf("        uint64_t: %ld byte(s)\n", sizeof(uint64_t));
                    return 0;
                }
                
            

    變數最大值

                
                #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;
                }
                
            

    整數範圍(C)

                
                #include <stdio.h>
                #include <limits.h>
    
                int main() {
                    printf(" CHAR: %d ~ %d  \n", CHAR_MIN, CHAR_MAX);
                    printf(" SHRT: %d ~ %d  \n", SHRT_MIN, SHRT_MAX);
                    printf("  INT: %d ~ %d  \n", INT_MIN, INT_MAX);
                    printf(" LONG: %ld ~ %ld\n", LONG_MIN, LONG_MAX);
                    printf("UCHAR: %d \n", UCHAR_MAX);
                    printf("USHRT: %d \n", USHRT_MAX);
                    printf(" UINT: %u \n", UINT_MAX);
                    printf("ULONG: %lu\n", ULONG_MAX);
                    return 0;
                }
                
            
    TypeRange
    CHAR-128 ~ 127
    SHRT-32768 ~ 32767
    INT-2147483648 ~ 2147483647
    LONG-9223372036854775808 ~ 9223372036854775807
    UCHAR255
    USHRT65535
    UINT4294967295
    ULONG18446744073709551615

    整數與字元

                
                #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;
                }
                
            

    兩數交換

                
                #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;
                }
                
            

    浮點數轉整數

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    float a, b;
                    int n;
    
                    cout << "Enter 2 numbers: ";
                    cin >> a >> b;
    
                    cout << a / b << endl;
                    n = a / b;
                    cout << n << endl;
                    return 0;
                }
                
            

    兩數相除

                
                #include <iostream>
                #include <iomanip>
                using namespace std;
    
                int main() {
                    int   dividend = 19;
                    int   divisor1 = 3;
                    float divisor2 = 6.0;
                    float answer;
    
                    answer = dividend / divisor1;
                    cout << "answer1: " << answer << endl;
    
                    cout << fixed << setprecision(3);
    
                    answer = dividend / divisor2;
                    cout << "answer2: " << answer << endl;
    
                    answer = (float)dividend / divisor1;
                    cout << "answer3: " << answer << endl;
    
                    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>
    
                int main() {
                    int a, b, c;
    
                    printf("Enter 3 numbers: ");
                    scanf("%d %d %d", &a, &b, &c);
                    printf("%p\n", &a);
                    printf("%p\n", &b);
                    printf("%p\n", &c);
                    return 0;
                }
                
            

    Decision making(決策) - 決策式(分支或選擇結構)

    if條件式

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    string weather = "sunny";
    
                    cout << "Let's hang out.\n";
                    if (weather == "sunny") {
                        cout << "Sure. Why not?\n";
                    }
                    return 0;
                }
                
            

    if條件式(C)

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

    if-else條件否則式

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

    if-else條件否則式(C)

                
                #include <stdio.h>
                #include <string.h>
    
                int main() {
                    char weather[10];
    
                    printf("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 at home.\n");
                    }
                    return 0;
                }
                
            

    絕對值

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int n;
    
                    cout << "> ";
                    cin >> n;
                    cout << "abs: " << abs(n) << endl;
                    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;
                }
                
            

    三元運算子

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

                
                #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;
                }
                
            

    成績平均績點

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int grade;
    
                    cout << "Your grade: ";
                    cin >> grade;
    
                    if (grade >= 80) {
                        cout << "A, GPA is 4\n";
                    }
                    else if (grade < 80 && grade >= 70) {
                        cout << "B, GPA is 3\n";
                    }
                    else if (grade < 70 && grade >= 60) {
                        cout << "C, GPA is 2\n";
                    }
                    else if (grade < 60 && grade >= 50) {
                        cout << "D, GPA is 1\n";
                    }
                    else {
                        cout << "F, GPA is 0\n";
                    }
                    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;
                                  break;
                        case '-': cout << x - y;
                                  break;
                        case '*': cout << x * y;
                                  break;
                        case '/': cout << x / y;
                                  break;
                        case '%': cout << x % y;
                                  break;
                        default: cout << "Wrong operation!";
                    }
                    cout << endl;
                    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\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 credit_card;
                    int total;
                    int iscard;
    
                    cout << "Price? ";
                    cin >> price;
                    cout << "Tickets? ";
                    cin >> tickets;
                    cout << "Credit Card? (Y/n): ";
                    cin >> credit_card;
    
                    credit_card = toupper(credit_card);
                    iscard = (credit_card == 'Y');
                    total = iscard ? price*tickets*0.9 : price*tickets;
                    cout << "Total: $" << total << endl;
                    return 0;
                }
                
            

    兩層巢狀決策

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

    三層巢狀決策

    增加第三層,第二層及第三層設定名字

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    char first_born;
                    char second_born;
                    char third_born;
    
                    cin >> first_born >> second_born >> third_born;
                    first_born  = toupper(first_born);
                    second_born = toupper(second_born);
                    third_born  = toupper(third_born);
    
                    if (first_born == 'M') {
                        cout << "1st child: Son -> Aaron\n";
                        if (second_born == 'M')
                            cout << "2nd child: Son\n";
                        else
                            cout << "2nd child: Daughter\n";
                    }
                    else {
                        cout << "1st child: Daughter -> Bella\n";
                        if (second_born == 'M')
                            cout << "2nd child: Son\n";
                        else
                            cout << "2nd child: Daughter\n";
                    }
                    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 < 5; i++) {
                        cout << i << endl;
                    }
                    return 0;
                }
                
            

    五個星號

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

    數的兩倍

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int i;
    
                    for (i = 1; i < 6; i++) {
                        cout << "i: " << i << '\n';
                        i = i * 2;
                        cout << "Double of i: " << i << '\n';
                    }
                    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--) {
                        cout << i << 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;
                }
                
            

    星號三角

    正左直角、倒左直角、正右直角、倒右直角、金字塔形、星號樹

                
                #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\n";
                    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\n";
                    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;
                }
                
            

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

    比較運算子

  • == : 是否相等
  • != : 是否不相等
  •  > : 大於
  • >= : 大於等於
  •  < : 小於
  • <= : 小於等於
  • 整數累加

                
                #include <iostream>
                using namespace std;
    
                int main() {
                    int plus = 1;
                    int sum = 0;
    
                    while (plus) {
                        sum = sum + 1;
                        cout << sum << endl;
                        if (sum == 10) {
                            plus = 0;
                        }
                    }
                    return 0;
                }
                
            

    布林變數

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

    無條件進迴圈

  • continue: 在「這層迴圈」中,忽略之後的程式,跳到 while 結構句,再執行一次迴圈
  • break: 立刻離開「這層迴圈
  • continue 和 break 指令,都適用於 for 迴圈
  •             
                #include <iostream>
                using namespace std;
    
                int main() {
                    int sum = 0;
    
                    while (true) {
                        sum++;
                        if (sum % 2 == 1) {
                            continue;
                        }
                        cout << sum << endl;
                        if (sum == 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>
                #include <iomanip>
                using namespace std;
    
                int main() {
                    int n = 0;
                    int total = 0;
                    int i = 1;
    
                    cout << "Enter integers (0 to end):\n";
                    do {
                        cout << right << setw(2) << i << "> ";
                        cin >> n;
                        while (getchar() != '\n');
                        total += n;
                        i++;
                    } while (n != 0);
                    cout << "Total: " << total << endl;
                    return 0;
                }
                
            

    基礎解題操作

    加速輸出入

  • ios::sync_with_stdio(0): 取消 C++ 的 iostream 同步 C 的 stdio,然後不該混用 C 的 scanf 和 printf
  • cin.tie(0): 解除綁定 cout,在 cin 時,就不會執行 flush cout buffer (清空輸出緩衝區)
  • 基礎解題一(文字訊息)

                
                /* 基礎解題一
    
                [INPUT]
                John
                Jane
    
                [OUTPUT]
                Hello, John!
                Hello, Jane!
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    string name;
    
                    while (cin >> name) {
                        cout << "Hello, " << name << "!\n";
                    }
                    return 0;
                }
    
                
            

    基礎解題二(兩數相加)

                
                /* 基礎解題二
    
                [INPUT]
                12 38
                54 87
    
                [OUTPUT]
                50
                141
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    int a, b;
    
                    while (cin >> a >> b) {
                        cout << a+b << '\n';
                    }
                    return 0;
                }
                
            

    基礎解題三(N數相加)

                
                /* 基礎解題三
    
                [INPUT]
                5
                13 24 36 47 18
                4
                32 54 67 81
    
                [OUTPUT]
                138
                234
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    int n, i, a;
                    int total;
    
                    while (cin >> n) {
                        total = 0;
                        for (i = 0; i < n; i+=1) {
                            cin >> a;
                            total += a;
                        }
                        cout << total << '\n';
                    }
                    return 0;
                }
                
            

    基礎解題四(不定N數相加)

                
                /* 基礎解題四
    
                [INPUT]
                13 24 36 47 18 -1
                32 54 67 81 -1
    
                [OUTPUT]
                138
                234
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    int i, a;
                    int total;
    
                    total = 0;
                    while (cin >> a) {
                        if (a == -1) {
                            cout << total << '\n';
                            total = 0;
                            continue;
                        }
                        total += a;
                    }
                    return 0;
                }
                
            

    基礎解題五(符號矩陣)

    矩陣蛇行、子矩陣

                
                /* 基礎解題五
    
                [INPUT]
                3 3
                1 2 3
                6 5 4
                7 8 9
    
                [OUTPUT]
                X O X
                O X O
                X O X
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    int n, m, a;
                    int ri, ci;
    
                    while (cin >> n >> m) {
                        for (ri = 0; ri < n; ri+=1) {
                            for (ci = 0; ci < m; ci+=1) {
                                cin >> a;
                                if (a % 2 == 0) {
                                    cout << "O ";
                                }
                                else if (a % 2 == 1) {
                                    cout << "X ";
                                }
                            }
                            cout << '\n';
                        }
                    }
                    return 0;
                }
                
            

    基礎解題六(大寫小寫個數)

                
                /* 基礎解題六
    
                [INPUT]
                AbcDGauGarD
    
                [OUTPUT]
                5
                6
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    char c;
                    int uppers = 0;
                    int lowers = 0;
    
                    while (cin >> c) {
                        if (c >= 'A' && c <= 'Z') {
                            uppers += 1;
                        }
                        else if (c >= 'a' && c <= 'z') {
                            lowers += 1;
                        }
                    }
                    cout << uppers << '\n' << lowers << '\n';
                    return 0;
                }
                
            

    基礎解題七(數字個數)

                
                /* 基礎解題七
    
                [INPUT]
                3398025504319006006144833458128230239123
    
                [OUTPUT]
                0: 7
                1: 4
                2: 5
                3: 8
                4: 4
                5: 3
                6: 2
                7: 0
                8: 4
                9: 3
                40
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    char c;
                    int digits[10] = {0};
                    int i, total;
    
                    while (cin >> c) {
                        digits[c-'0'] += 1;
                    }
    
                    total = 0;
                    for (i = 0; i < 10; i++) {
                        cout << i << ": " << digits[i] << '\n';
                        total += digits[i];
                    }
                    cout << total << '\n';
    
                    return 0;
                }
                
            

    基礎解題八(排序與反轉)

                
                /* 基礎解題八
    
                [INPUT]
                33 98 25 50 43 19 6 61 44 83 34 58 12 82 30 23 91 23
    
                [OUTPUT]
                23 91 23 30 82 12 58 34 83 44 61 6 19 43 50 25 98 33
                6 12 19 23 23 25 30 33 34 43 44 50 58 61 82 83 91 98
                98 91 83 82 61 58 50 44 43 34 33 30 25 23 23 19 12 6
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                void print_array(int arr[], int n) {
                    for (int i = 0; i < n; i++) {
                        cout << arr[i] << ' ';
                    }
                    cout << '\n';
                }
    
                int main() {
                    ios::sync_with_stdio(0);
                    cin.tie(0);
    
                    int numbers[100] = {0};
                    int n, a;
    
                    n = 0;
                    while (cin >> a) {
                        numbers[n] = a;
                        n++;
                    }
    
                    // reverse order
                    reverse(numbers, numbers+n);
                    print_array(numbers, n);
                    // ascending order
                    sort(numbers, numbers+n);
                    print_array(numbers, n);
                    // reverse order
                    reverse(numbers, numbers+n);
                    print_array(numbers, n);
    
                    return 0;
                }
                
            

    基礎解題九(尋找字串)

                
                /* 基礎解題九
    
                [INPUT]
                C++ is a high-level general-purpose programming language.
                program
                process
    
                [OUTPUT]
                1
                0
    
                */
    
                #include <bits/stdc++.h>
                using namespace std;
    
                int main() {
                    string astr;
                    string str1, str2;
                    int pos;
    
                    getline(cin, astr);
                    cin >> str1 >> str2;
                    // cout << "npos: " << string::npos << endl;
    
                    pos = astr.find(str1);
                    cout << (pos != string::npos) << endl;
    
                    pos = astr.find(str2);
                    cout << (pos != string::npos) << endl;
    
                    return 0;
                }