NivaarExam PrepOfficial exam papers ↗

25-Comp-A4 Program Design and Data Structures · May 2013

Question 6 of 8: File I/O

Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer)

Notes on this paper

National Exams — May 2013 — 98-Comp-A4 Program Design and Data Structures. Three-hour, closed-book exam, no calculator permitted. Format: eight questions, candidates answer any five (all questions equal weight; only the first five appearing in the answer book are marked). Pseudocode or a high-level language (C or C++) is acceptable throughout — marking emphasizes program operation, not syntactic detail. All eight questions are solved below for completeness. No marks breakdown per sub-part is given on the source paper beyond the "equal weight" instruction.

Reference texts: Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms (3rd ed., MIT Press) — algorithm design, complexity analysis, sorting; Weiss, Data Structures and Algorithm Analysis in C (2nd ed., Pearson) — linked lists, stacks, pointer-based structures; Deitel & Deitel, C++ How to Program (9th ed., Pearson) — classes, templates, operator overloading; Kernighan & Ritchie, The C Programming Language (2nd ed.) — file I/O and arrays.

Question 6: File I/O

Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.

Approach. Scan the file one character at a time; push every opening bracket onto a stack, and on every closing bracket, pop the stack and confirm the popped symbol is the matching opener — any mismatch, or a closing bracket with nothing on the stack, means unbalanced. At end of file, the stack must be empty (no unmatched openers left over).

#include <stdio.h>
#define MAXLEN 10000

int is_balanced(FILE *fp) {
    char stack[MAXLEN];
    int top = -1, c;

    while ((c = fgetc(fp)) != EOF) {
        if (c == '(' || c == '[' || c == '{') {
            stack[++top] = (char) c;
        } else if (c == ')' || c == ']' || c == '}') {
            if (top < 0) return 0;             /* closer with nothing open */
            char open = stack[top--];
            if ((c == ')' && open != '(') ||
                (c == ']' && open != '[') ||
                (c == '}' && open != '{'))
                return 0;                       /* wrong bracket type */
        }
        /* any other character is ignored */
    }
    return top == -1;                            /* nothing left unclosed */
}

int main(void) {
    char filename[256];
    printf("Enter file name: ");
    scanf("%255s", filename);

    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Could not open %s\n", filename);
        return 1;
    }
    printf(is_balanced(fp) ? "All parentheses are balanced.\n"
                            : "Parentheses are NOT balanced.\n");
    fclose(fp);
    return 0;
}

Tracing the two given examples: "( [ ] )" pushes ( then [, pops [ to match ], pops ( to match ) — stack ends empty, balanced. "( [) ]" pushes ( then [, then hits ): the top of the stack is [, not (, so the type check fails immediately — correctly reported as not balanced.

InputResultReason
( [ ] )Balancedevery closer matches the most recently opened bracket, stack empties
( [) ]Not balanced) arrives while [ is on top of the stack — type mismatch