NivaarExam PrepOfficial exam papers ↗

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

Question 3 of 9: Programming — Magic Square Checker

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 3: Programming — Magic Square Checker (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 square size $n$ followed by $n^2$ integers read row by row.

Given 4×4 example
Row 1Row 2Row 3Row 4
16 3 2 135 10 11 89 6 7 124 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.

  1. Write the checker.
    #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;
    }
  2. Apply it to the paper's example. Row 0 sets the target: $$\text{target} = 16+3+2+13 = 34$$ $$\boxed{\text{target} = 34}$$ Every remaining row (5+10+11+8, 9+6+7+12, 4+15+14+1), every column (16+5+9+4, 3+10+6+15, 2+11+7+14, 13+8+12+1) and both diagonals (16+10+7+1, 13+11+6+4) also sum to 34, so the checker returns true.
Question 3 — results
QuantityResult
Target sum (row 0)34
All 4 rows, 4 columns, 2 diagonalsall equal 34 → magic square
Time complexity of is_magic$O(n^2)$