What is C Matrix Programs and Quiz- Free Embedded C Programming Course

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course · Arrays · Chapter Wrap-Up

C Matrix Programs and Quiz

Determinant, counting, flattening and symmetry checks, followed by a chapter quiz and interview questions on arrays.

Matrix programs in C close the arrays chapter of this free C programming course. You will compute a determinant, count how often a number occurs, flatten a 2-D array row by row and test whether a matrix is symmetric. Each program is original and tested. After the programs you get a ten-question quiz, three programming challenges and ten interview questions with answers, so you can check that you are ready for exams and for embedded C programming interviews.

Topics Covered

matrix programs in Cfree C tutorialdeterminant in CC interview questions arraysfree embedded C course

What You Will Learn

  • Computing a determinant with cofactor expansion and recursion.
  • Counting occurrences of a value in a two-dimensional array.
  • Storing a 2-D array in a 1-D array row-wise using an index formula.
  • Testing symmetry by comparing mirrored elements.
  • Self-testing with a quiz, challenges and common interview questions.

Prerequisites

  • Two-dimensional arrays, row and column indexing, and nested loops.
  • Functions that receive a 2-D array: all dimensions except the first must be given.
  • Basic recursion from the functions chapter.

Why Practise Matrix Programs in C

Matrix programs in C look mathematical, but they are really exercises in disciplined indexing. A matrix is stored in memory as one long row-major sequence, and every matrix program is just a different rule for walking over that sequence. Embedded engineers meet the same ideas in image buffers, keypad scanning, LED panels and sensor arrays. Solving matrix programs in C also reveals why array parameters need a fixed column count, how recursion uses the stack and why index mistakes cause silent corruption. Treat each program below as a template you can reuse in your own projects.

Program 1: Determinant of a Matrix

The determinant of a 1 × 1 matrix is its only value. For 2 × 2 it is a·d − b·c. For larger matrices expand along the first row: for each column, take the element, build the smaller matrix (minor) that remains after removing that row and column, multiply the element by the determinant of the minor, and alternate the signs plus and minus. A recursive function expresses this directly. The program uses a fixed maximum size of 4, because the cost grows factorially and large matrices need a different method.

Cofactor expansion along the first row
Pick column c of row 0
Build minor without row 0 and column c
Recurse on the smaller matrix
Multiply by element, sign plus for even c, minus for odd c
Add all terms

Program 2: Count Occurrences in a Matrix

Scan every element with two nested loops and increase a counter when the element equals the target. The loop cost is rows × columns, and no extra memory is needed.

Program 3: Store a 2-D Array Row-Wise in a 1-D Array

C stores a 2-D array in memory row after row. The element at row r and column c of a matrix with COLS columns therefore sits at index r * COLS + c in a flat array. The table shows the mapping for a 3 × 4 matrix.

RowColumn 0Column 1Column 2Column 3
0index 0index 1index 2index 3
1index 4index 5index 6index 7
2index 8index 9index 10index 11

Embedded drivers use this formula constantly, for example to address a pixel in a frame buffer stored as one long array.

Program 4: Is the Matrix Symmetric?

A square matrix is symmetric when it equals its transpose, which means every element m[r][c] equals m[c][r]. You only need to compare the elements above the diagonal with their mirror images below it, so start the inner loop at r + 1. Non-square matrices cannot be symmetric.

Complete Program: Matrix Programs in C

#include <stdio.h>

#define MAXN 4
#define ROWS 3
#define COLS 4

static long determinant(int n, int m[][MAXN])
{
    if (n == 1)
        return m[0][0];
    if (n == 2)
        return (long)m[0][0] * m[1][1] - (long)m[0][1] * m[1][0];

    long det = 0;
    for (int skip = 0; skip < n; skip++) {
        int minor[MAXN][MAXN];
        for (int r = 1; r < n; r++) {
            int mc = 0;
            for (int c = 0; c < n; c++) {
                if (c == skip)
                    continue;
                minor[r - 1][mc++] = m[r][c];
            }
        }
        long term = (long)m[0][skip] * determinant(n - 1, minor);
        det += (skip % 2 == 0) ? term : -term;
    }
    return det;
}

