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