LearnFrenzy
Sign in Take a free test

Typedef · typedef Programs · Question 5

2×2 matrix type: multiplication and determinant in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Wrap a 2×2 matrix in a typedef'd struct so it can be returned by value, then multiply two matrices and compute a determinant.

Solution
main.c
#include <stdio.h>

typedef struct {
    int m[2][2];              /* in a struct, the array can be returned and copied */
} Mat2;

Mat2 mul(Mat2 a, Mat2 b) {
    Mat2 r = {{{0}}};
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            for (int k = 0; k < 2; k++)
                r.m[i][j] += a.m[i][k] * b.m[k][j];
    return r;
}

int det(Mat2 a) { return a.m[0][0] * a.m[1][1] - a.m[0][1] * a.m[1][0]; }

int main(void) {
    Mat2 a = {{{1, 2}, {3, 4}}}, swap = {{{0, 1}, {1, 0}}};
    Mat2 p = mul(a, swap);
    printf("%d %d\n%d %d\ndet(A) = %d\n", p.m[0][0], p.m[0][1], p.m[1][0], p.m[1][1], det(a));
    return 0;
}

Output Verified by compiling and running

2 1
4 3
det(A) = -2

A bare array typedef cannot be returned from a function, but a struct containing the array can. Multiplying by the swap matrix exchanges the columns; det = 1×4 − 2×3 = −2.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links