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

科目名稱:程式設計 開課系所:資訊工程 學系 考試日期 2024.3.14
系所別:
年級:
學號:
姓名:
考試時間 14:10-14:20
  1. (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).
    //  Reading/writing a binary file
    #include <iostream>
    int main()
    {
        const char s[4][3] = { "12", "34", "56", "78" };
        char t[2][6];
        FILE* fp = fopen("a.txt", "wb");
        fwrite(s, 3, 4, fp);
        fclose(fp);
        fp = fopen("a.txt", "rb");
        fread(t, 6, 2, fp);
        fclose(fp);
        t[1][2] = 65;       // 'A' == 65
        std::cout << t[0] << std::endl << t[1] << std::endl;
        return 0;
    }
  2. (10%) Assume there is no run-time error (e.g., out of memory).  Predict the output the following program.
    // Linked-list as a queue
    #include <iostream>
    struct Node {
        int value;
        Node* pNext;
    };

    Node* front = nullptr;  // a global variable
    void enqueue(int v) {
        Node* p = new Node;
        p->value = v;
        p->pNext = nullptr;
        if (front == nullptr) {
            front = p;
        } else {
            Node* rear = front;
            while (rear->pNext != nullptr)
                rear = rear->pNext;
            rear->pNext = p;
        }
    }

    int dequeue() {
        Node* p = front;
        int result = front->value;
        front = front->pNext;
        delete p;
        return result;
    }

    void display() {
        Node* p = front;
        while (p) {
            std::cout << p->value << ' ';
            p = p->pNext;
        }
        std::cout << std::endl;
    }

    int main() {
        enqueue(1); enqueue(3); enqueue(5);
        display();
        enqueue(2); enqueue(4);
        std::cout << dequeue() << dequeue();
        display();
        return 0;
    }

  3. (10%)Predict the output of the following program, and draw a figure of the created binary tree.
    // insertToTree
    #include <iostream>
    struct Node {
       int value;
       Node* left;
       Node* right;
    };

    void printTree(Node* p) {
       if (p) {
           printTree(p->left);              // recursive function call
           std::cout << p->value;
           printTree(p->right);
       }
    }

    void insertToTree(Node*& p, int v) {    // A pointer passed by ref
        if (p == nullptr) {
            p = new Node;
            p->value = v;
            p->left  = nullptr;
            p->right = nullptr;
        } else if (v < p->value)
            insertToTree(p->right, v);       // recursive function call
        else
            insertToTree(p->left, v);  
    }

    int main() {
        Node* root = nullptr;
        insertToTree(root, 3);
        insertToTree(root, 1);
        insertToTree(root, 2);
        insertToTree(root, 5);
        insertToTree(root, 4);
        printTree(root);
        std::cout << std::endl;
        return 0;
    }