NivaarExam PrepOfficial exam papers ↗

25-Comp-A4 Program Design and Data Structures · December 2018

Question 4 of 9: File I/O — Average Word Length

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

Notes on this paper

Paper format. 17-Comp-A4 Program Design and Data Structures, December 2018 — 3 hours, closed book, no calculator permitted. Nine questions, each of equal weight (Question 1 is split 10+10; Questions 2–9 are 20 marks each); candidates answer any six, and only the first six as they appear in the answer book are marked, so the paper is marked out of 120. Pseudocode or any high-level language (e.g. C or C++) is accepted, and the examiner's note states explicitly that marking emphasises the operation of the program, not syntactic details. All nine questions are answered below, because the whole set is the more useful revision resource. Answers are given in C or C++ as the question dictates; each is compilable as written, but a clear, correctly reasoned pseudocode answer would earn the same marks.

Reference texts for this subject.

  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 4th ed. — tree walks (ch. 12), stacks and linear-time scans (ch. 10, 2), asymptotic analysis (ch. 3).
  • Weiss, Data Structures and Algorithm Analysis in C, 2nd ed. — arrays and dynamic 2-D allocation (ch. 1), linked lists (ch. 3), stacks (ch. 3.3), binary trees (ch. 4).
  • Deitel & Deitel, C++ How to Program, 10th ed. — class design, templates and the Rule of Three (ch. 9–12), file streams (ch. 14).
  • Kernighan & Ritchie, The C Programming Language, 2nd ed. — character/file I/O idioms (ch. 1, 7), pointers and structures (ch. 5–6).
  • Stroustrup, The C++ Programming Language, 4th ed. — value semantics, const-correctness and templates (ch. 3, 16–18).

The Computer Engineering citation list is built around architecture and networking texts (Patterson & Hennessy, Tanenbaum, Mano); this subject is programming and data structures, so the works above are cited instead.

Question 4: File I/O — Average Word Length (20 marks)

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.

Given. A text file whose "word" boundaries are exactly four delimiter kinds: blank, comma, period, and line start/end (the newline character serves as both end-of-line and start-of-next-line).

Find. The average number of letters per word, over the whole file.

Approach. Read the file one character at a time (no need to buffer whole lines); maintain a running "current word length" that resets to zero at every delimiter, and add it to a running total whenever a non-empty word just ended; divide total letters by total words at end of file.

  1. Recognise this as a state-machine scan, not a tokenizer that needs to store words. Only the running letter-count of the word in progress is needed — never the word's actual characters — because the question asks for a length statistic, not the words themselves.
    #include <stdio.h>
    
    int is_delim(int c)
    {
        return c == ' ' || c == ',' || c == '.' || c == '\n';
    }
    
    int main(void)
    {
        char filename[256];
        long total_letters = 0, total_words = 0, cur_len = 0;
        int c;
        FILE *fp;
    
        printf("Enter file name: ");
        if (scanf("%255s", filename) != 1) return 1;
    
        fp = fopen(filename, "r");
        if (fp == NULL) {
            printf("Could not open %s\n", filename);
            return 1;
        }
    
        while ((c = fgetc(fp)) != EOF) {
            if (is_delim(c)) {
                if (cur_len > 0) {           /* a word just ended */
                    total_words++;
                    total_letters += cur_len;
                    cur_len = 0;
                }
            } else {
                cur_len++;
            }
        }
        if (cur_len > 0) {                   /* trailing word, no closing delimiter */
            total_words++;
            total_letters += cur_len;
        }
        fclose(fp);
    
        if (total_words == 0)
            printf("The file contains no words.\n");
        else
            printf("Average word length: %.4f letters (%ld words).\n",
                   (double) total_letters / total_words, total_words);
        return 0;
    }
  2. Trace it on a worked example file containing the single line The quick brown fox jumps over the lazy dog. The words are The(3), quick(5), brown(5), fox(3), jumps(5), over(4), the(3), lazy(4), dog(3) — nine words, and the trailing period after "dog" closes the last word rather than being swallowed into it. $$\text{total letters} = 3+5+5+3+5+4+3+4+3 = 35, \qquad \text{total words} = 9$$ $$\boxed{\text{average word length} = 35/9 = 3.8889\ \text{letters}}$$
Question 4 — results
QuantityValue
Sample sentence“The quick brown fox jumps over the lazy dog.”
Word count9
Total letters35
Average word length3.8889