25-Comp-A4 Program Design and Data Structures · May 2013
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer)
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 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. Square size $n$, followed by $n^2$ integers filling the array row by row. Find. Whether every row sum, column sum, and both diagonal sums are equal.
Approach. Dynamically allocate the $n \times n$ array, take the first row's sum as the target, then check every row, every column, and both diagonals against that one target — a single early mismatch is enough to reject the square.
int is_magic(int **sq, int n) {
int target = 0;
for (int j = 0; j < n; j++) target += sq[0][j]; /* row 0 sets the target */
for (int i = 0; i < n; i++) {
int row_sum = 0, col_sum = 0;
for (int j = 0; j < n; j++) {
row_sum += sq[i][j];
col_sum += sq[j][i];
}
if (row_sum != target || col_sum != target) return 0;
}
int diag1 = 0, diag2 = 0;
for (int i = 0; i < n; i++) {
diag1 += sq[i][i];
diag2 += sq[i][n - 1 - i];
}
return (diag1 == target && diag2 == target);
}
int main(void) {
int n;
printf("Enter n: ");
scanf("%d", &n);
int **sq = malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
sq[i] = malloc(n * sizeof(int));
for (int j = 0; j < n; j++) scanf("%d", &sq[i][j]);
}
printf(is_magic(sq, n) ? "Magic square.\n" : "Not a magic square.\n");
for (int i = 0; i < n; i++) free(sq[i]);
free(sq);
return 0;
}
Applying is_magic to the given 4×4 example: every row sums to 34 (16+3+2+13, 5+10+11+8, 9+6+7+12, 4+15+14+1), every column sums to 34, and both diagonals (16+10+7+1 and 13+11+6+4) sum to 34, so the check returns true.
| Quantity | Result |
|---|---|
| Target sum (row 0 of the example) | $\boxed{34}$ |
| All 4 rows, 4 columns, 2 diagonals | all equal 34 → magic square |
Time complexity of is_magic | $O(n^2)$ |