static int count_value(int m[][COLS], int target)
{
    int count = 0;
    for (int r = 0; r < ROWS; r++)
        for (int c = 0; c < COLS; c++)
            if (m[r][c] == target)
                count++;
    return count;
}

static void flatten_rowwise(int m[][COLS], int flat[])
{
    for (int r = 0; r < ROWS; r++)
        for (int c = 0; c < COLS; c++)
            flat[r * COLS + c] = m[r][c];
}

static int is_symmetric(int n, int m[][MAXN])
{
    for (int r = 0; r < n; r++)
        for (int c = r + 1; c < n; c++)
            if (m[r][c] != m[c][r])
                return 0;
    return 1;
}

int main(void)
{
    int a[MAXN][MAXN] = {{2, -1, 3}, {0, 4, 1}, {5, 2, -2}};
    int grid[ROWS][COLS] = {{4, 7, 4, 1}, {9, 4, 2, 7}, {4, 4, 8, 0}};
    int flat[ROWS * COLS];
    int sym[MAXN][MAXN] = {{1, 7, 3}, {7, 4, -5}, {3, -5, 6}};
    int notsym[MAXN][MAXN] = {{1, 2, 3}, {2, 4, 5}, {3, 6, 9}};

    printf("determinant of 3x3 = %ld\n", determinant(3, a));
    printf("count of 4 = %d, count of 7 = %d, count of 5 = %d\n",
           count_value(grid, 4), count_value(grid, 7), count_value(grid, 5));

    flatten_rowwise(grid, flat);
    printf("flattened:");
    for (int i = 0; i < ROWS * COLS; i++)
        printf(" %d", flat[i]);
    putchar('\n');

    printf("first matrix symmetric?  %s\n", is_symmetric(3, sym) ? "yes" : "no");
    printf("second matrix symmetric? %s\n", is_symmetric(3, notsym) ? "yes" : "no");
    return 0;
}
gcc -std=c11 -Wall -Wextra -o matrix_tasks matrix_tasks.c
./matrix_tasks

Output:

determinant of 3x3 = -85
count of 4 = 5, count of 7 = 2, count of 5 = 0
flattened: 4 7 4 1 9 4 2 7 4 4 8 0
first matrix symmetric?  yes
second matrix symmetric? no

Checking the Results by Hand

For the first matrix, expanding along row 0 gives 2 × (4 × −2 − 1 × 2) = −20, then +1 × (0 × −2 − 1 × 5) = −5, then 3 × (0 × 2 − 4 × 5) = −60, so the total is −85. The number 4 appears five times in the grid and 7 appears twice. The flattened list reads the grid row by row. The second matrix fails the test because the element in row 1, column 2 is 5 while its mirror in row 2, column 1 is 6.

Common Mistakes and Troubleshooting

MistakeEffectFix
Missing column size in a 2-D parameterCompile errorWrite int m[][COLS], never int m[][]
Wrong sign in cofactor expansionWrong determinantAlternate plus and minus by column index
Flat index r + c * COLSElements land in wrong placesUse r * COLS + c for row-wise storage
Comparing the full matrix for symmetryDouble workStart the inner loop at r + 1
int overflow in determinantsSilent wrong answerUse a wider type, as shown, and limit the size

Best Practices, Performance and Security

  • Cofactor expansion is O(n!), fine for 4 × 4 or less. Larger systems use elimination, which is O(n³).
  • Recursion uses stack space, so avoid it on very small microcontrollers or limit the depth, as the size cap does here.
  • Keep dimensions in named constants so you change them in one place.
  • Check that a flat buffer is at least rows × columns elements long before writing.

Chapter Quiz: Arrays in C

