Describing Complex Data

Difficulty: ★ ★ ☆ ☆

I’ve written many C programming Lessons and Exercises that deal with matrixes. For most of them, such as rotating a matrix, I rely on uniform matrix sizes, like 5×5 or 10×10. This approach makes coding easier, but it doesn’t properly describe every type of matrix.

A matrix, or grid, contains rows and columns of data. Depending on what’s being described, the rows and columns can be different: 2×4, 8×16, 18×5. These are all valid matrix sizes, often expressed in C as a two-dimensional array:

alpha[2][4]
beta[8][16]
gamma[18][5]

Manipulating such an array involves brainwork, but things get dicey when passing these matrixes to a function. In my code, I often use a pointer as an argument. It’s easier to pass but still involves overhead when calculating row and column offsets.

A larger problem is how to inform a function of a matrix’s dimensions. Other programming languages may offer a method to obtain row and column values in a matrix — but in C you must come up with another way to describe this complex data, which is the topic of this month’s Exercise.

Your task is to output these two matrixes:

int matrix_a[12] = {
    10, 20, 30, 40,
    11, 21, 31, 41,
    12, 22, 32, 42
};
int matrix_b[4] = {
    1, 2,
    3, 4
};

Each matrix is declared in the main() function, but as a single-dimension array. What’s desired is a matrix as shown in the format: 4×3 and 2×2. These dimensions are how the matrixes should be treated, which is important.

In your solution you must code a function to output the matrixes as a grid. The matrix must be passed to the function as a single argument, a complex data type that describes the matrix’s dimensions and values.

Here is output from my solution:

Matrix A
  10   20   30   40 
  11   21   31   41 
  12   22   32   42 
Matrix B
   1    2 
   3    4 

I use two arguments for my version of output() function. The first contains the title string, such as “Matrix A” above. The second argument is the complex data type that describes the array, its contents and dimensions.

Please try this exercise on your own before checking out my solution.

2 thoughts on “Describing Complex Data

  1. The rows come first so A is 3×4.

    Matrices are usually printed with multi-row square brackets for which there’s a selection of Unicode characters.

    ⎡ 23A1
    ⎢ 23A2
    ⎣ 23A3

    and

    ⎤ 23A4
    ⎥ 23A5
    ⎦ 23A6

    If using these it’s necessary to pad numbers to the widest so they line up, although of course that only works with monospace fonts. Also, with a monospace font they usually join up to look like single brackets.

Leave a Reply