國立暨南國際大學 112 學年度第二學期小考試卷

科目名稱:程式設計 開課系所:資訊工程 學系 考試日期 2024.3.8
系所別:
年級:
學號:
姓名:
考試時間 08:10-08:20
  1. (10%) Suppose you compile and run the following code on a Linux host (e.g., lilina). What will be the size of the output file "a.txt"?
    /* Write to a File */
    #include <iostream>
    int main() {
        FILE* fp = fopen("a.txt", "w");
        int n;      /* sizeof(n) == 4 */
        for (int i=0; i<4; ++i) {
            n = (i==0)?1:n*5;
            fprintf(fp, "%d\n", n);
        }
        fclose(fp);
        return 0;
    }

  2. (10%) Determine whether the syntax of the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    /* Linked-List */
    #include <iostream>
    struct Node {
        int value;
        Node* next;
    };

    Node* insertToList(Node* head, int v) {
        Node* p = new Node;
        p->value = v;
        p->next = head;
        return p;
    }

    void printList(Node* p) {
        if (p) {
            std::cout << p->value;
            printList(p->next);
        }
    }

    int main() {
        int a[] = { 26, 59, 41, 31 };
        Node* pList = nullptr;
        for (size_t i=0; i<sizeof(a)/sizeof(a[0]); ++i)
            pList = insertToList(pList, a[i]);
        printList(pList);
        return 0;
    }


  3. (10%) Determine whether the syntax of the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    /* Binary Tree */
    #include <iostream>

    struct Node {
        char c;
        Node* left;
        Node* right;
    };

    void printTree(Node* p) {
        if (p) {
            printTree(p->left);
            printTree(p->right);
            std::cout << p->c;
        }
    }

    int main() {
        Node n1 = { 'A', nullptr, nullptr };
        Node n2 = { 'I', nullptr, nullptr };
        Node n3 = { 'W', nullptr, nullptr };
        Node n4 = { 'O', nullptr, nullptr };
        Node n5 = { 'R', &n1, &n2 };
        Node n6 = { 'L', &n3, &n4 };
        Node n7 = { 'F', &n5, &n6 };

        printTree(&n7);
        return 0;
    }