Try each question before opening the answer.

  1. What does int a[5] = {1, 2}; store in a[4]?
    Show answer

    0. Elements without an initialiser are set to zero.

  2. With a 4-byte int, what is the size of int m[3][4]?
    Show answer

    48 bytes, because 12 elements times 4 bytes.

  3. Which declaration is invalid? (A) int m[][3] = {{1}, {2}}; (B) int m[3][]; (C) int m[2][2] = {{1, 2}, {3, 4}}; (D) int m[] = {1, 2, 3};
    Show answer

    B. Only the first dimension may be left empty.

  4. Inside void f(int arr[]), what does sizeof(arr) return?
    Show answer

    The size of a pointer, not of the array.

  5. What is the worst-case time of bubble sort?
    Show answer

    O(n²).

  6. What must be true of an array before binary search?
    Show answer

    It must be sorted.

  7. In the 4 × 4 spiral matrix from this chapter, which number is at row 1, column 1?
    Show answer

    13.

  8. For a matrix with 4 columns stored row-wise in a flat array, which index holds m[2][1]?
    Show answer

    Index 9, from 2 × 4 + 1.

  9. When is a square matrix symmetric?
    Show answer

    When it equals its transpose, so m[r][c] equals m[c][r] for every pair.

  10. What does int a[3] = {5, 6, 7}; printf("%d", a[3]); do?
    Show answer

    Undefined behaviour, because valid indices are 0 to 2.

Programming Challenges

  1. Write a function that fills an n × n matrix in a counter-clockwise spiral.
  2. Print the sum of the main diagonal and the secondary diagonal of a square matrix, counting the centre once.
  3. Check whether a square matrix is an identity matrix: ones on the main diagonal and zeros elsewhere.

Embedded C Interview Questions on Arrays

  1. Why can a function not know the size of an array it receives?
    Show answer

    The array decays to a pointer to its first element, which carries no length. Pass the length separately.

  2. What is the difference between arr and &arr[0]?
    Show answer

    In an expression, arr decays to the address of its first element, so both give the same address with the same type.

  3. Where is a local array stored and why does it matter on a microcontroller?
    Show answer

    On the stack, which is small on a microcontroller. Large local arrays can overflow it, so make them static or global.

  4. How do you place a lookup table in flash?
    Show answer

    Declare it static const at file scope so the toolchain stores it in read-only memory.

  5. What is a buffer overflow in the context of arrays?
    Show answer

    Writing beyond the last element, which corrupts neighbouring data and can be exploited.

  6. Are variable-length arrays recommended in firmware?
    Show answer

    No. Their stack usage is unknown at build time, and most embedded coding standards forbid them.

  7. How do you pass a 2-D array to a function?
    Show answer

    Give every dimension except the first, for example int m[][COLS], plus the number of rows.

  8. How would you rotate an array without extra memory?
    Show answer

    Reverse the whole array, then reverse the first k elements and then the remainder.

  9. Why start the sieve inner loop at p times p?
    Show answer

    Smaller multiples were already removed by smaller primes.

  10. What are the risks of using size_t in a countdown loop?
    Show answer

    It is unsigned, so a condition such as i >= 0 is always true and the loop never ends. Count with i > 0 instead.

Summary

  • Determinants use recursion over minors, with alternating signs.
  • Row-wise flattening uses the index r * COLS + c.
  • Symmetry needs only the upper triangle compared with the lower one.
  • Arrays decay to pointers in functions, so always pass lengths.

Revisit these matrix programs in C after a few days and rewrite them without looking, because retrieval from memory is what builds exam speed. Pair them with the earlier spiral and sorting lectures and you will have a complete toolkit for array questions. You have now finished the arrays chapter of the free C programming course. Review the quiz you missed, solve the three challenges, and move on to the next chapter with confidence.

FAQ: Matrix Programs in C

How do I pass a 2-D array to a function in C?

Specify all dimensions except the first, such as int m[][COLS], and pass the row count separately.

How do I flatten a matrix row-wise?

Store element m[r][c] at flat index r times COLS plus c.

What is the quickest way to test symmetry?

Compare each element above the diagonal with its mirror below it and stop at the first mismatch.

Why limit the determinant program to small sizes?

Cofactor expansion costs factorial time, so it is only practical for tiny matrices. Larger ones need elimination.

Can a non-square matrix be symmetric?

No. Symmetry compares a matrix with its transpose, so the matrix must have equal rows and columns.

Keep Going With the Free C Programming Course

Every lecture in this free C tutorial for embedded systems is original, tested and written for beginners who want real embedded C programming skills. Move on to the next lecture or return to the course index.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *