C Programming · PYQ Methods
RCS101 2017?18: Worked Study CompanionAn independent study companion to the RCS101 Computer System & Programming in C paper, session 2017–18. These worked methods are original teaching material, not an official university marking scheme. The PYQ library retains its PDF viewing and download controls. Open the paper PDF. Use these explanations alongside your course syllabus and the original paper. 1. Section A: definitions and traps1(a–b): function arguments and interfacesIn 1(c): greatest of three valuesDraw Start → read a, b, c → greatest = a → test b > greatest and update if true → test c > greatest and update if true → print greatest → Stop. With a = 8, b = 8, c = 3, greatest remains 8. This handles ties without a separate all-equal branch. 1(d): swap without a third integerFor two distinct unsigned-integer objects, XOR swap uses 1(e–f): translation and do-whileA compiler translates code into another representation before that result runs; an interpreter executes a representation through a runtime. A system may use both strategies, such as compiling to bytecode and then interpreting it. A do-while checks its condition after executing the body, so the body runs at least once. A menu that must appear before testing the user’s choice is a useful example. 1(g): expand the macro first
2. Section B: explain with examples2(a): operating-system responsibilitiesAn operating system coordinates hardware and offers program services. Explain process scheduling, virtual memory, files and directories, device I/O, access control and error handling. Relate each to a task: the scheduler chooses a runnable process, address protection separates processes, and file APIs let a program read a document without implementing a disk driver. 2(b): C typesOrganize the answer into arithmetic types, pointers, arrays, structures and unions, plus void for no returned value. Examples include 2(c): seven factorial terms
After n = 3, factorial is 6 and total is 1 + 1 + 0.5 = 2.5. The seven-term result is approximately 2.718055556. Floating-point division preserves the fractions. Reusing the previous factorial avoids calculating each factorial from scratch. 2(d): pointers and dynamic allocationA pointer can identify an object or function, or hold a null value. Address-of & obtains an object’s address and dereference * accesses the pointed-to object. malloc allocates uninitialized storage; calloc initializes allocated bytes to zero; realloc resizes; free releases. Check failures before dereferencing and specify who owns each allocation. For a nonzero resize, keep realloc’s result in a temporary pointer so failure does not overwrite the only reference to the original allocation. 2(e): bubble-sort traceCompare neighbours and swap those out of order. [5, 1, 4, 2] becomes [1, 4, 2, 5] after one pass and [1, 2, 4, 5] after the next. Each pass settles the largest remaining value at the right boundary; shorten the following pass. Stop early if no swap occurs. The usual algorithm takes O(n²) worst-case time and O(1) auxiliary storage; early exit reduces the already-sorted case to O(n). 3. Number programs and boundaries3(a): palindrome methodRead a decimal digit string, compare the first and last digit, then move inward. This avoids overflowing an integer while reversing a long number. Validate every character and reject a truncated bounded-buffer input. State whether leading zeroes are significant: under numeric semantics, strip them first; under text semantics, test the exact string. For 1221, both mirrored pairs match; for 1231, the inner pair fails. 3(b): prime test
Every composite has a factor at most its square root. The condition d <= n/d avoids overflowing d*d. Check 0, 1, 2, 29 and 49: only 2 and 29 are prime. Reject negative or malformed input before passing a value to this unsigned helper. 4. Recursion and parameters4(a): FibonacciUse F(0) = 0, F(1) = 1 and F(n) = F(n−1) + F(n−2). Return the base cases immediately. The first eight terms are 0, 1, 1, 2, 3, 5, 8, 13. Naïve recursion repeats subproblems and takes exponential time. Memoization computes each index once; an iterative pair of previous values produces the sequence in O(n) additions and O(1) auxiliary storage. A fixed-width implementation also needs an overflow limit. 4(b): value and address passingC passes every argument by value. A pointer parameter is itself copied, but enables changes to its pointed-to object. Copying a small scalar is inexpensive; passing a large structure by pointer can avoid copying its contents, while adding lifetime and aliasing concerns. Use pointer-to-const for read-only access. Neither choice is universally faster; the data size, compiler and operation matter. 5. Matrices and structures5(a): matrix multiplicationA with r rows and k columns can multiply B with k rows and c columns, producing an r-by-c result. Reject incompatible dimensions before calculating. Initialize each result cell to zero, then sum A[i][t]×B[t][j] for t = 0 to k−1. For A = [[1, 2], [3, 4]] and B = [[2, 0], [1, 2]], the result is [[4, 4], [10, 8]]. The conventional algorithm uses r×c×k multiply-add steps. Check dimensions, allocation sizes and numeric overflow for user input. 5(b): dates as structures
Print Equal when this returns true, otherwise Unequal. Validate actual calendar dates when accepting input. Do not compare structure bytes with memcmp: padding bytes are not part of logical date equality. 6. Files and preprocessing6(a): modes and copyingr reads an existing file, w writes and truncates or creates, and a appends or creates. A plus sign enables reading and writing, subject to update-stream sequencing rules. Add b for binary mode where text and binary differ. For byte-preserving copying, open the source with rb and destination with wb. Check that they are distinct files before opening the destination: otherwise truncation can destroy the source. Store fgetc’s result in an int, so EOF remains distinct from valid bytes. Copy successful reads with checked writes, inspect ferror to distinguish end-of-file from an input error, and check output close errors. An EOF indication alone is not proof that copying succeeded. 6(b): macros
7. Hardware and storage classes7(a): functional computer diagramDraw Input → Memory ↔ CPU → Output, with secondary storage connected through I/O. Within the CPU, label registers, the control unit and the arithmetic/logic unit. Registers hold immediately needed values, the control unit coordinates execution, the ALU performs calculations and comparisons, memory holds active programs and data, and secondary storage retains data. This functional diagram need not imply a particular physical bus arrangement. 7(b): distinguish scope, duration and linkageOrdinary block variables usually have automatic storage duration. A block-scope static object retains its value across calls. An extern declaration can refer to an object defined elsewhere. At file scope, static gives internal linkage within a translation unit. The traditional register specifier does not guarantee placement in a hardware register. Scope describes name visibility, storage duration describes lifetime, and linkage connects declarations referring to one entity. 8. Revision checklistFor each program, state input assumptions, initialize accumulators, trace a small example and check a boundary. Explain undefined behavior rather than predicting reliable output from it. Consult the WG14 C11 draft for exact rules, and confirm which C version your course uses. |